openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
292 lines (291 loc) • 8.4 kB
JavaScript
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { l as makeZeroUsageSnapshot } from "./usage-CHLnzpJG.mjs";
import { r as WORKER_PROTOCOL_MAX_IDENTIFIER_LENGTH } from "./worker-protocol-constants-D1ohc92w.mjs";
import { n as isWorkerTranscriptMessageFrameSafe, t as WORKER_PROVIDER_REPLAY_LOCAL_RETRY_MESSAGE } from "./transcript-message-CX61ai-2.mjs";
import { c as invalidateComputerFrameIfMissing } from "./computer-tool-shared-DjAanHYO.mjs";
import { t as event_stream_exports } from "./event-stream-BvhxOtdO.mjs";
import { t as fitWorkerReplayImages } from "./replay-message-window-CjXgxm-q.mjs";
import { createToolArgumentPreviewSchedule, parseStreamingJson, parseTerminalToolCallArguments } from "@openclaw/ai/internal/runtime";
//#region src/worker/inference-stream.runtime.ts
function emptyAssistantMessage(e) {
return {
role: "assistant",
content: [],
api: "openai-responses",
provider: e.provider,
model: e.model,
stopReason: "stop",
usage: makeZeroUsageSnapshot(),
timestamp: Date.now()
};
}
function processInferenceEvent(e, t, n, r) {
const i = e.event;
switch (i.type) {
case "start":
t.api = i.resolvedModel.api;
t.provider = i.resolvedModel.provider;
t.model = i.resolvedModel.model;
t.timestamp = i.timestamp;
return {
type: "start",
partial: t
};
case "text_start":
t.content[i.contentIndex] = {
type: "text",
text: "",
...i.contentSignature === void 0 ? {} : { textSignature: i.contentSignature }
};
return {
type: "text_start",
contentIndex: i.contentIndex,
partial: t
};
case "text_delta":
case "text_end":
case "thinking_delta":
case "thinking_end": {
const e = t.content[i.contentIndex];
const n = i.type === "text_delta" || i.type === "text_end" ? "text" : "thinking";
const a = i.type === "text_delta" || i.type === "thinking_delta";
if (e?.type !== "text" && e?.type !== "thinking" || e.type !== n) {
if (r) return;
throw new Error(`worker inference ${n} ${a ? "delta" : "end"} has no active ${n} block`);
}
if (a) {
if (e.type === "text") e.text += i.delta;
else e.thinking += i.delta;
return {
type: i.type,
contentIndex: i.contentIndex,
delta: i.delta,
partial: t
};
}
if (i.contentSignature !== void 0) {
if (e.type === "text") e.textSignature = i.contentSignature;
else e.thinkingSignature = i.contentSignature;
}
return {
type: i.type,
contentIndex: i.contentIndex,
content: e.type === "text" ? e.text : e.thinking,
partial: t
};
}
case "thinking_start":
t.content[i.contentIndex] = {
type: "thinking",
thinking: ""
};
return {
type: "thinking_start",
contentIndex: i.contentIndex,
partial: t
};
case "toolcall_start": {
const e = {
type: "toolCall",
id: i.id,
name: i.toolName,
arguments: {},
partialJson: ""
};
t.content[i.contentIndex] = e;
n.set(i.contentIndex, createToolArgumentPreviewSchedule());
return {
type: "toolcall_start",
contentIndex: i.contentIndex,
partial: t
};
}
case "toolcall_delta":
case "toolcall_end": {
const e = t.content[i.contentIndex];
if (e?.type !== "toolCall") {
if (r) return;
throw new Error(`worker inference tool ${i.type === "toolcall_delta" ? "delta" : "end"} has no active tool call`);
}
if (i.type === "toolcall_delta") {
const r = (e.partialJson ?? "") + i.delta;
e.partialJson = r;
const a = n.get(i.contentIndex);
if (!a) throw new Error("worker inference tool delta has no preview schedule");
if (a(r.length)) e.arguments = parseStreamingJson(r);
return {
type: "toolcall_delta",
contentIndex: i.contentIndex,
delta: i.delta,
partial: t
};
}
e.arguments = parseTerminalToolCallArguments(e.partialJson);
n.delete(i.contentIndex);
delete e.partialJson;
return {
type: "toolcall_end",
contentIndex: i.contentIndex,
toolCall: e,
partial: t
};
}
}
}
function transcriptSafeErrorMessage(e, t) {
if (isWorkerTranscriptMessageFrameSafe(t)) return t;
const n = emptyAssistantMessage(e);
n.api = t.api;
n.provider = t.provider;
n.model = t.model;
n.timestamp = t.timestamp;
n.stopReason = t.stopReason === "aborted" ? "aborted" : "error";
n.errorMessage = truncateUtf16Safe(t.errorMessage ?? "Worker inference result exceeds the transcript message limit.", 256);
n.usage = t.usage;
n.retryAfterMs = t.retryAfterMs;
return n;
}
function createInferenceRequestMeasure(e) {
const measureFull = (t) => Buffer.byteLength(JSON.stringify({
type: "req",
id: "00000000-0000-4000-8000-000000000000",
method: "worker.inference.start",
params: {
...e,
context: {
...e.context,
messages: t
}
}
}), "utf8");
let t = 0;
let n;
return (r) => {
if (r === e.context.messages) return measureFull(r);
if (!n) {
t = measureFull([]);
n = /* @__PURE__ */ new WeakMap();
}
let i = t + Math.max(0, r.length - 1);
for (const e of r) {
let t = n.get(e);
if (t === void 0) {
t = Buffer.byteLength(JSON.stringify(e), "utf8");
n.set(e, t);
}
i += t;
}
return i;
};
}
function createWorkerInferenceStreamAdapter(e) {
let t = 0;
return (n) => {
const r = (0, event_stream_exports.createAssistantMessageEventStream)();
const i = emptyAssistantMessage(e.modelRef);
const a = /* @__PURE__ */ new Map();
let o = false;
let s = false;
t += 1;
const c = `:${t}`;
const l = {
runEpoch: e.runEpoch,
sessionId: e.sessionId,
runId: e.runId,
turnId: `${e.turnId.slice(0, 256 - c.length)}${c}`
};
let u = {
...l,
modelRef: n.modelRef,
context: n.context,
options: n.options
};
const finishError = (t, n, a, o) => {
if (s) return;
s = true;
i.stopReason = n;
i.errorMessage = t instanceof Error ? t.message : String(t);
i.retryAfterMs = o;
if (a) i.usage = a;
r.push({
type: "error",
reason: n,
error: transcriptSafeErrorMessage(e.modelRef, i)
});
r.end();
};
const fail = (e) => finishError(e, n.signal?.aborted ? "aborted" : "error");
const abort = () => {
e.client.cancel(l).catch(() => void 0).finally(() => finishError("Worker inference aborted.", "aborted"));
};
if (n.signal?.aborted) {
finishError("Worker inference aborted before start.", "aborted");
return r;
}
try {
const t = fitWorkerReplayImages(u.context.messages, createInferenceRequestMeasure(u), e.computerContextEpoch?.frameToolCallId);
if (!t) throw new Error(u.context.messages.some((e) => e.role === "assistant" && e.providerReplay !== void 0) ? `${WORKER_PROVIDER_REPLAY_LOCAL_RETRY_MESSAGE} (inference payload limit)` : "Worker inference context exceeds the image transport limit. Use fewer or smaller images in this turn, then retry.");
u = {
...u,
context: {
...u.context,
messages: t
}
};
if (e.computerContextEpoch) invalidateComputerFrameIfMissing({
contextEpoch: e.computerContextEpoch,
messages: t.filter((e) => e.role === "toolResult")
});
} catch (e) {
fail(e);
return r;
}
n.signal?.addEventListener("abort", abort, { once: true });
e.client.start(u, {
onStreamGap: () => {
o = true;
},
onEvent: (e) => {
const t = processInferenceEvent(e, i, a, o);
if (t) r.push(t);
}
}).then((t) => {
if (s) return;
if (t.type === "done") {
s = true;
if (!isWorkerTranscriptMessageFrameSafe(t.message)) {
const n = emptyAssistantMessage(e.modelRef);
n.stopReason = "error";
n.errorMessage = "Worker inference result exceeds the transcript message limit.";
n.usage = t.message.usage;
r.push({
type: "error",
reason: "error",
error: n
});
r.end();
return;
}
const n = t.message.stopReason;
const i = t.message;
r.push({
type: "done",
reason: n,
message: i
});
r.end();
return;
}
if (t.reason === "cancelled") {
n.signal?.removeEventListener("abort", abort);
e.onCancelled?.(new Error(t.message));
}
finishError(t.message, t.reason === "cancelled" ? "aborted" : "error", t.usage, t.retryAfterMs);
}).catch(fail).finally(() => {
n.signal?.removeEventListener("abort", abort);
});
return r;
};
}
//#endregion
export { createWorkerInferenceStreamAdapter };