openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
590 lines (589 loc) • 20.9 kB
JavaScript
import { l as asNonNegativeFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { a as captureAsyncWorkTracker } from "./async-work-scope-BXagjUap.mjs";
import { I as hasInternalDiagnosticEventInterest, R as hasModelCallPromptStatsInterest, S as hasDiagnosticTracePropagationConsumer, t as areDiagnosticsEnabledForProcess, x as formatPropagatedDiagnosticTraceparent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { h as createChildDiagnosticTraceContext, l as modelUsageTimelineAttributes, n as emitDiagnosticsTimelineEvent, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { d as normalizeUsage, r as derivePromptTokens } from "./usage-CHLnzpJG.mjs";
import { l as getAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { a as emitAgentEvent } from "./agent-events-BdfWYmot.mjs";
import { h as recordReasoningSuppressedDiagnostic } from "./diagnostic-runtime-BxwnWXDu.mjs";
import { n as isOwnedTranscriptPayload } from "./transcript-json-Cy82tIe1.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { f as fireAndForgetBoundedHook } from "./hooks-BiZpB_10.mjs";
import { b as emitCoreModelRequestStartedDiagnosticEvent, v as emitCoreSemanticRunProgressDiagnosticEvent, y as emitCoreModelRequestEndedDiagnosticEvent } from "./diagnostic-run-activity-BzWz2WN_.mjs";
import { t as cloneDiagnosticContentValue } from "./diagnostic-llm-content-CvUZCA61.mjs";
import { a as diagnosticProviderRequestIdHash, i as diagnosticHttpStatusCode, n as diagnosticErrorFailureKind, t as diagnosticErrorCategory } from "./diagnostic-error-metadata-Cc4dyoSL.mjs";
import { t as log } from "./logger-DgCpB-Fs.mjs";
import { i as withModelTransportContext } from "./ai-transport-host-DfBOurnI.mjs";
import { t as createModelCallStreamProgressReporter } from "./diagnostic-model-stream-progress-D2GjiTSb.mjs";
import { modelRequestBodyState } from "@openclaw/ai/internal/model-request-body";
import { withProviderAcceptanceObserver } from "@openclaw/ai/transports";
//#region src/agents/embedded-agent-runner/run/attempt.model-diagnostic-lifecycle.ts
const TRACEPARENT_HEADER_NAME = "traceparent";
const TIMELINE_ATTRIBUTE_MAX_LENGTH = 256;
function modelContentPrivateData(e) {
return e ? { modelContent: e } : void 0;
}
function isModelOutputDelta(e) {
return isRecord(e) && (e.type === "text_delta" || e.type === "thinking_delta" || e.type === "toolcall_delta") && typeof e.delta === "string" && e.delta.length > 0;
}
function boundedTimelineAttribute(e) {
return truncateUtf16Safe(e?.trim() ?? "", TIMELINE_ATTRIBUTE_MAX_LENGTH) || void 0;
}
function modelCallErrorFields(e) {
const t = diagnosticProviderRequestIdHash(e);
const n = diagnosticErrorFailureKind(e);
return {
errorCategory: diagnosticErrorCategory(e),
...n ? {
failureKind: n,
memory: processMemoryUsageSnapshot()
} : {},
...t ? { upstreamRequestIdHash: t } : {}
};
}
function processMemoryUsageSnapshot() {
try {
const e = process.memoryUsage();
return {
rssBytes: e.rss,
heapTotalBytes: e.heapTotal,
heapUsedBytes: e.heapUsed,
externalBytes: e.external,
arrayBuffersBytes: e.arrayBuffers
};
} catch {
return;
}
}
const modelCallContextBudget = (e) => ({
...e.contextTokenBudget ? { contextTokenBudget: e.contextTokenBudget } : {},
...e.contextWindowSource ? { contextWindowSource: e.contextWindowSource } : {},
...e.contextWindowReferenceTokens ? { contextWindowReferenceTokens: e.contextWindowReferenceTokens } : {}
});
function modelCallHookEventBase(e) {
return {
runId: e.runId,
callId: e.callId,
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...e.sessionId ? { sessionId: e.sessionId } : {},
provider: e.provider,
model: e.model,
...e.api ? { api: e.api } : {},
...e.transport ? { transport: e.transport } : {},
...modelCallContextBudget(e)
};
}
function dispatchModelCallHook(e, t) {
const n = getGlobalHookRunner();
const r = t ? "model_call_ended" : "model_call_started";
if (!n?.hasHooks(r)) return;
const i = Object.freeze(modelCallHookEventBase(e));
const a = Object.freeze({
runId: e.runId,
...e.agentId ? { agentId: e.agentId } : {},
trace: e.trace,
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...e.sessionId ? { sessionId: e.sessionId } : {},
modelProviderId: e.provider,
modelId: e.model,
...modelCallContextBudget(e)
});
fireAndForgetBoundedHook(() => t ? n.runModelCallEnded(Object.freeze({
...i,
...t
}), a) : n.runModelCallStarted(i, a), `${r} plugin hook failed`);
}
function createModelLifecycle(e) {
const t = e.ctx.nextCallId();
const n = getAgentRunContext(e.ctx.runId);
const r = {
sessionKey: e.ctx.sessionKey,
runId: e.ctx.runId,
requestId: t,
priority: e.ctx.priority,
onRateLimitWait: (e) => {
const t = Math.max(0, e - Date.now());
reportStatus({
phase: "retrying",
reason: "rate_limit",
message: `Waiting for rate limit. Retrying in ${Math.ceil(t / 1e3)}s.`,
delayMs: t,
retryAt: e
});
return () => reportStatus({ phase: "starting_model" });
}
};
const i = freezeDiagnosticTraceContext(createChildDiagnosticTraceContext(e.ctx.trace));
const a = e.createObserver(areDiagnosticsEnabledForProcess() && hasModelCallPromptStatsInterest(), areDiagnosticsEnabledForProcess() && (hasInternalDiagnosticEventInterest("model.call.completed", true) || hasInternalDiagnosticEventInterest("model.call.error", true) || hasDiagnosticTracePropagationConsumer()) || e.ctx.suppressPluginHooks !== true && getGlobalHookRunner()?.hasHooks("model_call_ended") === true);
const o = {
...modelCallHookEventBase({
...e.ctx,
callId: t
}),
...e.ctx.agentId ? { agentId: e.ctx.agentId } : {},
observationUnit: "request",
...a.promptStats ? { promptStats: a.promptStats } : {},
trace: i
};
const s = e.ctx.diagnosticOwner?.watchdogAttempt;
const c = createModelCallStreamProgressReporter({
config: e.ctx.config,
target: o,
recordProgress: s ? () => s.progress("transport", "model_call:stream_progress") : void 0
});
emitCoreModelRequestStartedDiagnosticEvent(o, e.ctx.ownerGeneration, e.requestTimeoutMs, modelContentPrivateData(a.modelContent));
if (e.ctx.suppressPluginHooks !== true) dispatchModelCallHook(o);
const l = Date.now();
emitDiagnosticsTimelineEvent({
type: "mark",
name: "provider.request.started",
timestamp: new Date(l).toISOString(),
runId: o.runId,
spanId: t,
provider: o.provider,
attributes: {
model: o.model,
observationUnit: "logical-call",
...o.sessionId ? { sessionId: o.sessionId } : {},
traceId: i.traceId
}
}, { config: e.ctx.config });
const u = e.options;
const d = e.ctx;
const f = formatPropagatedDiagnosticTraceparent(i);
const p = u?.onPayload;
const m = u?.onResponse;
const onPayload = (e, t) => {
const n = modelRequestBodyState(g);
if (n.enabled || n.reportsBytes) return p?.(e, t);
if (!p) {
a.assignRequestPayloadBytes(e);
return;
}
const r = p(e, t);
const observeReplacement = (t) => {
a.assignRequestPayloadBytes(t ?? e);
return t;
};
return isPromiseLike(r) ? r.then(observeReplacement) : observeReplacement(r);
};
const onResponse = (e, t) => {
if (!a.state.terminalEventEmitted) {
a.state.responseStatus = e.status;
a.state.lastProviderActivityAtMs = Date.now();
}
return m?.(e, t);
};
const h = {};
for (const [e, t] of Object.entries(u?.headers ?? {})) {
if (e.toLowerCase() === TRACEPARENT_HEADER_NAME) continue;
h[e] = t;
}
if (f) h[TRACEPARENT_HEADER_NAME] = f;
const g = {
...u,
requestId: t,
...(u?.headers || f) && { headers: h },
onPayload,
onResponse
};
modelRequestBodyState(g).onBytes = (e) => {
a.state.requestPayloadBytes = e;
emitDiagnosticsTimelineEvent({
type: "mark",
name: "provider.request.serialized",
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
runId: d.runId,
spanId: t
}, { config: d.config });
};
const _ = withProviderAcceptanceObserver(g, (e) => {
if (a.state.terminalEventEmitted) return;
a.state.lastProviderActivityAtMs = Date.now();
a.state.providerAcceptanceKind = e.kind;
if (e.kind === "http_response") a.state.responseStatus = e.status;
});
let v = null;
let y = false;
const b = captureAsyncWorkTracker();
const x = e.options?.signal;
function reportStatus(t) {
const n = {
stream: "run_status",
data: t
};
emitAgentEvent({
runId: e.ctx.runId,
sessionKey: e.ctx.sessionKey,
...n
});
if (e.ctx.onAgentEvent) b(async () => {
try {
await e.ctx.onAgentEvent?.(n);
} catch {
log.warn("Provider wait status delivery failed");
}
});
}
const reportWait = (r) => {
if (r === v || r !== null && (y || x?.aborted || a.state.terminalEventEmitted)) return;
v = r;
if (n) {
if (r) n.localModelWait = { requestId: t };
else if (n.localModelWait?.requestId === t) delete n.localModelWait;
}
reportStatus(r ? {
phase: "waiting_for_model",
reason: r
} : { phase: "starting_model" });
e.options?.onProviderWait?.(r);
};
const clearWait = () => reportWait(null);
_.onProviderWait = reportWait;
x?.addEventListener("abort", clearWait, { once: true });
function emitModelCallEnded(t) {
const { ownerGeneration: n, config: r } = e.ctx;
if (a.state.reasoningSuppressed) {
const e = recordReasoningSuppressedDiagnostic({
sessionKey: o.sessionKey,
sessionId: o.sessionId ?? (o.sessionKey ? void 0 : o.runId)
}, o.provider, o.model);
if (e) log.warn(e);
}
if (a.state.terminalEventEmitted) return;
clearWait();
x?.removeEventListener("abort", clearWait);
a.state.terminalEventEmitted = true;
const s = Date.now();
const c = s - l;
const u = a.state.providerProcessingMs === void 0 ? {} : {
providerProcessingMs: a.state.providerProcessingMs,
providerWaitEstimateMs: Math.max(0, c - a.state.providerProcessingMs)
};
const d = a.sizeTimingFields();
const f = t ? modelCallErrorFields(t.error) : void 0;
const p = f ? {
type: "model.call.error",
...f
} : { type: "model.call.completed" };
const m = t ? diagnosticHttpStatusCode(t.error) : void 0;
const h = a.state.responseStatus ?? (m === void 0 ? void 0 : Number(m));
const g = t ? a.state.terminalReason === "aborted" ? "aborted" : f?.failureKind ?? "error" : a.state.terminalReason ?? "unknown";
const { providerAcceptanceKind: _ } = a.state;
const v = boundedTimelineAttribute(o.provider);
const y = boundedTimelineAttribute(o.model);
const b = boundedTimelineAttribute(o.api);
const S = boundedTimelineAttribute(o.transport);
emitDiagnosticsTimelineEvent({
type: "provider.request",
name: "provider.request",
timestamp: new Date(l).toISOString(),
runId: o.runId,
spanId: o.callId,
durationMs: c,
provider: v,
operation: b ?? S ?? "model.call",
ok: t === void 0,
...h !== void 0 ? { status: h } : {},
attributes: {
observationUnit: "logical-call",
...modelUsageTimelineAttributes(a.terminalFields().usage),
...a.state.responseModel ? { responseModel: a.state.responseModel } : {},
...o.sessionId ? { sessionId: o.sessionId } : {},
traceId: i.traceId,
...y ? { model: y } : {},
...b ? { api: b } : {},
...S ? { transport: S } : {},
terminalAtMs: s,
...u,
...a.state.lastProviderActivityAtMs !== void 0 ? { lastProviderActivityAtMs: a.state.lastProviderActivityAtMs } : {},
terminalReason: g,
providerAccepted: _ !== void 0,
..._ ? { providerAcceptanceKind: _ } : {}
}
}, { config: r });
emitCoreModelRequestEndedDiagnosticEvent({
...p,
...o,
durationMs: c,
...u,
...d,
...a.terminalFields()
}, n, modelContentPrivateData(a.completedContent()));
if (!a.state.suppressPluginHooks) dispatchModelCallHook(o, {
durationMs: c,
outcome: t ? "error" : "completed",
...d,
...f
});
}
let S = false;
let C = false;
const notifyFinished = () => {
if (!C) {
C = true;
r.onRateLimitWait = void 0;
clearWait();
x?.removeEventListener("abort", clearWait);
e.ctx.onFinished?.(t);
}
};
try {
e.ctx.onStarted?.(t);
} catch (e) {
notifyFinished();
throw e;
}
return {
eventBase: o,
observer: a,
propagatedOptions: _,
runInTransportContext(e) {
return withModelTransportContext(r, e);
},
startedAt: l,
observeChunk(n) {
y = true;
clearWait();
a.observeResponseChunk(l, n);
c(a.state.terminalEventEmitted ? void 0 : t);
if (e.ctx.onOutputDelta && isModelOutputDelta(n)) e.ctx.onOutputDelta();
},
emitCompleted() {
try {
if (!S && (a.state.terminalSucceeded || a.state.terminalError)) {
S = true;
e.ctx.onTerminal?.();
if (a.state.terminalSucceeded && !a.state.terminalError) e.ctx.onSucceeded?.(l);
}
emitModelCallEnded(a.state.terminalError ? { error: a.state.terminalError } : void 0);
} finally {
notifyFinished();
}
},
emitError(e) {
try {
emitModelCallEnded({ error: e });
} finally {
notifyFinished();
}
}
};
}
//#endregion
//#region src/agents/embedded-agent-runner/run/attempt.model-diagnostic-observation.ts
const MODEL_CALL_SEMANTIC_PROGRESS_REASON = "model_call:semantic_result";
function jsonLength(e, t, n) {
try {
let r = 0;
const i = JSON.stringify(e, function(e, i) {
if (!t && n && i !== null && typeof i === "object" && isOwnedTranscriptPayload(i)) {
const e = n.owned.get(i) ?? jsonLength(i, false);
if (e !== void 0) {
n.owned.set(i, e);
r += e - 2;
return "";
}
}
if (typeof i !== "string" || i.length < 4096) return i;
const a = !t ? n?.previous.get(e)?.get(this) : void 0;
let o = a?.text === i ? a.chars : void 0;
if (o === void 0) {
const e = JSON.stringify(i);
o = (t ? Buffer.byteLength(e, "utf8") : e.length) - 2;
}
if (!t && n) {
const t = n.current.get(e) ?? /* @__PURE__ */ new WeakMap();
t.set(this, a?.text === i ? a : {
text: i,
chars: o
});
n.current.set(e, t);
}
r += o;
return "";
});
return i === void 0 ? void 0 : r + (t ? Buffer.byteLength(i, "utf8") : i.length);
} catch {
return;
}
}
function responseStreamChunkByteLength(e) {
try {
if (!isRecord(e)) return jsonLength(e, true);
const t = e.type;
if ((t === "text_delta" || t === "thinking_delta" || t === "toolcall_delta") && typeof e.delta === "string") return Buffer.byteLength(e.delta, "utf8");
if (!("partial" in e)) return jsonLength(e, true);
const { partial: n, ...r } = e;
return jsonLength(r, true);
} catch {
return;
}
}
function streamContextModelContentFields(e, t) {
if (!e?.anyModelContent) return;
const n = {
...e.inputMessages && t.messages ? { inputMessages: cloneDiagnosticContentValue(t.messages) } : {},
...e.systemPrompt && t.systemPrompt !== void 0 ? { systemPrompt: t.systemPrompt } : {},
...e.toolDefinitions && t.tools ? { toolDefinitions: cloneDiagnosticContentValue(t.tools) } : {}
};
return Object.keys(n).length > 0 ? n : void 0;
}
function createModelPromptStats() {
let e = /* @__PURE__ */ new Map();
const t = /* @__PURE__ */ new WeakMap();
return (n) => {
const r = /* @__PURE__ */ new Map();
const i = streamContextModelPromptStats(n, {
previous: e,
current: r,
owned: t
});
e = r;
return i;
};
}
function streamContextModelPromptStats(e, t) {
const { messages: n, tools: r, systemPrompt: i } = e;
const a = n ? jsonLength(n, false, t) : void 0;
const o = r ? jsonLength(r, false, t) : void 0;
const s = i?.length;
if (n === void 0 && r === void 0 && i === void 0) return;
const c = (a ?? 0) + (s ?? 0) + (o ?? 0);
return {
...n ? { inputMessagesCount: n.length } : {},
...a !== void 0 ? { inputMessagesChars: a } : {},
...s !== void 0 ? { systemPromptChars: s } : {},
...r ? { toolDefinitionsCount: r.length } : {},
...o !== void 0 ? { toolDefinitionsChars: o } : {},
totalChars: c
};
}
function observeModelCallTerminalMessage(e, t) {
if (!isRecord(t)) return;
let n;
try {
n = t.usage;
const r = t.responseModel;
if (typeof r === "string" && r.trim()) e.responseModel = r.trim();
e.reasoningSuppressed ||= t.role === "assistant" && Array.isArray(t.diagnostics) && t.diagnostics.some((e) => isRecord(e) && e.type === "reasoning_suppressed");
const i = Array.isArray(t.diagnostics) ? t.diagnostics.findLast((e) => isRecord(e) && e.type === "provider_timing") : void 0;
if (isRecord(i) && isRecord(i.details)) e.providerProcessingMs = asNonNegativeFiniteNumber(i.details.processingMs);
const a = t.stopReason;
if (t.role === "assistant" && (a === "stop" || a === "length" || a === "toolUse")) {
e.terminalSucceeded = true;
e.terminalReason = a;
}
if (t.role === "assistant" && (a === "error" || a === "aborted")) {
e.terminalReason = a;
e.terminalError ??= Object.assign(new Error(typeof t.errorMessage === "string" ? t.errorMessage : a), { code: a === "aborted" ? "ABORT_ERR" : t.errorCode });
}
} catch {
return;
}
const r = isRecord(n) ? normalizeUsage(n) : void 0;
if (r) {
const t = derivePromptTokens(r);
e.usage = {
...r,
...t !== void 0 ? { promptTokens: t } : {}
};
}
}
function observeOutputMessageContent(e, t) {
if (!isRecord(t)) return;
let n;
try {
const e = t.type;
n = e === "done" ? t.message : e === "error" ? t.error : void 0;
} catch {
return;
}
if (n !== void 0) {
observeModelCallTerminalMessage(e, n);
if (e.contentCapture?.outputMessages) e.outputMessages = [cloneDiagnosticContentValue(n)];
}
}
function observeModelResponse(e, t, n, r, i) {
if (!e.terminalEventEmitted && (r === "chunk" || e.terminalReason === void 0)) e.lastProviderActivityAtMs = Date.now();
e.timeToFirstByteMs ??= Math.max(0, Date.now() - t);
if (r === "chunk") observeOutputMessageContent(e, n);
else {
observeModelCallTerminalMessage(e, n);
if (e.contentCapture?.outputMessages && e.outputMessages === void 0) e.outputMessages = [cloneDiagnosticContentValue(n)];
}
if (i && (r === "chunk" || e.responseStreamBytes === 0)) {
const t = r === "chunk" ? responseStreamChunkByteLength(n) : jsonLength(n, true);
if (t !== void 0) e.responseStreamBytes += t;
}
}
function isNormalizedToolCall(e) {
if (!isRecord(e) || e.type !== "toolCall") return false;
return typeof e.id === "string" && e.id.trim().length > 0 && typeof e.name === "string" && e.name.trim().length > 0 && isRecord(e.arguments);
}
function isSemanticModelCallResult(e) {
try {
if (!isRecord(e) || e.role !== "assistant" || e.stopReason === "error" || e.stopReason === "aborted" || !Array.isArray(e.content)) return false;
return e.stopReason === "toolUse" && e.content.some(isNormalizedToolCall) || e.content.some((e) => isRecord(e) && e.type === "text" && typeof e.text === "string" && e.text.trim().length > 0);
} catch {
return false;
}
}
function createModelObserver(e) {
const t = streamContextModelContentFields(e.contentCapture, e.streamContext);
const n = e.capturePromptStats ? (e.measurePromptStats ?? streamContextModelPromptStats)(e.streamContext) : void 0;
const r = {
responseStreamBytes: 0,
modelContent: t,
contentCapture: e.contentCapture,
suppressPluginHooks: e.suppressPluginHooks
};
return {
state: r,
promptStats: n,
modelContent: t,
assignRequestPayloadBytes(t) {
const n = e.captureByteStats ? jsonLength(t, true) : void 0;
if (n !== void 0) r.requestPayloadBytes = n;
},
observeResponseChunk(t, n) {
observeModelResponse(r, t, n, "chunk", e.captureByteStats);
},
observeFinalResult(t, n, i) {
observeModelResponse(r, n, i, "result", e.captureByteStats);
if (!r.semanticProgressEmitted && isSemanticModelCallResult(i)) {
r.semanticProgressEmitted = true;
emitCoreSemanticRunProgressDiagnosticEvent({
runId: t.runId,
...t.sessionKey ? { sessionKey: t.sessionKey } : {},
...t.sessionId ? { sessionId: t.sessionId } : {},
reason: MODEL_CALL_SEMANTIC_PROGRESS_REASON
}, e.diagnosticOwner);
}
},
sizeTimingFields() {
return {
...r.requestPayloadBytes !== void 0 ? { requestPayloadBytes: r.requestPayloadBytes } : {},
...r.responseStreamBytes > 0 ? { responseStreamBytes: r.responseStreamBytes } : {},
...r.timeToFirstByteMs !== void 0 ? { timeToFirstByteMs: r.timeToFirstByteMs } : {}
};
},
completedContent() {
return r.modelContent || r.outputMessages ? {
...r.modelContent,
...r.outputMessages ? { outputMessages: r.outputMessages } : {}
} : void 0;
},
terminalFields() {
return {
...r.usage ? { usage: r.usage } : {},
...r.responseModel ? { responseModel: r.responseModel } : {}
};
}
};
}
//#endregion
export { createModelPromptStats as n, createModelLifecycle as r, createModelObserver as t };