openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,916 lines • 91.7 kB
JavaScript
import { E as parseStrictNonNegativeInteger, L as resolvePositiveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { m as toStringifiedError, n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import { n as estimateStringChars, t as CHARS_PER_TOKEN_ESTIMATE } from "./cjk-chars-CgnWl5qA.mjs";
import { n as ok, t as err } from "./result-CV1-31DB.mjs";
import { i as isLocalStorageOutcomeError } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { l as makeZeroUsageSnapshot } from "./usage-CHLnzpJG.mjs";
import { i as isSqliteTranscriptMutationConflict } from "./session-mutation-conflict-error-DsnM4Ef8.mjs";
import { h as runPluginStreamConsumer } from "./plugin-instance-scope-oezVdCr2.mjs";
import { a as REPETITIVE_OUTPUT_ERROR_CODE, r as PROVIDER_FAILURE_WITH_OUTPUT_ERROR_CODE } from "./types-iq-cNLsd.mjs";
import { E as takeInternalToolBatchLifecycle, S as getInternalToolTurnInputScope, _ as getInternalSyncSteeringGetter, a as attachInternalSyncSteeringGetter, d as commitInternalToolTurnInput, g as getInternalSteeringQueueObserver, h as getInternalRepetitionGuard, i as attachInternalSteeringQueueObserver, m as getInternalBeforeToolBatch, p as copyInternalToolResultState, r as appendToolLoopWarning, t as InternalToolLoopBlocked, v as getInternalToolExecutionPreparer, x as getInternalToolTurnCompletion, y as getInternalToolResultContentSource } from "./internal-hooks-Ch3rqxs-.mjs";
import { i as orderSystemUpdateMessages, r as isOpenClawSystemUpdateMessage } from "./operator-messages-B9HgXnnQ.mjs";
import { o as convertToLlm } from "./messages-MSizso-z.mjs";
import { a as projectSessionEntryMessage } from "./session-BC1-SoD4.mjs";
import "./llm-Bp_VCUmP.mjs";
import { t as validateToolArguments } from "./src-DFw9QOgs.mjs";
import "./truncate-DCXARhAL.mjs";
import { _ as mergeSummaryFileOperations, c as createFileOps, d as extractFileOpsFromMessage, g as formatFileOperations, p as extractSummaryText, s as computeFileLists, y as serializeConversation } from "./compaction-cut-point-CEj7MSFJ.mjs";
import "./http-body-B9w7rzPz.mjs";
import { r as withResponseBodyTimeout } from "./http-response-body-timeout-BomM6jjh.mjs";
import { i as readResponseWithLimit } from "./http-response-body-B-i_0116.mjs";
import "./validation-Dt-LkqDC.mjs";
import { t as uuidv7 } from "./uuid-DOBT3ORq.mjs";
import { t as BranchSummaryError } from "./types-CD5C4AET.mjs";
import { a as ToolArgumentValidationError, n as REPEATED_TOOL_ERROR_MESSAGE, o as TranscriptNotContinuableError, r as REPETITIVE_OUTPUT_ERROR_MESSAGE, t as REPEATED_TOOL_ERROR_CODE } from "./errors-D_CW6sfd.mjs";
import { S as resolveAgentReasoningOption, _ as createSummarizationContext, b as resolveAgentCoreStreamFn, g as SUMMARIZATION_SYSTEM_PROMPT, p as buildSummaryCheckpointPrompt, v as consumeAgentCoreStream, x as runAgentCoreStream, y as resolveAgentCoreCompleteFn } from "./compaction-z9gtIF8y.mjs";
import { a as resolveAgentAssistantTurnId, o as runWithAgentToolExecutionContext, t as captureAgentToolInputScope } from "./tool-execution-context-D0eUSg2-.mjs";
import { t as event_stream_exports } from "./event-stream-BvhxOtdO.mjs";
import { i as streamSimple, n as completeSimple } from "./stream-DEhzhrZ_.mjs";
import { isResponsesOutputLimitToolCallError } from "@openclaw/ai/diagnostics";
import { prepareSystemPrompt } from "@openclaw/ai/internal/shared";
import { createToolArgumentPreviewSchedule, parseStreamingJson, parseTerminalToolCallArguments } from "@openclaw/ai/internal/runtime";
import { createEmptyTransportUsage, replaceCompactionReplayOwnerContent } from "@openclaw/ai/transports";
//#region packages/llm-core/src/utils/assistant-message-events.ts
function appendTextDeltaToAssistantMessage(e, t, n) {
const r = [...e.content];
const i = r[t];
r[t] = i?.type === "text" ? {
...i,
text: i.text + n
} : {
type: "text",
text: n
};
return {
...e,
content: r
};
}
//#endregion
//#region packages/agent-core/src/agent-loop-steering.ts
function getSteeringAtCheckpoint(e) {
const t = e.getSteeringMessages;
if (!t) return [];
return getInternalSyncSteeringGetter(t)?.() ?? t.call(e);
}
function createStreamedSteeringConfig(e) {
let t;
const n = {
...e,
getSteeringMessages: async () => {
if (t) return t;
const n = getSteeringAtCheckpoint(e);
if (Array.isArray(n)) {
if (n.length > 0) t = Promise.resolve(n);
return n;
}
const r = t = n;
const i = await r;
if (i.length === 0 && t === r) t = void 0;
return i;
}
};
if (n.getSteeringMessages) attachInternalSteeringQueueObserver(n.getSteeringMessages, getInternalSteeringQueueObserver(e.getSteeringMessages));
return {
config: n,
getTerminalConfig: () => t ? n : e
};
}
//#endregion
//#region packages/agent-core/src/tool-batch-completion.ts
/** Keep the initiating failure primary without dropping later accepted work's outcome. */
function mergeToolExecutionFailure(e, t) {
if (!e) return { error: t };
if (e.error === t) return e;
let n = "Tool execution failed";
try {
n = coerceErrorMessage(e.error);
} catch {}
return { error: new AggregateError([e.error, t], n, { cause: e.error }) };
}
function mergeRejectedToolOutcomes(e, t) {
let n = e;
for (const e of t) if (e.status === "rejected") n = mergeToolExecutionFailure(n, e.reason);
return n;
}
/** Drain before disposal; an existing fatal alone still follows normal batch completion. */
async function drainToolCallGroup(e, t, n, r) {
let i;
if (e.length > 0) {
const t = await Promise.allSettled(e.map(async (e) => ({
call: e,
result: await e.outcome
})));
for (const e of t) if (e.status === "rejected") i = mergeToolExecutionFailure(i ?? n, e.reason);
else try {
await r(e.value.call, e.value.result);
} catch (e) {
i = mergeToolExecutionFailure(i ?? n, e);
}
}
for (const e of t) if ("kind" in e) try {
e.execution.dispose();
} catch (e) {
i = mergeToolExecutionFailure(i ?? n, e);
}
return i;
}
function resolveToolBatchTermination(e) {
const t = e.filter((e) => e.result.terminate === true).map((e) => e.toolCall.id);
return {
terminate: e.length > 0 && t.length === e.length,
terminalToolCallIds: t
};
}
/**
* Combines the tool batches one assistant message ran (streamed batches first, then
* the terminal batch). The turn ends when every result asked to terminate, or when
* OpenClaw's turn-completion hook says the settled results complete the turn.
*/
function combineExecutedToolBatches(e, t, n) {
const r = n.flatMap((e) => e.messages);
const i = n.flatMap((e) => e.terminalToolCallIds);
let a;
for (const e of n) if (e.fatal) a = mergeToolExecutionFailure(a, e.fatal.error);
const o = e.completesToolTurn;
let s;
try {
s = o?.({
message: t,
toolResults: r,
terminalToolCallIds: new Set(i),
inputScope: getInternalToolTurnInputScope(o)
}) === true;
} catch (e) {
throw mergeToolExecutionFailure(a, e).error;
}
const c = n.every((e) => e.terminate) || s;
const l = n.find((e) => e.terminateRun);
return {
messages: r,
terminalToolCallIds: i,
steeringMessages: [...new Set(n.flatMap((e) => e.steeringMessages))],
terminate: c,
terminateRun: l !== void 0,
intervention: l?.intervention ?? n.find((e) => e.intervention)?.intervention,
fatal: a
};
}
//#endregion
//#region packages/agent-core/src/repetition-guard.ts
const FIRST_CHECK_CHARS = 16e3;
const TAIL_CHARS = 64e3;
const WINDOW_CHARS = 60;
const MIN_REPEATS = 5;
function isRepetitionDominated(e) {
const t = /* @__PURE__ */ new Map();
let n = 0;
for (const r of e.split(/\r\n|[\r\n]/)) {
const e = r.trim();
if (e) {
t.set(e, (t.get(e) ?? 0) + 1);
n++;
}
}
if (n >= MIN_REPEATS && t.size > n / 2) return false;
const r = e.length / 2;
let i = 0;
for (const [e, n] of t) if (n >= MIN_REPEATS) i = Math.max(i, e.length * n);
if (i >= r) return true;
const a = /* @__PURE__ */ new Map();
const o = Math.max(MIN_REPEATS, Math.ceil(r / WINDOW_CHARS));
for (let t = 0; t <= e.length - WINDOW_CHARS; t++) {
const n = e.slice(t, t + WINDOW_CHARS);
const r = a.get(n);
if (r && t < r.end) continue;
const i = (r?.count ?? 0) + 1;
if (i >= o) return true;
a.set(n, {
count: i,
end: t + WINDOW_CHARS
});
}
const s = e.length - WINDOW_CHARS;
const c = Math.max(1, Math.ceil(s / 31));
for (let t = 0; t <= 31; t++) {
const n = Math.min(t * c, s);
const i = e.slice(n, n + WINDOW_CHARS);
let a = n;
for (let t = 0; t < 8; t++) {
a = e.indexOf(i, a + 1);
if (a < 0) break;
const t = a - n;
let o = n;
let s = n + WINDOW_CHARS;
while (o > 0 && e[o - 1] === e[o - 1 + t]) o--;
while (s + t < e.length && e[s] === e[s + t]) s++;
const c = s + t - o;
if (c >= MIN_REPEATS * t && c >= r) return true;
}
if (n === s) break;
}
return false;
}
/** Hermes-inspired long-output guard, scoped to one visible-text or reasoning block. */
var RepetitionWatch = class {
constructor() {
this.parts = [];
this.chars = 0;
this.nextCheck = FIRST_CHECK_CHARS;
this.stopped = false;
}
feed(e) {
if (this.stopped) return true;
let t = 0;
while (t < e.length) {
const n = Math.min(e.length, t + this.nextCheck - this.chars);
this.parts.push(e.slice(t, n));
this.chars += n - t;
t = n;
if (this.chars === this.nextCheck) {
const e = this.parts.join("").slice(-64e3);
this.parts = [e];
this.nextCheck += Math.min(this.chars, TAIL_CHARS);
if (isRepetitionDominated(e)) {
this.stopped = true;
return true;
}
}
}
return false;
}
};
//#endregion
//#region packages/agent-core/src/assistant-repetition-guard.ts
/** Tracks each text/reasoning block once, including providers that only emit final snapshots. */
var AssistantRepetitionGuard = class {
constructor() {
this.blocks = /* @__PURE__ */ new Map();
}
check(e, t, n, r) {
const i = n === void 0 ? e.content.length : n + 1;
for (let a = n ?? t; a < i; a++) {
const n = e.content[a];
const i = n?.type === "text" ? n.text : n?.type === "thinking" ? n.thinking : void 0;
if (i === void 0 || a < t) continue;
let o = this.blocks.get(a);
const s = r && r.offset === (o?.text.length ?? 0);
if (!o || !s && !i.startsWith(o.text)) {
o = {
watch: new RepetitionWatch(),
text: ""
};
this.blocks.set(a, o);
}
const c = o.watch.feed(s ? r.delta : i.slice(o.text.length));
o.text = i;
if (c) return {
...e,
providerReplay: void 0,
content: [
...e.content.slice(0, t),
...e.content.slice(t, a).filter((e) => e.type !== "toolCall"),
{
type: "text",
text: "[Repetitive output stopped]"
}
],
stopReason: "error",
endTurn: true,
errorCode: REPETITIVE_OUTPUT_ERROR_CODE,
errorMessage: REPETITIVE_OUTPUT_ERROR_MESSAGE
};
}
}
};
//#endregion
//#region packages/agent-core/src/stream-steering.ts
/** Forward queued input while its normal transcript owner retains commit ordering. */
function createStreamSteering(e, t, n) {
const r = getInternalSteeringQueueObserver(e.getSteeringMessages);
let i = true;
let a;
let o = Promise.resolve();
let s;
let c;
let l;
let u = false;
const stop = () => {
i = false;
if (r) r.onChange = void 0;
const e = a;
a = void 0;
e?.();
};
const onActiveResponse = (c) => {
if (!i || t?.aborted) return;
s = c.needsContinuation;
a = e.onActiveResponse?.(c) ?? void 0;
const forward = () => {
if (!i || t?.aborted || l || !r || u) return;
const e = r.peek();
if (e.length === 0) return;
u = true;
const a = r.reserve(e);
let s = false;
o = o.then(async () => {
if (!i || t?.aborted) {
a();
return;
}
const r = await n([...e]);
const o = r.filter((e) => e.role === "user");
if (!i || t?.aborted || o.length !== r.length || o.length === 0) {
a();
stop();
return;
}
s = true;
if (!await c.steer(o)) {
a();
stop();
}
}).catch((e) => {
if (!s) a();
l ??= { error: e };
});
};
if (r) r.onChange = forward;
forward();
return stop;
};
return {
onActiveResponse,
finish() {
return c ??= (async () => {
stop();
await o;
if (l) throw l.error;
return s?.() === true;
})();
}
};
}
//#endregion
//#region packages/agent-core/src/turn-taint.ts
function readTurnTaintMetadata(e) {
const t = Reflect.get(e, "__openclaw");
const n = asOptionalRecord(t);
if (!n) return;
return {
...n.resultContentSource === "network" ? { resultContentSource: n.resultContentSource } : {},
...n.turnTainted === true ? { turnTainted: true } : {}
};
}
function toolResultTaintsTurn(e) {
return readTurnTaintMetadata(e)?.resultContentSource === "network";
}
function isActiveTurnTainted(e) {
const t = e.findLast((e) => {
if (e.role === "user") return true;
const t = readTurnTaintMetadata(e);
return t?.turnTainted === true || t?.resultContentSource === "network";
});
return t !== void 0 && t.role !== "user";
}
function withAssistantTurnTaint(e, t) {
if (!t) return e;
return {
...e,
__openclaw: {
...readTurnTaintMetadata(e),
turnTainted: true
}
};
}
function withToolResultContentSource(e, t) {
if (!t) return e;
return {
...e,
__openclaw: {
...readTurnTaintMetadata(e),
resultContentSource: t
}
};
}
//#endregion
//#region packages/agent-core/src/agent-stream-response.ts
function removeNonExecutableToolCalls(e) {
if (e.stopReason === "toolUse") return e;
const t = e.stopReason === "aborted" || e.stopReason === "error";
const n = e.content.filter((e) => e.type !== "toolCall" || !t && e.async);
return n.length === e.content.length ? e : replaceCompactionReplayOwnerContent(e, n);
}
function ensureToolTurnIdentity(e) {
if (!(e.stopReason === "toolUse" || (e.stopReason === "stop" || e.stopReason === "length") && e.content.some((e) => e.type === "toolCall" && e.async)) || e.responseId?.trim() || e.turnId?.trim()) return e;
return {
...e,
turnId: uuidv7()
};
}
function emitToolExecutionStart(e, t, n) {
return e.emit({
type: "tool_execution_start",
toolCallId: t.id,
toolName: t.name,
args: t.arguments,
...n ? { hideFromChannelProgress: true } : {}
});
}
async function emitToolExecutionEnd(e, t) {
const n = resolveAgentAssistantTurnId(t.assistantMessage);
await t.emit({
type: "tool_execution_end",
toolCallId: e.toolCall.id,
...n ? { assistantTurnId: n } : {},
toolName: e.toolCall.name,
result: e.result,
isError: e.isError,
executionStarted: e.executionStarted,
...e.errorKind ? { errorKind: e.errorKind } : {},
...e.hideFromChannelProgress === true ? { hideFromChannelProgress: true } : {}
});
}
async function emitToolResultMessage(e, t) {
const n = copyInternalToolResultState(e.result, withToolResultContentSource({
role: "toolResult",
toolCallId: e.toolCall.id,
toolName: e.toolCall.name,
content: e.result.content ?? [],
details: e.result.details,
isError: e.isError,
timestamp: Date.now()
}, e.resultContentSource));
await t({
type: "message_start",
message: n
});
const r = {
type: "message_end",
message: n
};
await t(r);
return r.message;
}
async function streamAgentResponse(e, t, n, r, i, a, o, s, c) {
const l = [...e.messages];
const convertMessages = async (e, r = n) => {
const i = t.transformContext ? await t.transformContext(e, r) : e;
return t.convertToLlm(i.map((e) => {
if (e.role !== "custom" || e.customType !== "openclaw:turn-aborted") return e;
return {
role: "user",
content: typeof e.content === "string" ? [{
type: "text",
text: e.content
}] : e.content,
timestamp: e.timestamp
};
}));
};
const u = await convertMessages(l);
let d;
e.preparedSystemPrompt = prepareSystemPrompt(e.systemPrompt, e.preparedSystemPrompt);
const f = {
systemPrompt: e.systemPrompt,
preparedSystemPrompt: e.preparedSystemPrompt,
messages: u,
tools: e.tools
};
const p = resolveAgentCoreStreamFn(c, s);
const m = (t.getApiKey ? await t.getApiKey(t.model.provider) : void 0) || t.apiKey;
const h = new AbortController();
const g = n ? AbortSignal.any([n, h.signal]) : h.signal;
const _ = new AbortController();
const v = AbortSignal.any([g, _.signal]);
let y = false;
const onTerminalLoop = () => {
y = true;
_.abort(/* @__PURE__ */ new Error("Tool batch terminated"));
};
const abortFailedResponse = (e) => {
if (e && !y && (e.stopReason === "error" || e.stopReason === "aborted") && e.errorCode !== "openclaw_repetitive_output" && !isResponsesOutputLimitToolCallError(e)) h.abort(new Error(e.errorMessage ?? "Model response interrupted"));
};
const b = createStreamSteering(t, g, async (e) => {
d ??= JSON.stringify(u);
const t = await convertMessages([...l, ...e], g);
if (JSON.stringify(t.slice(0, u.length)) !== d) return [];
return t.slice(u.length);
});
const x = /* @__PURE__ */ new Set();
const S = [];
let C = Promise.resolve();
let w = Promise.resolve();
let T;
const emitToolEvent = async (t) => {
if (t.type !== "message_end" || t.message.role !== "toolResult") {
await r(t);
return;
}
const n = t.message;
const a = e.messages.push(n) - 1;
const o = i.push(n) - 1;
try {
await r(t);
} finally {
if (t.message !== n && t.message.role === "toolResult") {
if (e.messages[a] === n) e.messages[a] = t.message;
if (i[o] === n) i[o] = t.message;
}
}
};
const enqueueTools = (e) => {
if (e.stopReason === "error" || e.stopReason === "aborted") return;
const t = e.content.filter((t) => t.type === "toolCall" && !x.has(t.id) && (e.stopReason === "toolUse" || t.async === true));
if (t.length === 0) return;
const n = x.size > 0;
for (const e of t) x.add(e.id);
const r = C;
const i = w;
let o;
w = new Promise((e) => {
o = e;
});
const s = i.then(async () => {
let i = g;
if (y) {
i = AbortSignal.abort(/* @__PURE__ */ new Error("Tool-loop recovery ended"));
await r;
}
const s = await a(e, t, i, emitToolEvent, {
waitForPrevious: () => r,
onParallelStarted: o,
onTerminalLoop,
hasUnobservedAsyncToolResults: n
});
S.push(s);
if (s.fatal || s.terminateRun && s.intervention?.detector !== "repeated_tool_error") h.abort(s.fatal?.error ?? /* @__PURE__ */ new Error("Tool batch terminated"));
}).catch((e) => {
T = mergeToolExecutionFailure(T, e);
h.abort(e);
}).finally(o);
C = Promise.all([r, s]).then(() => {});
};
let E;
try {
const a = p(t.model, f, {
...t,
apiKey: m,
signal: v,
onActiveResponse: b.onActiveResponse,
asyncToolExecution: f.tools?.some((e) => e.name === "sessions_yield") === true
});
return await runAgentCoreStream(a, async () => {
const s = await a;
const c = t.repetitionGuard?.(t.model) ? new AssistantRepetitionGuard() : void 0;
let l = null;
let u;
let d = 0;
let f;
const remainingFragment = (e) => d === 0 ? e : replaceCompactionReplayOwnerContent(e, e.content.slice(d));
const commitFragment = async (t) => {
if (u === void 0) {
e.messages.push(t);
await r({
type: "message_start",
message: { ...t }
});
} else {
e.messages.splice(u, 1);
e.messages.push(t);
}
u = void 0;
i.push(t);
await r({
type: "message_end",
message: t
});
};
function projectEvent(e, t, n) {
if (d === 0 && !n && (!("partial" in e) || e.partial === t)) return e;
const r = {
...e,
contentIndex: e.contentIndex - d
};
if ("partial" in e) r.partial = t;
return r;
}
for await (const t of s) switch (t.type) {
case "start": {
const n = t.partial;
l = n;
u = e.messages.length;
e.messages.push(n);
await r({
type: "message_start",
message: { ...n }
});
break;
}
case "text_start":
case "text_delta":
case "text_end":
case "thinking_start":
case "thinking_delta":
case "thinking_end":
case "toolcall_start":
case "toolcall_delta":
case "toolcall_end":
if (l) {
let n;
if (c && t.type === "text_delta" && t.partial === void 0) {
const e = l.content[t.contentIndex];
n = {
offset: e?.type === "text" ? e.text.length : 0,
delta: t.delta
};
}
let i = l;
if ("partial" in t && t.partial) i = t.partial;
else if (t.type === "text_delta") i = appendTextDeltaToAssistantMessage(l, t.contentIndex, t.delta);
l = i;
if (t.contentIndex < d) break;
const a = c?.check(i, d, t.type === "toolcall_end" ? void 0 : t.contentIndex, n);
if (a) {
_.abort(new Error(REPETITIVE_OUTPUT_ERROR_MESSAGE));
return await finalizeAssistantMessage(a);
}
const s = remainingFragment(i);
if (u === void 0) {
u = e.messages.length;
e.messages.push(s);
await r({
type: "message_start",
message: { ...s }
});
} else e.messages[u] = s;
const p = t.type === "toolcall_end";
await r({
type: "message_update",
assistantMessageEvent: projectEvent(t, s, p),
message: t.type === "text_delta" && !t.partial ? Object.freeze(s) : { ...s }
});
if (p && t.toolCall.async && !x.has(t.toolCall.id) && i.content.slice(d, t.contentIndex).every((e) => e.type !== "toolCall" || e.async === true)) {
let e = structuredClone(replaceCompactionReplayOwnerContent(i, i.content.slice(d, t.contentIndex + 1)));
if (f) e.turnId = f;
e.stopReason = "toolUse";
e.usage = createEmptyTransportUsage();
e = o(ensureToolTurnIdentity(e));
f ??= e.turnId;
await commitFragment(e);
d = t.contentIndex + 1;
enqueueTools(e);
}
}
break;
case "done":
case "error": return await finalizeAssistantMessage(t.type === "done" ? t.message : t.error);
}
return await finalizeAssistantMessage();
async function finalizeAssistantMessage(e) {
const t = e?.errorCode === "openclaw_repetitive_output" ? e : e && c?.check(e, d);
if (t) _.abort(new Error(REPETITIVE_OUTPUT_ERROR_MESSAGE));
abortFailedResponse(t ?? e);
const r = await s.result();
const i = t ?? c?.check(r, d);
if (i) _.abort(new Error(REPETITIVE_OUTPUT_ERROR_MESSAGE));
const a = i ? {
...i,
usage: r.usage
} : r;
abortFailedResponse(a);
const l = isResponsesOutputLimitToolCallError(a);
if (l) await C;
const u = remainingFragment(a);
const p = o(ensureToolTurnIdentity(removeNonExecutableToolCalls({
...u,
...d > 0 && u.stopReason === "toolUse" && !u.content.some((e) => e.type === "toolCall") ? { stopReason: "stop" } : {},
...f ? { turnId: f } : {},
...l && n?.aborted ? { stopReason: "aborted" } : l && S.length > 0 && S.every((e) => e.terminate) ? { errorCode: PROVIDER_FAILURE_WITH_OUTPUT_ERROR_CODE } : {}
})));
await commitFragment(p);
if (x.size > 0) enqueueTools(p);
await C;
if (T) throw T.error;
const m = await b.finish();
return {
message: p,
executedIds: x,
batches: S,
continuationRequired: m
};
}
}, c);
} catch (e) {
E = { error: e };
throw e;
} finally {
h.abort(/* @__PURE__ */ new Error("Model response closed"));
await C;
if (T) E = mergeToolExecutionFailure(E, T.error);
if (E) {
for (const e of S) if (e.fatal) E = mergeToolExecutionFailure(E, e.fatal.error);
}
try {
await b.finish();
} catch (e) {
if (!E) {
for (const e of S) if (e.fatal) E = mergeToolExecutionFailure(E, e.fatal.error);
}
E = mergeToolExecutionFailure(E, e);
}
if (E) throw E.error;
}
}
//#endregion
//#region packages/agent-core/src/tool-call-outcome.ts
function hidesToolCallFromChannelProgress(e, t) {
const n = e.resolved.get(t);
return (n?.kind === "resolved" ? n.tool : e.currentContext.tools?.find((e) => e.name === t.name))?.hideFromChannelProgress === true;
}
function applyToolResultUpdate(e, t) {
return t.content === void 0 && t.details === void 0 && t.terminate === void 0 ? e : copyInternalToolResultState(e, {
...e,
content: t.content ?? e.content,
details: t.details ?? e.details,
terminate: t.terminate ?? e.terminate
});
}
async function finalizeExecutedToolCall(e, t, n, r) {
let i = n.result;
let a = n.isError;
if (n.executionStarted && e.config.afterToolCall) try {
const n = await e.config.afterToolCall({
assistantMessage: e.assistantMessage,
toolCall: t.toolCall,
args: r,
result: i,
isError: a,
context: e.currentContext
}, e.signal);
if (n) {
i = applyToolResultUpdate(i, n);
a = n.isError ?? a;
}
} catch (t) {
if (e.isLocalError?.(t)) throw t;
i = createErrorToolResult(coerceErrorMessage(t));
a = true;
}
return await finalizeToolCallOutcome(e, {
toolCall: t.toolCall,
result: i,
isError: a,
executionStarted: n.executionStarted,
...n.intervention ? { intervention: n.intervention } : {},
...t.tool.hideFromChannelProgress === true ? { hideFromChannelProgress: true } : {},
...n.executionStarted && !n.callerCancelled ? resolveToolResultContentSource(t.tool, n.result) : {}
}, r);
}
async function completeStartedToolCall(e, t, n, r) {
try {
const i = await finalizeExecutedToolCall(e, t, n, t.execution.args);
if (r) t.execution.dispose();
await emitToolExecutionEnd(i, e);
return i;
} finally {
t.execution.dispose();
}
}
async function finalizeToolCallOutcome(e, t, n) {
let r = t;
if (e.config.afterToolOutcome) try {
const i = await e.config.afterToolOutcome({
assistantMessage: e.assistantMessage,
toolCall: t.toolCall,
args: n,
result: t.result,
isError: t.isError,
executionStarted: t.executionStarted,
...t.errorKind ? { errorKind: t.errorKind } : {},
context: e.currentContext
}, e.signal);
if (i) r = {
...t,
result: applyToolResultUpdate(t.result, i),
isError: i.isError ?? t.isError
};
} catch (n) {
if (e.isLocalError?.(n)) throw n;
const i = createErrorToolResult(coerceErrorMessage(n));
r = {
...t,
result: {
...i,
...t.result.terminate === void 0 ? {} : { terminate: t.result.terminate }
},
isError: true
};
}
if (e.lifecycle?.observeOutcome) r.loopOutcome = {
toolCall: r.toolCall,
args: n,
result: r.result,
isError: r.isError,
...r.errorKind ? { errorKind: r.errorKind } : {}
};
const i = e.warnings?.find((e) => e.toolCallId === r.toolCall.id);
return i ? {
...r,
result: appendToolLoopWarning(r.result, i)
} : r;
}
function immediateToolCallError(e, t) {
return {
kind: "immediate",
result: createErrorToolResult(e),
isError: true,
...t ? { errorKind: t } : {}
};
}
function immediateToolArgumentValidationError(e) {
return immediateToolCallError(coerceErrorMessage(e), "argument-validation");
}
/** Classify only preparation rejections, not generic or execution failures. */
function immediateToolPreparationError(e) {
return e instanceof ToolArgumentValidationError ? immediateToolArgumentValidationError(e) : immediateToolCallError(coerceErrorMessage(e));
}
/**
* An executed call's source comes from its tool declaration, or from the raw
* result/error mark a dispatcher (Tool Search, Code Mode) sets for nested calls.
*/
function resolveToolResultContentSource(e, t) {
const n = e.resultContentSource ?? getInternalToolResultContentSource(t);
return n ? { resultContentSource: n } : {};
}
function createToolExecutionErrorResult(e) {
const t = createErrorToolResult(coerceErrorMessage(e));
return typeof e === "object" && e !== null ? copyInternalToolResultState(e, t) : t;
}
function createErrorToolResult(e, t = {}) {
return {
content: [{
type: "text",
text: e
}],
details: t
};
}
const TOOL_LOOP_BLOCKED_MESSAGE = "This tool was not executed because tool-loop recovery blocked further execution. Reassess the task before choosing the next action.";
const STEERING_TOOL_SKIP_MESSAGE = "Skipped to process an incoming message.";
const TOOL_ADMISSION_FAILURE_MESSAGE = "Tool execution was blocked before launch.";
const TOOL_ADMISSION_FAILURE_DETAILS = {
status: "blocked",
deniedReason: "tool-admission"
};
async function completeUnstartedToolCall(e, t, n = {}) {
const { hideFromChannelProgress: r = false } = n;
if (!n.startEmitted) await emitToolExecutionStart(e, t, r);
const i = await finalizeToolCallOutcome(e, {
toolCall: t,
result: createErrorToolResult(n.intervention ? TOOL_LOOP_BLOCKED_MESSAGE : n.reason === "admission" ? TOOL_ADMISSION_FAILURE_MESSAGE : n.reason === "steering" ? STEERING_TOOL_SKIP_MESSAGE : "Operation aborted", n.intervention ? {
status: "blocked",
deniedReason: "tool-loop",
intervention: n.intervention
} : n.reason === "admission" ? TOOL_ADMISSION_FAILURE_DETAILS : n.reason === "steering" ? {
status: "skipped",
deniedReason: "steering"
} : void 0),
isError: true,
executionStarted: false,
...r ? { hideFromChannelProgress: true } : {}
}, "args" in n ? n.args : t.arguments);
await emitToolExecutionEnd(i, e);
return i;
}
//#endregion
//#region packages/agent-core/src/agent-loop-tool-execution.ts
async function prepareToolCallExecution(e, t, n, r, i) {
const a = [];
let o = true;
let s = t.pendingInput;
const c = /* @__PURE__ */ new Set();
const l = {
...t,
pendingInput: s ? {
hasPending: () => o && !n?.aborted && s?.hasPending() === true,
subscribe: (e) => {
if (!o || n?.aborted || !s) return () => {};
const t = s.subscribe(() => {
if (o && !n?.aborted) e();
});
const release = () => {
c.delete(release);
t();
};
c.add(release);
return release;
}
} : void 0
};
const closeUpdates = () => {
o = false;
l.pendingInput = void 0;
s = void 0;
for (const e of c) e();
};
const onUpdate = (t) => {
if (!o) return;
a.push(Promise.resolve(r({
type: "tool_execution_update",
toolCallId: e.toolCall.id,
toolName: e.toolCall.name,
args: e.toolCall.arguments,
partialResult: t,
...e.tool.hideFromChannelProgress === true ? { hideFromChannelProgress: true } : {}
})));
};
const finishUpdates = async (e, t) => {
let n;
try {
closeUpdates();
} catch (t) {
n = mergeToolExecutionFailure(e, t);
}
for (const t of await Promise.allSettled(a)) if (t.status === "rejected") n = mergeToolExecutionFailure(n ?? e, t.reason);
try {
t?.();
} catch (t) {
n = mergeToolExecutionFailure(n ?? e, t);
}
if (n) throw n.error;
};
const readyExecution = (e, t, r = () => {}) => {
let a = false;
const dispose = () => {
if (!a) {
a = true;
closeUpdates();
r();
}
};
return {
kind: "ready",
args: e,
dispose,
async execute(e) {
let r = false;
let a;
let o;
try {
if (n?.aborted) return {
result: createErrorToolResult("Operation aborted"),
isError: true,
executionStarted: false
};
try {
const n = await t(() => {
try {
e?.();
} catch (e) {
a = { error: e };
throw e;
}
r = true;
});
if (a) throw a.error;
return {
result: n,
isError: false,
executionStarted: r
};
} catch (e) {
if (a?.error instanceof InternalToolLoopBlocked) {
const { intervention: e } = a.error;
return {
result: createErrorToolResult(TOOL_LOOP_BLOCKED_MESSAGE, {
status: "blocked",
deniedReason: "tool-loop",
intervention: e
}),
isError: true,
executionStarted: false,
intervention: e
};
}
o = { error: a?.error ?? e };
if (a) throw a.error;
if (i?.(e)) throw e;
return {
result: createToolExecutionErrorResult(e),
isError: true,
executionStarted: r,
...r && n?.aborted && e === n.reason ? { callerCancelled: true } : {}
};
}
} catch (e) {
o = { error: e };
throw e;
} finally {
await finishUpdates(o, dispose);
}
}
};
};
const u = getInternalToolExecutionPreparer(e.tool);
if (!u) return readyExecution(e.args, async (t) => {
if (n?.aborted) throw n.reason ?? /* @__PURE__ */ new Error("Operation aborted");
return await runWithAgentToolExecutionContext(l, () => {
t();
return e.tool.execute(e.toolCall.id, e.args, n, onUpdate);
});
});
let d;
try {
d = await runWithAgentToolExecutionContext(l, () => u({
toolCallId: e.toolCall.id,
args: e.args,
...n ? { signal: n } : {},
onUpdate
}));
} catch (e) {
await finishUpdates({ error: e });
if (i?.(e)) throw e;
return {
kind: "immediate",
outcome: {
result: createToolExecutionErrorResult(e),
isError: true,
executionStarted: false
}
};
}
if (d.kind === "immediate") {
await finishUpdates(d.outcome.kind === "error" ? { error: d.outcome.error } : void 0, () => d.dispose());
if (d.outcome.kind === "error" && i?.(d.outcome.error)) throw d.outcome.error;
return {
kind: "immediate",
outcome: d.outcome.kind === "result" ? {
result: d.outcome.result,
isError: d.outcome.isError,
executionStarted: false
} : {
result: createToolExecutionErrorResult(d.outcome.error),
isError: true,
executionStarted: false
}
};
}
const f = d;
return readyExecution(f.args, (e) => runWithAgentToolExecutionContext(l, () => f.execute(e)), f.dispose);
}
async function launchParallelToolCalls(e, t, n) {
const r = e.flatMap((e, t) => "kind" in e ? [{
entry: e,
index: t
}] : []);
/**
* Rejected calls never start, so they launch as lifecycle commits when the
* launch cursor passes their assistant-order position. Admission then records
* them between the prepared calls that commit as their implementations start.
*/
let i = 0;
const launchRejectedBefore = (n) => {
for (; i < n; i += 1) {
const n = e[i];
if (!n || "kind" in n || n.errorKind !== "argument-validation") continue;
try {
t?.commitReadyCalls?.([{
toolCallId: n.toolCall.id,
args: n.toolCall.arguments
}]);
} catch (e) {
return {
index: i,
error: e
};
}
}
};
const a = {
started: [],
completed: []
};
const o = [];
const reject = (e, t) => {
a.rejected = {
index: a.rejected?.index ?? e,
error: mergeToolExecutionFailure(a.rejected, t).error
};
};
let s = 0;
let c;
const l = new Promise((e) => {
c = e;
});
const launchNext = () => {
const i = r[s++];
a.rejected ??= launchRejectedBefore(i?.index ?? e.length);
if (!i || a.rejected) {
c();
return;
}
let resolvePreparation = () => {};
o.push(new Promise((e) => {
resolvePreparation = e;
}));
const l = {};
let u = false;
let d = false;
const onStart = () => {
try {
if (n.terminalIntervention) throw new InternalToolLoopBlocked(n.terminalIntervention);
t?.commitReadyCalls?.([{
toolCallId: i.entry.toolCall.id,
args: i.entry.execution.args
}]);
} catch (e) {
if (e instanceof InternalToolLoopBlocked) {
a.blocked = {
index: i.index,
intervention: e.intervention
};
throw e;
}
d = true;
reject(i.index, e);
c();
throw e;
}
u = true;
resolvePreparation();
n.executionStarted = true;
if (l.outcome) a.started.push({
...i,
outcome: l.outcome
});
queueMicrotask(launchNext);
};
const f = i.entry.execution.execute(onStart);
l.outcome = f;
if (u) a.started.push({
...i,
outcome: f
});
f.then((e) => {
resolvePreparation();
if (!u && !d) {
a.completed.push({
...i,
outcome: e
});
if (a.blocked) c();
else queueMicrotask(launchNext);
}
}, (e) => {
resolvePreparation();
reject(i.index, e);
c();
});
};
launchNext();
await l;
await Promise.all(o);
return a;
}
//#endregion
//#region packages/agent-core/src/agent-loop-tool-recovery.ts
function resetToolLoopRecovery(e) {
e.criticalToolLoopSeen = false;
delete e.repeatedToolError;
delete e.blockedToolActions;
}
/** Repeated tool errors in one unseen response share the same recovery allowance. */
function advanceToolLoopRecovery(e, t) {
if (e.toolPlan.terminalIntervention) return true;
if (t.detector === "repeated_tool_error" && e.toolPlan.repeatedToolErrorRecoveryGranted) return false;
const n = e.toolLoopRecoveryState.criticalToolLoopSeen;
e.toolLoopRecoveryState.criticalToolLoopSeen = true;
if (n) {
e.toolPlan.terminalIntervention = t;
if (t.detector === "repeated_tool_error") e.onTerminalLoop?.();
} else if (t.detector === "repeated_tool_error") e.toolPlan.repeatedToolErrorRecoveryGranted = true;
return n;
}
async function completeToolLoopInterventionBatch(e, t) {
const n = [];
const r = [];
if (t.intervention.detector === "repeated_tool_error") await e.waitForPrevious?.();
for (const i of t.toolCalls) {
const a = hidesToolCallFromChannelProgress(e, i);
await emitToolExecutionStart(e, i, a);
const o = i.id === t.intervention.toolCallId;
const s = t.terminal ? o ? `${t.intervention.reason}\n\nCritical tool-loop recovery failed because another critical loop was detected. This run is stopping now.` : "This tool was not executed because another call in the batch repeated a critical tool loop. This run is stopping now." : o ? `${t.intervention.recoveryMessage ?? t.intervention.reason}\n\nDo not repeat this exact tool action. Reassess the task. You may answer the user, ask for clarification, or continue with a different tool or different arguments.` : "This tool was not executed because another call in the batch triggered critical tool-loop recovery. Reassess the task before choosing the next action.";
const c = e.validated.get(i);
const l = await finalizeToolCallOutcome(e, {
toolCall: i,
result: {
content: [{
type: "text",
text: s
}],
details: {
status: "blocked",
deniedReason: "tool-loop",
intervention: t.intervention
},
...t.terminal ? { terminate: true } : {}
},
isError: true,
executionStarted: false,
...a ? { hideFromChannelProgress: true } : {}
}, c?.kind === "prepared" ? c.args : i.arguments);
await emitToolExecutionEnd(l, e);
n.push(await emitToolResultMessage(l, e.emit));
r.push(l);
}
const i = resolveToolBatchTermination(r);
return {
messages: n,
steeringMessages: [],
...i,
terminate: t.terminal || i.terminate,
terminateRun: t.terminal,
intervention: t.intervention
};
}
function appendToolLoopRecoveryNote(e, t) {
return {
...e,
result: copyInternalToolResultState(e.result, {
...e.result,
content: [...e.result.content ?? [], {
type: "text",
text: "[System note: " + (t.recoveryMessage ?? t.reason) + " Do not repeat this exact tool action. If it may have partly applied, check current state first. Reassess: change the tool or arguments, ask the user, or answer without it.]"
}]
})
};
}
//#endregion
//#region packages/agent-core/src/tool-batch-admission.ts
/** Map validated calls to admission candidates in assistant order. */
function toToolBatchCalls(e, t) {
return e.flatMap((e) => {
const n = t.get(e);
if (n?.kind === "prepared") return [{
toolCall: e,
args: n.args,
tool: n.tool
}];
return n?.errorKind === "argument-validation" ? [{
toolCall: e,
args: e.arguments,
validationFailure: n.result
}] : [];
});
}
/** Admitted calls, prepared or rejected, whose admission a skipped batch must release. */
function admittedIds(e, t) {
return toToolBatchCalls(e, t).map((e) => e.toolCall.id);
}
/** Admitted entries among prepared batch entries: ready calls and rejected calls. */
function admittedEntryIds(e) {
return e.flatMap((e) => e.kind === "prepared" || e.errorKind === "argument-validation" ? [e.toolCall.id] : []);
}
//#endregion
//#region packages/agent-core/src/turn-interruption.ts
/** Canonical empty aborted/error assistant recorded when a run ends without output. */
function createFailureMessage(e, t, n) {
return {
role: "assistant",
content: [{
type: "text",
text: ""
}],
api: e.api,
provider: e.provider,
model: e.id,
stopReason: n ? "aborted" : "error",
errorMessage: t instanceof Error ? t.message : String(t),
timestamp: Date.now(),
usage: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
total: 0
}
}
};
}
const INTERRUPTED_TURN_GUIDANCE = `<turn_aborted>
The previous turn was interrupted. Any running background processes may still be active. If any tools or commands were aborted, they may have partially executed.
</turn_aborted>`;
/**
* Aborts that end a turn as an intentional handoff (e.g. yield-style tools)
* mark it with an abort reason carrying `turnHandoff: true`. Interruption
* guidance is skipped for them: the next turn would otherwise be told tools
* may have partially executed after a clean, deliberate stop.
*/
function isTurnHandoffAbort(e) {
if (!e?.aborted) return false;
const t = e.reason;
return typeof t === "object" && t !== null && t.turnHandoff === true;
}
async function appendInterruptedTurnMessage(e, t) {
const n = {
role: "custom",
customType: "openclaw:turn-aborted",
content: INTERRUPTED_TURN_GUIDANCE,
display: false,
timestamp: Date.now()
};
e.push(n);
await t({
type: "message_start",
message: n
});
await t({
type: "message_end",
message: n
});
}
//#endregion
//#region packages/agent-core/src/agent-loop.ts
const TOOL_LOOP_RECOVERY_TERMINATED_MESSAGE = "OpenClaw stopped this run because tool-loop recovery encountered another critical loop. No blocked tool action was executed.";
/** Run a prompt-started loop and emit events through a caller-owned sink. */
async function runAgentLoop(e, t, n, r, i, a, o) {
const s = [];
const c = n.toolLoopRecoveryState ?? { criticalToolLoopSeen: false };
const l = { context: {
...t,
messages: [...t.messages]
} };
const u = e.filter(isOpenClawSystemUpdateMessage);
const d = e.filter((e) => !isOpenClawSystemUpdateMessage(e));
await r({ type: "agent_start" });
await r({ type: "turn_start" });
for (const e of d) {
if (n.consumeQueuedMessageCancellation?.(e)) continue;
await r({
type: "message_start",
message: e
});
if (n.consumeQueuedMessageCancellation?.(e)) continue;
l.context.messages.push(e);
s.push(e);
if (e.role === "user") resetToolLoopRecovery(c);
commitInternalToolTurnInput(n.completesToolTurn);
await r({
type: "message_end",
message: e
});
}
if (d.length > 0 && s.length === 0) {
await r({
type: "agent_end",
messages: []
});
return [];
}
return runLoop(l, s, {
...n,
toolLoopRecoveryState: c
}, i, r, a, o, u);
}
/**
* Own one replaceable context slot so this async frame does not retain earlier
* contexts after a next-turn hook replaces them.
*/
async function runLoop(e, t, n, r, i, a, o, s = []) {
let c = n;
let l = s;
let u = true;
let d;
let f = true;
let p = isActiveTurnTainted(e.context.messages);
const m = n.toolLoopRecoveryState ?? { criticalToolLoopSeen: false };
const h = getSteeringAtCheckpoint(c);
let g = Array.isArray(h) ? h : await h;
const stopIfAborted = async () => {
if (!r?.aborted) return false;
if (o?.isLocalError?.(r.reason)) throw r.reason;
const e = withAssistantTurnTaint(createFailureMessage(c.model, r.reason instanceof Error ? r.reason : /* @__PURE__ */ new Error("Agent run aborted"), true), p);
t.push(e);
if (!f) {
await i({ type: "turn_start" });
f = true;
}
await i({
type: "message_start",
message: e
});
await i({
type: "message_end",
message: e
});
await i({
type: "turn_end",
message: e,
toolResults: []
});
f = false;
if (!isTurnHandoffAbort(r)) await appendInterruptedTurnMessage(t, i);
await i({
type: "agent_end",
messages: t
});
return true;
};
const commitPendingMessages = async () => {
const n = orderSystemUpdateMessages(g);
g = [];
let r = false;
for (const a of n) {
if (c.consumeQueuedMessageCancellation?.(a)) continue;
await i({
type: "message_start",
message: a
});
if (c.consumeQueuedMessageCancellation?.(a)) continue;
if (a.role === "user") {
p = false;
resetToolLoopRecovery(m);
}
e.context.messages.push(a);
t.push(a);
if (!isOpenClawSystemUpdateMessage(a)) commitInternalToolTurnInput(c.completesToolTurn);
await i({
type: "message_end",
message: a
});
r = true;
}
return r;
};
while (true) {
let n = u || !d;
while (n || g.length > 0) {
if (await stopIfAborted()) return t;
if (!u) {
await i({ type: "turn_start" });
f = true;
} else u = false;
if (g.length > 0) {
if (!await commitPendingMessages() && !n) continue;
}
if (await stopIfAborted()) return t;
if (d) {
const n = await d(e.context);
e.context = {
...e.context,
systemPrompt: n.systemPrompt,
tools: n.tools
};
if (await stopIfAborted()) return t;
}
const s = getInternalSteeringQueueObserver(c.getSteeringMessages)?.drainContext?.() ?? [];
if (l.length > 0 || s.length > 0) {
g = [...l, ...s];
l = [];
await commitPendingMessages();
if (await stopIfAborted()) return t;
}
const h = { executionStarted: false };
const _ = createStreamedSteeringConfig(c);
const v = await streamAgentResponse(e.context, c, r, i, t, async (t, n, r, i, a) => {
return await executeToolCalls(e.context, t, _.config, r, i, m, h, n, a, a.hasUnobservedAsyncToolResults, o?.isLocalError);
}, (e) => withAssistantTurnTaint(e, p), a, o);
const { message: y } = v;
const b = y.stopReason === "error" || y.stopReason === "aborted";
const x = b ? [] : y.content.filter((e) => e.type === "toolCall" && !v.executedIds.has(e.id) && (y.stopReason === "toolUse" || e.async === true));
const S = x.length > 0 ? await executeToolCalls(e.context, y, _.getTerminalConfig(), r, i, m, h, x, void 0, v.executedIds.size > 0, o?.isLocalError) : void 0;
const C = [...v.batches, ...S ? [S] : []];
const w = C.length ? combineExecutedToolBatches(c, y, C) : void 0;
const T = w?.messages ?? [];
p ||= T.some(toolResultTaintsTurn);
n = v.continuationRequired || y.stopReason === "stop" && y.endTurn === false && !w?.terminate || w !== void 0 && !w.terminate;
g = w?.steeringMessages ?? [];
for (const n of S?.messages ?? []) {
e.context.messages.push(n);
t.push(n);
}
try {
await i({
type: "turn_end",
message: y,
toolResults: T
});
} catch (e) {
throw mergeToolExecutionFailure(w?.fatal, e).error;
}
f = false;
if (w?.fatal) throw w.fatal.error;
if (y.stopReason === "aborted" && (!w?.terminateRun || r?.aborted)) {
if (r?.aborted && o?.isLocalError?.(r.reason)) throw r.reason;
if (r?.aborted && !isTurnHandoffAbort(r)) await appendInterruptedTurnMessage(t, i);
await i({
type: "agent_end",
messages: t
});
return t;
}
if (await stopIfAborted()) return t;
if (w?.terminateRun) {
const n = w.intervention?.detector === "repeated_tool_error";
const r = n ? w.intervention?.reason ?? "OpenClaw stopped this turn after 3 consecutive identical tool failures. Check the tool inputs or service, then use a changed request." : TOOL_LOOP_RECOVERY_TERMINATED_MESSAGE;
const a = {
...createFailureMessage(c.model, new Error(r), false),
...n ? { errorCode: REPEATED_TOOL_ERROR_CODE } : {},
content: [{
type: "text",
text: r
}]
};
e.context.messages.push(a);
t.push(a);
await i({ type: "turn_start" });
f = true;
await i({
type: "message_start",
message: a
});
await i({
type: "message_end",
message: a
});
await i({
type: "turn_end",
message: a,
toolResults: []
});
f = false;
await i({
type: "agent_end",
messages: t
});
return t;
}
if (b) {
await i({
type: "agent_end",
messages: t
});
return t;
}
const E = await c.prepareNextTurn?.({
message: y,
toolResults: T,
context: e.context,
newMessages: t
});
d = E?.prepareContinuation;
if (E) {
e.context = E.context ?? e.context;
const t = E.model ?? c.model;
const n = E.thinkingLevel ?? c.thinkingLevel;
const r = (E.thinkingLevel !== void 0 || E.model !== void 0 && n !== void 0) && n !== void 0 ? resolveAgentReasoningOption(t, n) : c.reasoning;
c = Object.assign({}, c, {
model: t,
thinkingLevel: n,
reasoning: r
});
}
if (await stopIfAborted()) return t;
if (g.length === 0) {
if (!E?.stop && await c.shouldStopAfterTurn?.({
message: y,
toolResults: T,
context: e.context,
newMessages: t
})) {
await i({
type: "agent_end",
messages: t
});
return t;
}
const n = getSteeringAtCheckpoint(c);
g = Array.isArray(n) ? n : await n;
}
if (await stopIfAborted()) return t;
if (E?.stop) {
await commitPendingMessages();
await i({
type: "agent_end",
messages: t
});
return t;
}
}
g = await c.getFollowUpMessages?.() || [];
if (g.length === 0) {
const e = getSteeringAtCheckpoint(c);
g = Array.isArray(e) ? e : await e;
}
if (g.length === 0) break;
}
await i({
type: "agent_end",
messages: t
});
return t;
}
async function executeToolCalls(e, t, n, r, i, a, o, s = t.content.filter((e) => e.type === "toolCall"), c, l = false, u) {
if (n.completesToolTurn) {
const e = getInternalToolTurnInputScope(n.completesToolTurn);
for (const n of s) captureAgentToolInputScope({
assistantMessage: t,
toolCall: n
}, e);
}
const d = {
currentContext: e,
assistantMessage: t,
config: n,
signal: r,
emit: i,
resolved: /* @__PURE__ */ new Map(),
validated: /* @__PURE__ */ new Map(),
onParallelStarted: c?.onParallelStarted,
onTerminalLoop: c?.onTerminalLoop,
hasUnobservedAsyncToolResults: l,
isLocalError: u,
toolPlan: o,
toolLoopRecoveryState: a,
waitForPrevious: c?.waitForPrevious
};
if (n.beforeToolBatch) {
for (const e of s) {
if (r?.aborted) break;
d.validated.set(e, await validateToolCallForBatchAdmission(d, e));
}
const i = toToolBatchCalls(s, d.validated);
if (!r?.aborted) {
const o = await n.beforeToolBatch({
assistantMessage: t,
calls: i,
context: e,
toolLoopRecoveryState: a
}, r);
if (o?.intervention) return await completeToolLoopInterventionBatch(d, {
toolCalls: s,
intervention: o.intervention,
terminal: advanceToolLoopRecovery(d, o.intervention)
});
d.lifecycle = o ? takeInternalToolBatchLifecycle(o) : void 0;
d.warnings = o?.warnings;
}
}
let f = false;
if (n.toolExecution !== "sequential") for (const e of s) {
if (r?.aborted) break;
const t = await resolveToolCallTool(d, e);
if (t.kind === "resolved" && t.tool?.executionMode === "sequential") {
f = true;
break;
}
}
const p = n.toolExecution === "sequential" || f;
if (p && c) await c.waitForPrevious();
if (r?.aborted) d.lifecycle?.releaseSkippedCalls?.(admittedIds(s, d.validated));
return executeToolCallGroups(d, s, p);
}
async function executeToolCallGroups(e, t, n) {
const r = [];
const i = [];
let a = [];
let o = 0;
let s;
let c;
let l = false;
while (o < t.length) {
if (n && e.toolPlan.executionStarted && !e.signal?.aborted) {
const t = getSteeringAtCheckpoint(e.config);
a = Array.isArray(t) ? t : await t;
}
if (a.length > 0) {
e.lifecycle?.releaseSkippedCalls?.(admittedIds(t.slice(o), e.validated));
break;
}
const u = [];
let d = [];
let f;
const p = [];
const settle = async (t, r, i) => {
const a = await completeStartedToolCall(e, r, i, n);
p[t] = a;
return a;
};
try {
const f = o;
try {
while (o < t.length) {
const r = t[o++];
if (!r) continue;
const i = await prepareToolCallEntry(e, r);
u.push(i);
if (!("kind" in i)) await emitToolExecutionEnd(i, e);
if (n || e.signal?.aborted) break;
}
} catch (n) {
s = mergeToolExecutionFailure(s, n);
e.lifecycle?.releaseSkippedCalls?.(admittedIds(t.slice(f), e.validated));
throw n;
}
const m = u.some((e) => "kind" in e);
if (n && e.toolPlan.executionStarted && m && !e.signal?.aborted) {
const t = getSteeringAtCheckpoint(e.config);
a = Array.isArray(t) ? t : await t;
}
for (const [e, t] of u.entries()) p[e] = "kind" in t ? void 0 : t;
const h = a.length > 0 ? void 0 : await launchParallelToolCalls(u, e.lifecycle, e.toolPlan);
s = h?.rejected ? { error: h.rejected.error } : void 0;
if (!s && h?.blocked?.intervention.detector === "repeated_tool_error") advanceToolLoopRecovery(e, h.blocked.intervention);
d = h?.started ?? [];
const g = new Set(d.map(({ index: e }) => e));
if (!n && h?.started.length && !h.rejected && !h.blocked) e.onParallelStarted?.();
try {
for (const { index: e, entry: t, outcome: n } of h?.completed ?? []) await settle(e, t, n);
} catch (n) {
s = mergeToolExecutionFailure(s, n);
e.lifecycle?.releaseSkippedCalls?.([...admittedIds(u.filter((t, n) => !g.has(n) && (e.validated.get(t.toolCall)?.kind === "prepared" || n >= (h?.rejected?.index ?? u.length))).map(({ toolCall: e }) => e), e.validated), ...admittedIds(t.slice(o), e.validated)]);
throw n;
}
const _ = a.length > 0 ? 0 : h?.rejected?.index ?? (h?.blocked ? h.blocked.index + 1 : u.length);
if (a.length > 0) {
for (const e of u) if ("kind" in e) e.execution.dispose();
}
if (a.length > 0 || s || h?.blocked) {
const n = [...admittedEntryIds(u.filter((e, t) => t >= (h?.blocked?.index ?? _) && !g.has(t))), ...admittedIds(t.slice(o), e.validated)];
e.lifecycle?.releaseSkippedCalls?.(n);
}
for (let t = _; t < u.length; t++) {
const r = u[t];
if (!r || !("kind" in r) || g.has(t) || p[t]) continue;
if (!n) r.execution.dispose();
p[t] = await completeUnstartedToolCall(e, r.toolCall, {
reason: s ? "admission" : "steering",
intervention: h?.blocked?.intervention,
args: r.execution.args,
startEmitted: true,
hideFromChannelProgress: hidesToolCallFromChannelProgress(e, r.toolCall)
});
}
if (h) {
const n = await Promise.allSettled(d.map(async ({ index: e, entry: t, outcome: n }) => settle(e, t, await n)));
d = [];
const r = !s;
s = mergeRejectedToolOutcomes(s, n);
if (r && s && o < t.length) e.lifecycle?.releaseSkippedCalls?.(admittedIds(t.slice(o), e.validated));
}
try {
if (e.lifecycle?.observeOutcome) await e.waitForPrevious?.();
for (let t of p) if (t) {
if ((t.intervention || t.loopOutcome) && !s && !e.signal?.aborted && !a.length) {
let n = t.intervention;
if (!n && t.loopOutcome && !e.toolPlan.terminalIntervention) n = e.lifecycle?.observeOutcome?.(t.loopOutcome, e.toolLoopRecoveryState);
if (n) {
l = advanceToolLoopRecovery(e, n);
c = e.toolPlan.terminalIntervention ?? c ?? n;
if (!l) t = appendToolLoopRecoveryNote(t, n);
}
}
i.push(await emitToolResultMessage(t, e.emit));
r.push(t);
}
} catch (n) {
const r = !s && a.length === 0 && o < t.length;
s = mergeToolExecutionFailure(s, n);
if (r) e.lifecycle?.releaseSkippedCalls?.(admittedIds(t.slice(o), e.validated));
throw n;
}
} catch (e) {
f = mergeToolExecutionFailure(s, e);
} finally {
f = await drainToolCallGroup(d, u, f ?? s, async ({ index: t, entry: n }, a) => {
const o = await settle(t, n, a);
i.push(await emitToolResultMessage(o, e.emit));
r.push(o);
}) ?? f;
}
if (f) throw f.error;
if (c || a.length > 0 || s || e.signal?.aborted) break;
}
if (c) {
const n = t.slice(o);
e.lifecycle?.releaseSkippedCalls?.(admittedIds(n, e.validated));
const a = await completeToolLoopInterventionBatch(e, {
toolCalls: n,
intervention: c,
terminal: l
});
const s = resolveToolBatchTermination(r);
return {
...a,
messages: [...i, ...a.messages],
terminate: l || s.terminate && (a.messages.length === 0 || a.terminate),
terminalToolCallIds: [...s.terminalToolCallIds, ...a.terminalToolCallIds]
};
}
if (!s && !e.signal?.aborted && a.length === 0) {
const t = getSteeringAtCheckpoint(e.config);
a = Array.isArray(t) ? t : await t;
}
const u = s ? "admission" : a.length > 0 ? "steering" : void 0;
try {
for (; o < t.length; o++) {
const n = t[o];
if (!n) continue;
const a = await completeUnstartedToolCall(e, n, {
reason: u,
hideFromChannelProgress: hidesToolCallFromChannelProgress(e, n)
});
i.push(await emitToolResultMessage(a, e.emit));
r.push(a);
}
} catch (e) {
throw mergeToolExecutionFailure(s, e).error;
}
return {
messages: i,
steeringMessages: a,
...resolveToolBatchTermination(r),
terminateRun: false,
...s ? { fatal: s } : {}
};
}
async function prepareToolCallEntry(e, t) {
const n = hidesToolCallFromChannelProgress(e, t);
await emitToolExecutionStart(e, t, n);
const r = await prepareToolCall(e, t);
if (r.kind === "immediate") return await finalizeToolCallOutcome(e, {
toolCall: t,
result: r.result,
isError: r.isError,
executionStarted: false,
...r.errorKind ? { errorKind: r.errorKind } : {},
...n ? { hideFromChannelProgress: true } : {}
}, t.arguments);
const i = getInternalSteeringQueueObserver(e.config.getSteeringMessages);
const a = i?.subscribe;
const o = await prepareToolCallExecution(r, {
assistantMessage: e.assistantMessage,
pendingInput: i && a ? {
hasPending: () => i.peek().length > 0,
subscribe: a
} : void 0,
toolCall: r.toolCall,
hasUnobservedAsyncToolResults: e.hasUnobservedAsyncToolResults || e.assistantMessage.content.slice(0, e.assistantMessage.content.indexOf(t)).some((e) => e.type === "toolCall" && e.async === true)
}, e.signal, e.emit, e.isLocalError);
return o.kind === "immediate" ? await finalizeExecutedToolCall(e, r, o.outcome, r.args) : {
...r,
execution: o
};
}
async function resolveToolCallTool(e, t) {
const n = e.resolved.get(t);
if (n) return n;
let r;
try {
let n = e.currentContext.tools?.find((e) => e.name === t.name);
if (!n) {
const r = await e.config.resolveDeferredTool?.({
assistantMessage: e.assistantMessage,
toolCall: t,
context: e.currentContext
}, e.signal);
if (r && r.name !== t.name) throw new Error(`Deferred tool resolver returned "${r.name}" for requested "${t.name}"`);
n = r;
if (n) e.currentContext.tools = [...e.currentContext.tools ?? [], n];
}
r = {
kind: "resolved",
...n ? { tool: n } : {}
};
} catch (t) {
if (e.isLocalError?.(t)) throw t;
r = {
kind: "error",
error: t
};
}
e.resolved.set(t, r);
return r;
}
async function prepareToolCall(e, t) {
const n = e.validated.get(t);
if (e.signal?.aborted) return immediateToolCallError("Operation aborted");
const r = n ?? await validateToolCallForBatchAdmission(e, t);
if (r.kind === "immediate") return r;
const { args: i } = r;
try {
if (e.config.beforeToolCall) {
const n = await e.config.beforeToolCall({
assistantMessage: e.assistantMessage,
toolCall: t,
args: i,
context: e.currentContext
}, e.signal);
if (e.signal?.aborted) return immediateToolCallError("Operation aborted");
if (n?.block) return immediateToolCallError(n.reason || "Tool execution was blocked");
}
if (e.signal?.aborted) return immediateToolCallError("Operation aborted");
return r;
} catch (t) {
if (e.isLocalError?.(t)) throw t;
return immediateToolCallError(coerceErrorMessage(t));
}
}
async function validateToolCallForBatchAdmission(e, t) {
const n = await resolveToolCallTool(e, t);
if (n.kind === "error") return immediateToolCallError(e.signal?.aborted ? "Operation aborted" : coerceErrorMessage(n.error));
const r = n.tool;
if (!r) return immediateToolCallError(`Tool ${t.name} not found`, "unknown-tool");
let i;
try {
const e = r.prepareArguments ? r.prepareArguments(t.arguments) : t.arguments;
i = e === t.arguments ? t : {
...t,
arguments: e
};
} catch (e) {
return immediateToolPreparationError(e);
}
let a;
try {
a = validateToolArguments(r, i);
} catch (e) {
return immediateToolArgumentValidationError(e);
}
return {
kind: "prepared",
toolCall: t,
tool: r,
args: a
};
}
//#endregion
//#region packages/agent-core/src/pending-message-queue.ts
var PendingMessageQueue = class {
constructor(e) {
this.messages = [];
this.inputListeners = /* @__PURE__ */ new Set();
this.submitted = /* @__PURE__ */ new Set();
this.inFlight = [];
this.cancelled = /* @__PURE__ */ new WeakSet();
this.mode = e;
}
enqueue(e) {
this.admit(e)();
}
admit(e) {
this.messages.push(e);
return () => {
const e = [];
const t = this.onChange ? [this.onChange, ...this.inputListeners] : [...this.inputListeners];
for (const n of t) try {
n();
} catch (t) {
e.push(t);
}
if (e.length === 1) throw e[0];
if (e.length > 1) throw new AggregateError(e, "Steering notifications failed");
};
}
subscribe(e) {
this.inputListeners.add(e);
return () => {
this.inputListeners.delete(e);
};
}
peek() {
return (this.inFlight.length > 0 ? this.inFlight : this.messages).filter((e) => !isOpenClawSystemUpdateMessage(e)).slice(0, this.mode === "all" ? void 0 : 1);
}
reserve(e) {
for (const t of e) this.submitted.add(t);
return () => {
for (const t of e) this.submitted.delete(t);
};
}
hasItems() {
return this.messages.some((e) => !isOpenClawSystemUpdateMessage(e));
}
drain() {
const e = this.messages.filter((e) => !isOpenClawSystemUpdateMessage(e));
let t = this.mode === "all" ? e.length : 1;
const n = e.findIndex((e) => !this.submitted.has(e));
if (n > 0) t = Math.min(t, n);
return this.drainMatching(t, (e) => !isOpenClawSystemUpdateMessage(e));
}
drainContext() {
return this.drainMatching(Infinity, isOpenClawSystemUpdateMessage);
}
drainMatching(e, t) {
const n = [];
this.messages = this.messages.filter((r) => {
if (n.length >= e || !t(r)) return true;
n.push(r);
return false;
});
this.inFlight.push(...n);
return n;
}
commit(e) {
this.submitted.delete(e);
this.cancelled.delete(e);
const t = this.inFlight.indexOf(e);
if (t >= 0) this.inFlight.splice(t, 1);
}
restore() {
this.messages = [...this.inFlight, ...this.messages];
this.inFlight = [];
this.submitted.clear();
}
cancelFirst(e) {
const t = this.messages.findIndex(e);
const n = this.messages[t];
if (n) {
if (this.submitted.has(n)) return;
return this.messages.splice(t, 1)[0];
}
const r = this.inFlight.findIndex(e);
const i = this.inFlight[r];
if (!i || this.submitted.has(i)) return;
this.inFlight.splice(r, 1);
this.cancelled.add(i);
return i;
}
consumeCancellation(e) {
return this.cancelled.delete(e);
}
clear() {
this.messages = this.messages.filter((e) => this.submitted.has(e));
this.inFlight = this.inFlight.filter((e) => this.submitted.has(e));
this.cancelled = /* @__PURE__ */ new WeakSet();
}
};
//#endregion
//#region packages/agent-core/src/agent.ts
function defaultConvertToLlm(e) {
return e.filter((e) => e.role === "user" || e.role === "assistant" || e.role === "toolResult");
}
const DEFAULT_MODEL = {
id: "unknown",
name: "unknown",
api: "unknown",
provider: "unknown",
baseUrl: "",
reasoning: false,
input: [],
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
contextWindow: 0,
maxTokens: 0
};
/**
* Stateful wrapper around the low-level agent loop.
*
* `Agent` owns the current transcript, emits lifecycle events, executes tools,
* and exposes queueing APIs for steering and follow-up messages.
*/
var Agent$1 = class {
constructor(e = {}) {
this.listeners = /* @__PURE__ */ new Set();
this.toolLoopRecoveryState = { criticalToolLoopSeen: false };
const t = e.initialState;
let n = t?.tools?.slice() ?? [];
let r = t?.messages?.slice() ?? [];
this.mutableState = {
systemPrompt: t?.systemPrompt ?? "",
model: t?.model ?? DEFAULT_MODEL,
thinkingLevel: t?.thinkingLevel ?? "off",
get tools() {
return n;
},
set tools(e) {
n = e.slice();
},
get messages() {
return r;
},
set messages(e) {
r = e.slice();
},
isStreaming: false,
streamingMessage: void 0,
pendingToolCalls: /* @__PURE__ */ new Set(),
errorMessage: void 0
};
this.convertToLlm = e.convertToLlm ?? defaultConvertToLlm;
this.transformContext = e.transformContext;
this.runtime = e.runtime;
this.streamFn = resolveAgentCoreStreamFn(e.runtime, e.streamFn);
this.getApiKey = e.getApiKey;
this.onPayload = e.onPayload;
this.onResponse = e.onResponse;
this.beforeToolCall = e.beforeToolCall;
this.resolveDeferredTool = e.resolveDeferredTool;
this.afterToolCall = e.afterToolCall;
this.afterToolOutcome = e.afterToolOutcome;
this.prepareNextTurn = e.prepareNextTurn;
this.prepareNextTurnWithContext = e.prepareNextTurnWithContext;
this.steeringQueue = new PendingMessageQueue(e.steeringMode ?? "one-at-a-time");
this.followUpQueue = new PendingMessageQueue(e.followUpMode ?? "one-at-a-time");
this.sessionId = e.sessionId;
this.thinkingBudgets = e.thinkingBudgets;
this.transport = e.transport ?? "auto";
this.maxRetryDelayMs = e.maxRetryDelayMs;
this.toolExecution = e.toolExecution ?? "parallel";
}
/**
* Subscribe to agent lifecycle events.
*
* Listener promises are awaited in subscription order and are included in
* the current run's settlement. Listeners also receive the active abort
* signal for the current run.
*
* `agent_end` is the final emitted event for a run, but the agent does not
* become idle until all awaited listeners for that event have settled.
*/
subscribe(e) {
this.listeners.add(e);
return () => this.listeners.delete(e);
}
/**
* Current agent state.
*
* Assigning `state.tools` or `state.messages` copies the provided top-level array.
*/
get state() {
return this.mutableState;
}
/** Controls how queued steering messages are drained. */
set steeringMode(e) {
this.steeringQueue.mode = e;
}
get steeringMode() {
return this.steeringQueue.mode;
}
/** Controls how queued follow-up messages are drained. */
set followUpMode(e) {
this.followUpQueue.mode = e;
}
get followUpMode() {
return this.followUpQueue.mode;
}
/**
* Queue a message for the active run. After its first tool starts, an assistant
* message's unstarted sequential tail can be skipped. Parallel batches always run.
*/
steer(e) {
this.admitSteeringMessage(e)();
}
/** Install admitted input synchronously; notify listeners after admission custody ends. */
admitSteeringMessage(e) {
return this.steeringQueue.admit(e);
}
/** Cancel queued input unless a live provider response may already have admitted it. */
cancelSteeringMessage(e) {
return this.steeringQueue.cancelFirst(e);
}
/** Queue a message to run only after the agent would otherwise stop. */
followUp(e) {
this.followUpQueue.enqueue(e);
}
/** Remove queued steering messages that have not been submitted to a live response. */
clearSteeringQueue() {
this.steeringQueue.clear();
}
/** Remove all queued follow-up messages. */
clearFollowUpQueue() {
this.followUpQueue.clear();
}
/** Remove all queued steering and follow-up messages. */
clearAllQueues() {
this.clearSteeringQueue();
this.clearFollowUpQueue();
}
/** Returns true when either queue contains pending input that can start a turn. */
hasQueuedMessages() {
return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
}
/** Active abort signal for the current run, if any. */
get signal() {
return this.activeRun?.abortController.signal;
}
/** Abort the current run, if one is active. */
abort(e) {
this.activeRun?.abortController.abort(e);
}
/**
* Resolve when the current run and all awaited event listeners have finished.
*
* This resolves after `agent_end` listeners settle.
*/
waitForIdle() {
return this.activeRun?.promise ?? Promise.resolve();
}
/** Clear transcript state, runtime state, and queued messages. */
reset() {
this.mutableState.messages = [];
this.mutableState.isStreaming = false;
this.mutableState.streamingMessage = void 0;
this.mutableState.pendingToolCalls = /* @__PURE__ */ new Set();
this.mutableState.errorMessage = void 0;
this.toolLoopRecoveryState = { criticalToolLoopSeen: false };
this.clearAllQueues();
}
async prompt(e, t) {
if (this.activeRun) throw new Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");
let n;
if (Array.isArray(e)) n = e;
else if (typeof e !== "string") n = [e];
else {
const r = [{
type: "text",
text: e
}];
if (t && t.length > 0) r.push(...t);
n = [{
role: "user",
content: r,
timestamp: Date.now()
}];
}
await this.runPromptMessages(n);
}
/** Continue from a user, tool result, or failed assistant without rewriting its history. */
async continue() {
if (this.activeRun) throw new Error("Agent is already processing. Wait for completion before continuing.");
const e = this.mutableState.messages[this.mutableState.messages.length - 1];
if (!e) throw new Error("No messages to continue from");
if (e.role === "assistant" || e.role === "toolResult") {
const e = this.steeringQueue.drain();
if (e.length > 0) {
await this.runPromptMessages(e, { skipInitialSteeringPoll: true });
return;
}
const t = this.followUpQueue.drain();
if (t.length > 0) {
await this.runPromptMessages(t);
return;
}
}
if (e.role === "assistant" && e.stopReason !== "error" && e.stopReason !== "aborted") throw new TranscriptNotContinuableError(e.role);
await this.runPromptMessages([]);
}
async runPromptMessages(e, t = {}) {
if (this.activeRun) throw new Error("Agent is already processing.");
const n = new AbortController();
let resolvePromise = () => {};
const r = new Promise((e) => {
resolvePromise = e;
});
this.activeRun = {
promise: r,
resolve: resolvePromise,
abortController: n
};
this.mutableState.isStreaming = true;
this.mutableState.streamingMessage = void 0;
this.mutableState.errorMessage = void 0;
try {
const r = n.signal;
this.preparedSystemPrompt = prepareSystemPrompt(this.mutableState.systemPrompt, this.preparedSystemPrompt);
await runAgentLoop(e, {
systemPrompt: this.mutableState.systemPrompt,
preparedSystemPrompt: this.preparedSystemPrompt,
messages: this.mutableState.messages,
tools: this.mutableState.tools.slice()
}, this.createLoopConfig(t), (e) => this.processEvents(e), r, this.streamFn, this.runtime);
} catch (e) {
if (this.runtime?.isLocalError?.(e)) throw e;
const t = n.signal.aborted;
const r = createFailureMessage(this.mutableState.model, e, t);
await this.processEvents({
type: "message_start",
message: r
});
await this.processEvents({
type: "message_end",
message: r
});
await this.processEvents({
type: "turn_end",
message: r,
toolResults: []
});
const i = [r];
if (t && !isTurnHandoffAbort(this.signal)) await appendInterruptedTurnMessage(i, (e) => this.processEvents(e));
await this.processEvents({
type: "agent_end",
messages: i
});
} finally {
this.steeringQueue.restore();
this.followUpQueue.restore();
this.mutableState.isStreaming = false;
this.mutableState.streamingMessage = void 0;
this.mutableState.pendingToolCalls = /* @__PURE__ */ new Set();
this.activeRun?.resolve();
this.activeRun = void 0;
}
}
createLoopConfig(e = {}) {
const t = this.steeringQueue;
let n = e.skipInitialSteeringPoll === true;
const drainSteeringMessages = () => {
if (n) {
n = false;
return [];
}
return this.steeringQueue.drain();
};
const r = attachInternalSyncSteeringGetter(async () => drainSteeringMessages(), drainSteeringMessages, {
peek: () => this.steeringQueue.peek(),
subscribe: (e) => this.steeringQueue.subscribe(e),
drainContext: () => [...this.steeringQueue.drainContext(), ...this.followUpQueue.drainContext()],
reserve: (e) => this.steeringQueue.reserve(e),
set onChange(e) {
t.onChange = e;
}
});
return {
model: this.mutableState.model,
repetitionGuard: getInternalRepetitionGuard(this),
thinkingLevel: this.mutableState.thinkingLevel,
reasoning: resolveAgentReasoningOption(this.mutableState.model, this.mutableState.thinkingLevel),
sessionId: this.sessionId,
onPayload: this.onPayload,
onResponse: this.onResponse,
transport: this.transport,
thinkingBudgets: this.thinkingBudgets,
maxRetryDelayMs: this.maxRetryDelayMs,
toolExecution: this.toolExecution,
beforeToolCall: this.beforeToolCall,
beforeToolBatch: getInternalBeforeToolBatch(this),
completesToolTurn: getInternalToolTurnCompletion(this),
toolLoopRecoveryState: this.toolLoopRecoveryState,
resolveDeferredTool: this.resolveDeferredTool,
afterToolCall: this.afterToolCall,
afterToolOutcome: this.afterToolOutcome,
prepareNextTurn: this.prepareNextTurnWithContext || this.prepareNextTurn ? async (e) => {
if (this.prepareNextTurnWithContext) return await this.prepareNextTurnWithContext(e, this.signal);
return await this.prepareNextTurn?.(this.signal);
} : void 0,
convertToLlm: this.convertToLlm,
transformContext: this.transformContext,
getApiKey: this.getApiKey,
getSteeringMessages: r,
getFollowUpMessages: async () => this.followUpQueue.drain(),
consumeQueuedMessageCancellation: (e) => this.steeringQueue.consumeCancellation(e) || this.followUpQueue.consumeCancellation(e)
};
}
/**
* Reduce internal state for a loop event, then await listeners.
*
* `agent_end` only means no further loop events will be emitted. The run is
* considered idle later, after all awaited listeners for `agent_end` finish
* and run cleanup clears runtime-owned state.
*/
async processEvents(e) {
let t = e.type === "message_end" && e.message.role === "toolResult" ? e.message : void 0;
const n = this.mutableState.messages.length;
switch (e.type) {
case "agent_start":
case "turn_start":
case "tool_execution_update": break;
case "message_start":
if (e.message.role !== "toolResult" || this.mutableState.streamingMessage?.role !== "assistant") this.mutableState.streamingMessage = e.message;
break;
case "message_update":
this.mutableState.streamingMessage = e.message;
break;
case "message_end":
if (e.message.role !== "toolResult" || this.mutableState.streamingMessage?.role !== "assistant") this.mutableState.streamingMessage = void 0;
this.mutableState.messages.push(e.message);
this.steeringQueue.commit(e.message);
this.followUpQueue.commit(e.message);
break;
case "tool_execution_start":
case "tool_execution_end": {
const t = new Set(this.mutableState.pendingToolCalls);
if (e.type === "tool_execution_start") t.add(e.toolCallId);
else t.delete(e.toolCallId);
this.mutableState.pendingToolCalls = t;
break;
}
case "turn_end":
if (e.message.role === "assistant" && e.message.errorMessage) this.mutableState.errorMessage = e.message.errorMessage;
break;
case "agent_end": this.mutableState.streamingMessage = void 0;
}
const r = this.activeRun?.abortController.signal;
if (!r) throw new Error("Agent listener invoked outside active run");
for (const i of this.listeners) try {
await i(e, r);
} finally {
if (t && e.type === "message_end" && e.message.role === "toolResult" && e.message !== t && this.mutableState.messages[n] === t) {
t = e.message;
this.mutableState.messages[n] = t;
}
}
}
};
//#endregion
//#region packages/agent-core/src/harness/prompt-template-arguments.ts
/** Parse an argument string using simple shell-style single and double quotes. */
function parseCommandArgs(e) {
const t = [];
let n = "";
let r = null;
let i = false;
for (const a of e) if (r) {
if (a === r) r = null;
else {
i = true;
n += a;
}
} else if (a === "\"" || a === "'") {
i = true;
r = a;
} else if (/\s/.test(a)) {
if (i) {
t.push(n);
n = "";
i = false;
}
} else {
i = true;
n += a;
}
if (i) t.push(n);
return t;
}
/**
* Substitute prompt template placeholders (`$1`, `$@`, `$ARGUMENTS`, `${@:N}`, `${@:N:L}`) with command arguments.
*
* Unsafe integer placeholders resolve to empty text instead of throwing, so malformed templates cannot abort prompt
* loading or invocation.
*/
function substituteArgs(e, t) {
const n = t.join(" ");
return e.replace(/\$(\d+)|\$\{@:(\d+)(?::(\d+))?\}|\$ARGUMENTS|\$@/g, (e, r, i, a) => {
if (r !== void 0) {
const e = parseStrictNonNegativeInteger(r);
if (e === void 0 || e <= 0) return "";
return t[e - 1] ?? "";
}
if (i !== void 0) {
const e = parseStrictNonNegativeInteger(i);
if (e === void 0) return "";
const n = Math.max(0, e - 1);
if (a) {
const e = parseStrictNonNegativeInteger(a);
if (e === void 0) return "";
return t.slice(n, n + e).join(" ");
}
return t.slice(n).join(" ");
}
return n;
});
}
//#endregion
//#region packages/agent-core/src/harness/compaction/branch-summarization.ts
/** Collect entries that should be summarized before navigating to a different session tree entry. */
function collectEntriesForBranchSummaryFromBranches(e, t) {
const n = new Set(e.map((e) => e.id));
const r = t.findLast((e) => n.has(e.id))?.id ?? null;
const i = r === null ? 0 : e.findIndex((e) => e.id === r) + 1;
return {
entries: e.slice(i),
commonAncestorId: r
};
}
/** Prepare branch entries for summarization within an optional token budget. */
function prepareBranchEntries(e, t = 0) {
const n = [];
const r = createFileOps();
let i = 0;
for (const t of e) if (t.type === "branch_summary" && !t.fromHook && t.details) mergeSummaryFileOperations(r, t.details);
for (const a of e.toReversed()) {
const e = projectSessionEntryMessage(a);
if (!e) continue;
extractFileOpsFromMessage(e, r);
const o = serializeConversation(convertToLlm([e]));
const s = o ? Math.ceil((estimateStringChars(o) + (i > 0 ? 2 : 0)) / 4) : 0;
if (t > 0 && i + s > t) break;
n.push(e);
i += s;
}
return {
messages: n.toReversed(),
fileOps: r,
totalTokens: i
};
}
const BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.
Summary of that exploration:
`;
const BRANCH_SUMMARY_PROMPT = buildSummaryCheckpointPrompt({
introduction: "Create a structured summary of this conversation branch for context when returning later.",
goal: "[What was the user trying to accomplish in this branch?]",
constraints: "- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]",
inProgress: "- [ ] [Work that was started but not finished]",
blocked: "- [Issues preventing progress, if any]",
decisions: "- **[Decision]**: [Brief rationale]",
nextSteps: "1. [What should happen next to continue this work]"
});
/** Generate a summary for abandoned branch entries. */
async function generateBranchSummary(e, t) {
const { model: n, apiKey: r, headers: i, signal: a, customInstructions: o, replaceInstructions: s, reserveTokens: c = 16384 } = t;
const l = s && o ? o : BRANCH_SUMMARY_PROMPT + (o ? `\n\nAdditional focus: ${o}` : "");
const u = "<conversation>\n";
const d = `\n</conversation>\n\n${l}`;
const f = Math.ceil(estimateStringChars(`${SUMMARIZATION_SYSTEM_PROMPT}${u}${d}`) / 4);
const p = n.contextWindow || 128e3;
const m = Math.min(2048, Math.max(1, Math.floor(p / 4)), n.maxTokens > 0 ? n.maxTokens : 2048);
const h = c < p ? c : Math.floor(p / 2);
const g = p - Math.max(m + f, h);
if (g <= 0) return err(new BranchSummaryError("summarization_failed", "Branch summary instructions and output reservation exceed the model context window."));
const { messages: _, fileOps: v } = prepareBranchEntries(e, g);
const y = serializeConversation(convertToLlm(_));
if (!y) {
if (e.some((e) => {
const t = projectSessionEntryMessage(e);
return t && serializeConversation(convertToLlm([t])).length > 0;
})) return err(new BranchSummaryError("summarization_failed", "The latest branch content cannot fit beside the summary instructions and output. Reduce the focus instructions or select a larger context window."));
return ok({
summary: "No content to summarize",
readFiles: [],
modifiedFiles: []
});
}
const b = `${u}${y}${d}`;
const x = createSummarizationContext(b);
const S = {
apiKey: r,
headers: i,
signal: a,
maxTokens: m
};
const C = t.streamFn ? await consumeAgentCoreStream(t.streamFn(n, x, S), t.runtime) : await resolveAgentCoreCompleteFn(t.runtime)(n, x, S);
t.runtime?.internalUsageSink?.(C.usage);
if (C.stopReason === "aborted") return err(new BranchSummaryError("aborted", C.errorMessage || "Branch summary aborted"));
if (C.stopReason === "error") return err(new BranchSummaryError("summarization_failed", `Branch summary failed: ${C.errorMessage || "Unknown error"}`));
if (C.stopReason === "length") return err(new BranchSummaryError("summarization_failed", "Branch summary failed: summary truncated at the output token limit"));
const w = extractSummaryText(C);
if (w === void 0) return err(new BranchSummaryError("summarization_failed", "Branch summary failed: model returned no summary text"));
const { readFiles: T, modifiedFiles: E } = computeFileLists(v);
return ok({
summary: BRANCH_SUMMARY_PREAMBLE + w + formatFileOperations(T, E),
readFiles: T,
modifiedFiles: E
});
}
//#endregion
//#region src/agents/runtime/proxy.ts
/**
* Proxy stream function for apps that route LLM calls through a server.
* The server manages auth and proxies requests to LLM providers.
*/
const PROXY_ERROR_BODY_MAX_BYTES = 16777216;
const PROXY_SSE_PENDING_BUFFER_MAX_BYTES = 16777216;
const PROXY_SSE_READ_IDLE_TIMEOUT_MS = 12e4;
/**
* Stream function that proxies through a server instead of calling LLM providers directly.
* The server strips the partial field from delta events to reduce bandwidth.
* We reconstruct the partial message client-side.
*
* Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.
*
* @example
* ```typescript
* const agent = new Agent({
* streamFn: (model, context, options) =>
* streamProxy(model, context, {
* ...options,
* authToken: await getAuthToken(),
* proxyUrl: "https://genai.example.com",
* }),
* });
* ```
*/
function buildProxyRequestOptions(e) {
return {
temperature: e.temperature,
maxTokens: e.maxTokens,
reasoning: e.reasoning,
cacheRetention: e.cacheRetention,
promptCacheTtl: e.promptCacheTtl,
sessionId: e.sessionId,
promptCacheKey: e.promptCacheKey,
metadata: e.metadata,
transport: e.transport,
thinkingBudgets: e.thinkingBudgets,
maxRetryDelayMs: e.maxRetryDelayMs,
timeoutMs: e.timeoutMs
};
}
function sanitizeProxyModel(e) {
const { headers: t, ...n } = e;
return n;
}
function createProxyRequestTimeoutError(e) {
const t = /* @__PURE__ */ new Error(`Proxy request timed out after ${e}ms`);
t.name = "TimeoutError";
return t;
}
function buildProxyRequestAbort(e, t) {
const n = new AbortController();
const r = setTimeout(() => {
n.abort(createProxyRequestTimeoutError(t));
}, t);
return {
signal: e ? AbortSignal.any([e, n.signal]) : n.signal,
clear: () => {
clearTimeout(r);
}
};
}
function streamProxy(e, t, n) {
const r = new event_stream_exports.AssistantMessageEventStream();
(async () => {
const i = {
role: "assistant",
stopReason: "stop",
content: [],
api: e.api,
provider: e.provider,
model: e.id,
usage: makeZeroUsageSnapshot(),
timestamp: Date.now()
};
let a;
let o = false;
let s;
let c;
const l = resolvePositiveTimerTimeoutMs(n.timeoutMs, PROXY_SSE_READ_IDLE_TIMEOUT_MS);
const cancelReader = (e) => a ? s ??= a.cancel(e).catch(() => void 0) : Promise.resolve();
const abortHandler = () => void cancelReader("Request aborted by user");
n.signal?.addEventListener("abort", abortHandler);
try {
const c = buildProxyRequestAbort(n.signal, l);
const u = await fetch(`${n.proxyUrl}/api/stream`, {
method: "POST",
headers: {
Authorization: `Bearer ${n.authToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: sanitizeProxyModel(e),
context: t,
options: buildProxyRequestOptions(n)
}),
signal: c.signal
}).catch((e) => {
if (!n.signal?.aborted && c.signal.aborted && e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError" || e.message === "Request was aborted")) throw new Error(`Proxy request timed out after ${l}ms`, { cause: e });
throw e;
}).finally(() => {
c.clear();
});
if (!u.ok) {
let e = `Proxy error: ${u.status} ${u.statusText}`;
try {
const t = await readResponseWithLimit(u, PROXY_ERROR_BODY_MAX_BYTES, {
onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`Proxy error body exceeded ${e} bytes`),
chunkTimeoutMs: l,
onIdleTimeout: ({ chunkTimeoutMs: e }) => /* @__PURE__ */ new Error(`Proxy error body stalled: no data received for ${e}ms`)
});
const n = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(t));
if (n?.error) e = `Proxy error: ${n.error}`;
} catch (e) {
if (e instanceof Error && e.message.startsWith("Proxy error body")) throw e;
}
throw new Error(e);
}
a = u.body.getReader();
const d = new TextDecoder();
let f = "";
let p = 0;
let m = false;
const h = /* @__PURE__ */ new Map();
const processSseLine = (e) => {
if (!e.startsWith("data:")) return false;
const t = e.slice(5).trim();
if (!t) return false;
const n = processProxyEvent(JSON.parse(t), i, h);
if (!n) return false;
r.push(n);
return n.type === "done" || n.type === "error";
};
while (!m) {
const { done: e, value: t } = await withResponseBodyTimeout({
timeoutMs: l,
onTimeout: () => /* @__PURE__ */ new Error(`Proxy SSE stream stalled: no data received for ${l}ms`),
cancel: cancelReader,
read: () => a.read().catch((e) => {
throw toStringifiedError(e);
})
});
if (e) {
o = s === void 0;
break;
}
if (n.signal?.aborted) throw new Error("Request aborted by user");
for (let e = 0; e < t.byteLength && !m;) {
const n = t.indexOf(10, e);
const r = n === -1 ? t.byteLength : n;
p += r - e;
if (p > PROXY_SSE_PENDING_BUFFER_MAX_BYTES) throw new Error(`Proxy SSE pending buffer exceeded ${PROXY_SSE_PENDING_BUFFER_MAX_BYTES} bytes`);
f += d.decode(t.subarray(e, n === -1 ? r : r + 1), { stream: true });
if (n === -1) break;
m = processSseLine(f.slice(0, -1));
f = "";
p = 0;
e = r + 1;
}
}
if (n.signal?.aborted) throw new Error("Request aborted by user");
if (o) {
f += d.decode();
if (f.trim()) m = processSseLine(f);
}
if (!m) throw new Error("Proxy stream ended before terminal event");
r.end();
} catch (e) {
c = e;
const t = e instanceof Error ? e.message : String(e);
const a = n.signal?.aborted ? "aborted" : "error";
i.stopReason = a;
i.errorMessage = t;
r.push({
type: "error",
reason: a,
error: i
});
r.end();
} finally {
try {
if (a && !o) cancelReader(c);
a?.releaseLock();
} catch {}
n.signal?.removeEventListener("abort", abortHandler);
}
})();
return r;
}
function processProxyEvent(e, t, n) {
switch (e.type) {
case "start": return {
type: "start",
partial: t
};
case "text_start":
t.content[e.contentIndex] = {
type: "text",
text: "",
...e.contentSignature !== void 0 ? { textSignature: e.contentSignature } : {}
};
return {
type: "text_start",
contentIndex: e.contentIndex,
partial: t
};
case "text_delta":
case "thinking_delta":
case "toolcall_delta": {
const r = t.content[e.contentIndex];
const i = e.type === "text_delta" ? "text" : e.type === "thinking_delta" ? "thinking" : "toolCall";
if (r?.type !== i) throw new Error(`Received ${e.type} for non-${i} content`);
if (r.type === "text") r.text += e.delta;
else if (r.type === "thinking") r.thinking += e.delta;
else {
const i = (r.partialJson ?? "") + e.delta;
r.partialJson = i;
const a = n.get(e.contentIndex);
if (!a) throw new Error("Received toolcall_delta without a preview schedule");
if (a(i.length)) r.arguments = parseStreamingJson(i);
t.content[e.contentIndex] = { ...r };
}
return {
type: e.type,
contentIndex: e.contentIndex,
delta: e.delta,
partial: t
};
}
case "text_end":
case "thinking_end": {
const n = t.content[e.contentIndex];
const r = e.type === "text_end" ? "text" : "thinking";
if (n?.type !== r) throw new Error(`Received ${e.type} for non-${r} content`);
if (n.type === "text") {
if (e.contentSignature !== void 0) n.textSignature = e.contentSignature;
} else n.thinkingSignature = e.contentSignature;
return {
type: e.type,
contentIndex: e.contentIndex,
content: n.type === "text" ? n.text : n.thinking,
partial: t
};
}
case "thinking_start":
t.content[e.contentIndex] = {
type: "thinking",
thinking: ""
};
return {
type: "thinking_start",
contentIndex: e.contentIndex,
partial: t
};
case "toolcall_start": {
const r = {
type: "toolCall",
id: e.id,
name: e.toolName,
arguments: {},
partialJson: ""
};
t.content[e.contentIndex] = r;
n.set(e.contentIndex, createToolArgumentPreviewSchedule());
return {
type: "toolcall_start",
contentIndex: e.contentIndex,
partial: t
};
}
case "toolcall_end": {
const r = t.content[e.contentIndex];
if (r?.type === "toolCall") {
r.arguments = r.partialJson ? parseTerminalToolCallArguments(r.partialJson) : {};
n.delete(e.contentIndex);
delete r.partialJson;
return {
type: "toolcall_end",
contentIndex: e.contentIndex,
toolCall: r,
partial: t
};
}
return;
}
case "done":
t.stopReason = e.reason;
t.usage = e.usage;
return {
type: "done",
reason: e.reason,
message: t
};
case "error":
t.stopReason = e.reason;
t.errorMessage = e.errorMessage;
t.usage = e.usage;
return {
type: "error",
reason: e.reason,
error: t
};
default:
console.warn(`Unhandled proxy event type: ${e.type}`);
return;
}
}
//#endregion
//#region src/plugin-sdk/agent-core.ts
/** Runtime adapter that lets the package agent-core use OpenClaw LLM helpers. */
const openClawAgentCoreRuntime = {
isLocalError: (e) => {
if (isLocalStorageOutcomeError(e)) return true;
try {
return isSqliteTranscriptMutationConflict(e);
} catch {
return false;
}
},
runStream: runPluginStreamConsumer,
completeSimple: ((e, t, n) => completeSimple(e, t, n)),
streamSimple: ((e, t, n) => streamSimple(e, t, n))
};
/** Agent-core class preconfigured with OpenClaw runtime dependencies. */
var Agent = class extends Agent$1 {
constructor(e = {}) {
super({
runtime: openClawAgentCoreRuntime,
...e
});
}
};
//#endregion
export { generateBranchSummary as a, substituteArgs as c, collectEntriesForBranchSummaryFromBranches as i, runAgentLoop as l, openClawAgentCoreRuntime as n, prepareBranchEntries as o, streamProxy as r, parseCommandArgs as s, Agent as t, appendTextDeltaToAssistantMessage as u };