openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,084 lines • 72.1 kB
JavaScript
import { n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import { n as sliceUtf16Safe, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { i as throwCollectedErrors } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as notifyListeners, r as registerListener } from "./listeners-Cb2-CnP8.mjs";
import { k as walkDirectorySync } from "./fs-safe-BbWvmdVn.mjs";
import { t as freezeJsonSnapshot } from "./immutable-data-Y7xVjZoy.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs";
import { r as scheduleAbsoluteDeadline } from "./absolute-deadline-kK4DcdPs.mjs";
import { t as createWindowsOutputDecoder } from "./windows-encoding-BGmFeZe1.mjs";
import { a as createCommandTerminationController, s as releaseChildProcessOutputAfterExit } from "./exec-runner-Br73vG-X.mjs";
import { c as spawnCommand, d as waitForCommandSpawn } from "./exec-spawn-DMKoejF-.mjs";
import "./exec-aRIvS9s4.mjs";
import { i as sameSessionTranscriptTargetBinding } from "./transcript-target-binding-BvjuRqS9.mjs";
import { r as AGENT_RUN_RESTART_ABORT_ERROR_CODE } from "./run-termination-0Ig0-bk6.mjs";
import { a as annotateInterSessionPromptText } from "./input-provenance-DupvvURj.mjs";
import { p as copyInternalToolResultState } from "./internal-hooks-Ch3rqxs-.mjs";
import { i as gateAgentToolExecution } from "./agent-tool-availability-ecKW8hOH.mjs";
import { n as isOwnedTranscriptPayload } from "./transcript-json-Cy82tIe1.mjs";
import { t as cloneTranscriptView } from "./transcript-snapshot-Dc4djFs_.mjs";
import { r as attachRuntimePromptMediaFacts } from "./media-facts-B-0Dpo5L.mjs";
import { i as orderSystemUpdateMessages, r as isOpenClawSystemUpdateMessage } from "./operator-messages-B9HgXnnQ.mjs";
import { f as resolvePendingRuntimeContextReplay } from "./internal-runtime-context-BEUlDNuI.mjs";
import { c as substituteArgs, s as parseCommandArgs } from "./agent-core-DiRTR2U_.mjs";
import { n as estimateTokens } from "./compaction-cut-point-CEj7MSFJ.mjs";
import { c as mergePreparedUserTurnMessageForRuntime, f as readModelPromptProjection } from "./session-transcript-rewrite-effects-BVKR4US3.mjs";
import { i as rethrowIncognitoSessionError } from "./incognito-session-error-BxQdjUZa.mjs";
import { t as warnSessionPersistenceDeprecation } from "./session-persistence-deprecation-B7LsOH2X.mjs";
import { m as withOwnedSessionRestartAbortWrite, y as withSessionTranscriptWriteAssertion } from "./transcript-write-context-_7rz2F7z.mjs";
import { t as applyAssistantDeliveryDirectives } from "./transcript-assistant-delivery-Ddb-cbeg.mjs";
import { d as withMessageInjectionAdmission, t as MessageInjectionAcceptedUnconfirmedError, u as enqueueMessageInjection } from "./message-injection-authority-B9SdalrV.mjs";
import { n as getModelRegistryRuntime } from "./model-registry.core-DcVMaqxb.mjs";
import { s as getStreamLlmRuntime } from "./model-runtime-binding-3f0QcVoj.mjs";
import { t as extractFrontmatterBlock } from "./frontmatter-CLR6jwh6.mjs";
import { n as createSyntheticSourceInfo } from "./source-info-BSApnBJN.mjs";
import { t as collectTextContentBlocks } from "./content-blocks-DgfxPwgj.mjs";
import { n as isToolResultError } from "./tool-result-error-B2GHe83l.mjs";
import { f as shouldRetainSteeringRuntimeContext, r as attachSteeringRuntimeContext, s as getSteeringRuntimeContext } from "./runtime-context-prompt-CRmsG0oC.mjs";
import { t as stripStaleAssistantUsageBeforeLatestCompaction } from "./compaction-usage-DmR900jF.mjs";
import { n as stripStaleThinkingSignaturesForCompactionReplay } from "./thinking-signatures-BKYzkyKv.mjs";
import "./runtime-D47BXwOO.mjs";
import { n as readRuntimePromptImageFactIndexes } from "./runtime-prompt-image-provenance-Cb0Aq_Rw.mjs";
import { t as attachRuntimeUserTurnTranscriptContext } from "./user-turn-transcript-runtime-context-BZjNfwCQ.mjs";
import { n as CONFIG_DIR_NAME, r as getDocsPath } from "./package-metadata-C27BOCp8.mjs";
import { _ as withSessionManagerAppend, b as sessionManagerAppendPromptContext, x as SessionMetadataCommittedError, y as getModelPromptProjectionAppend } from "./session-manager-DuaaMI5O.mjs";
import { a as withSessionManagerWriteAssertion } from "./session-manager-write-admission-CUQ2naL2.mjs";
import { p as interactiveAgentTheme } from "./tools-EkGDfRbZ.mjs";
import { t as createSessionManagerRuntimeRegistry } from "./session-manager-runtime-registry-nD6JfovM.mjs";
import { c as withCompactionQueuedContext, r as createCompactionRequestBudget, s as takePromptCompactionRequestBudget } from "./request-budget-CDN2iAaH.mjs";
import { readFileSync, statSync } from "node:fs";
import * as path$1 from "node:path";
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
import { homedir } from "node:os";
import { parse as parse$1 } from "yaml";
import { cleanupSessionResources } from "@openclaw/ai/internal/runtime";
//#region src/agents/compaction-replay.ts
/** Keep every transcript rebuild safe for the next provider request. */
function sanitizeCompactionReplayMessages(e) {
return stripStaleThinkingSignaturesForCompactionReplay(stripStaleAssistantUsageBeforeLatestCompaction(e));
}
//#endregion
//#region src/agents/utils/frontmatter.ts
const normalizeNewlines = (e) => e.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
const parsePromptFrontmatter = (e) => {
const t = normalizeNewlines(e);
const n = extractFrontmatterBlock(t);
if (!n) return {
frontmatter: {},
body: t
};
return {
frontmatter: parse$1(n.block) ?? {},
body: n.body.trim()
};
};
const stripFrontmatter = (e) => parsePromptFrontmatter(e).body;
//#endregion
//#region src/agents/sessions/agent-session-transcript.ts
/** Persist completed model messages through their existing custody owner. */
async function persistAgentSessionMessage(e, t, n) {
applyAssistantDeliveryDirectives(t);
const r = { invalidateSerializedPrefixCache: n.invalidateSerializedPrefixCache };
const append = () => e.appendMessageAsync(t, r);
const i = t.role === "assistant" && (t.stopReason === "aborted" || t.stopReason === "error") && t.errorCode === "OPENCLAW_RESTART_ABORT" ? await withOwnedSessionRestartAbortWrite(e.getSessionTarget(), append) : await append();
if (t.role === "assistant" && !isOwnedTranscriptPayload(t)) freezeJsonSnapshot(t);
return i;
}
//#endregion
//#region src/agents/sessions/agent-session-utils.ts
function unwrapCoreResult(e) {
if (e.ok) return e.value;
throw e.error;
}
function hasPersistedAssistantContent(e) {
return (typeof e === "string" || Array.isArray(e)) && e.length > 0;
}
function extractTextContent(e) {
return typeof e === "string" ? e : collectTextContentBlocks(e).join("");
}
function replaceAgentMessageInPlace(e, t) {
if (e === t) return;
for (const t of Object.keys(e)) Reflect.deleteProperty(e, t);
Object.assign(e, t);
}
function estimateMessagesFromContent(e) {
return e.reduce((e, t) => e + estimateTokens(t), 0);
}
//#endregion
//#region src/agents/sessions/auth-guidance.ts
/**
* Shared user-facing auth guidance for session/model selection failures.
*
* Uses docs paths instead of provider-specific instructions so guidance stays correct across OAuth/API-key providers.
*/
const UNKNOWN_PROVIDER = "unknown";
/** Returns the standard provider login help block. */
function getProviderLoginHelp() {
return [
"Use /login to log into a provider via OAuth or API key. See:",
` ${join(getDocsPath(), "providers.md")}`,
` ${join(getDocsPath(), "models.md")}`
].join("\n");
}
/** Formats the message shown before a model is selected. */
function formatNoModelSelectedMessage() {
return `No model selected.\n\n${getProviderLoginHelp()}\n\nThen use /model to select a model.`;
}
/** Formats the missing API key guidance for a provider or unknown selected model. */
function formatNoApiKeyFoundMessage(e) {
return `No API key found for ${e === UNKNOWN_PROVIDER ? "the selected model" : e}.\n\n${getProviderLoginHelp()}`;
}
//#endregion
//#region src/agents/sessions/exec.ts
const DEFAULT_OUTPUT_LIMIT_CHARS = 16777216;
const FORCE_KILL_GRACE_MS = 5e3;
function decodeCapturedOutput(e, t) {
return Buffer.isBuffer(t) ? e.decode(t) : `${e.flush()}${t}`;
}
function clampMaxOutputChars(e) {
if (typeof e !== "number" || !Number.isFinite(e) || e <= 0) return DEFAULT_OUTPUT_LIMIT_CHARS;
return Math.max(1, Math.floor(e));
}
function appendCapturedOutput(e, t, n, r) {
const i = `${e.text}${t}`;
const a = Math.max(0, i.length - n);
const o = a === 0 ? i : r ? sliceUtf16Safe(i, a) : sliceUtf16Safe(i, 0, n);
return {
text: o,
truncatedChars: e.truncatedChars + i.length - o.length
};
}
async function execCommand(e, t, n, r) {
const i = new AbortController();
const a = createDeferredCore();
let o = true;
let s = true;
let c = false;
let l = false;
let u;
let d;
const killProcess = () => {
c = true;
if (d) {
if (!l) {
l = true;
if (!d.terminate()) i.abort();
}
} else i.abort();
if (o) a.resolve({
stdout: "",
stderr: "",
code: 1,
killed: true
});
};
try {
const l = spawnCommand([e, ...t], {
buffer: false,
cancelSignal: i.signal,
cwd: n,
detached: process.platform !== "win32",
forceKillAfterDelay: FORCE_KILL_GRACE_MS,
reject: false,
stdio: [
"ignore",
"pipe",
"pipe"
]
});
r?.signal?.addEventListener("abort", killProcess, { once: true });
if (r?.timeout && r.timeout > 0) u = scheduleAbsoluteDeadline(performance.now() + r.timeout, killProcess, () => performance.now());
const f = (async () => {
if (l.pid === void 0) await waitForCommandSpawn(l);
o = false;
const e = releaseChildProcessOutputAfterExit(l.nodeChildProcess);
let t = false;
l.nodeChildProcess.once("exit", () => {
t = true;
});
let n = false;
const a = createCommandTerminationController({
child: l.nodeChildProcess,
cancelController: i,
processTree: { mode: "graceful" },
killGraceMs: FORCE_KILL_GRACE_MS,
isChildExited: () => t,
isCommandSettled: () => n
});
d = a;
const f = {
stdout: {
text: "",
truncatedChars: 0
},
stderr: {
text: "",
truncatedChars: 0
}
};
const p = {
stdout: createWindowsOutputDecoder({ preserveUtf8Bom: true }),
stderr: createWindowsOutputDecoder({ preserveUtf8Bom: true })
};
const m = clampMaxOutputChars(r?.maxOutputChars);
const h = r?.maxOutputChars !== void 0;
let g;
const captureOutput = (e, t) => {
const n = f[e].truncatedChars;
f[e] = appendCapturedOutput(f[e], t, m, h);
if (!h && f[e].truncatedChars > n && !g) {
g = e;
return true;
}
return false;
};
const ignoreOutputStreamError = () => {};
for (const e of ["stdout", "stderr"]) {
l[e]?.on("error", ignoreOutputStreamError);
l[e]?.on("data", (t) => {
if (!s) return;
if (captureOutput(e, decodeCapturedOutput(p[e], t))) killProcess();
});
}
if (c) killProcess();
try {
const e = await l.then((e) => e.exitCode ?? (e.failed ? 1 : 0), () => 1);
n = true;
u?.();
r?.signal?.removeEventListener("abort", killProcess);
const t = await a.settle();
for (const e of ["stdout", "stderr"]) captureOutput(e, p[e].flush());
if (g) f.stderr = appendCapturedOutput(f.stderr, `${f.stderr.text ? "\n" : ""}exec ${g} exceeded output limit ${m} chars`, m, true);
const i = {
stdout: f.stdout.text,
stderr: f.stderr.text,
stdoutTruncatedChars: f.stdout.truncatedChars || void 0,
stderrTruncatedChars: f.stderr.truncatedChars || void 0,
outputLimitExceeded: g,
code: g ? 1 : e,
killed: c
};
if (t === "uncertain") throw new CommandProcessCleanupError({ cause: i });
return i;
} finally {
e();
}
})();
if (r?.signal?.aborted) killProcess();
return await Promise.race([f, a.promise]);
} finally {
s = false;
u?.();
r?.signal?.removeEventListener("abort", killProcess);
}
}
//#endregion
//#region src/agents/sessions/extensions/loader.ts
/**
* Create a runtime with throwing stubs for action methods.
* Runner.bindCore() replaces these with real implementations.
*/
function createExtensionRuntime() {
const notInitialized = () => {
throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.");
};
let e;
const assertActive = () => {
if (e) throw new Error(e);
};
const t = {
sendMessage: notInitialized,
sendUserMessage: notInitialized,
appendEntry: notInitialized,
appendEntryAsync: notInitialized,
setSessionName: notInitialized,
setSessionNameAsync: notInitialized,
getSessionName: notInitialized,
setLabel: notInitialized,
setLabelAsync: notInitialized,
getActiveTools: notInitialized,
getAllTools: notInitialized,
setActiveTools: notInitialized,
refreshTools: () => {},
getCommands: notInitialized,
setModel: () => Promise.reject(/* @__PURE__ */ new Error("Extension runtime not initialized")),
getThinkingLevel: notInitialized,
setThinkingLevel: notInitialized,
flagValues: /* @__PURE__ */ new Map(),
pendingProviderRegistrations: [],
assertActive,
invalidate: (t) => {
e ??= t ?? "This extension ctx is stale after session replacement or reload. Do not use a captured api or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";
},
registerProvider: (e, n, r = "<unknown>") => {
t.pendingProviderRegistrations.push({
name: e,
config: n,
extensionPath: r
});
},
unregisterProvider: (e) => {
t.pendingProviderRegistrations = t.pendingProviderRegistrations.filter((t) => t.name !== e);
}
};
return t;
}
/**
* Registration methods write to the extension object.
* Action methods delegate to the shared runtime.
*/
function createExtensionAPI(e, t, n, r) {
const activeRuntime = () => {
t.assertActive();
return t;
};
const persist = async (e) => {
const t = activeRuntime();
const n = e(t);
if (!n) throw new Error("Extension host must bind worker persistence with bindCoreAsync");
const r = await n;
t.assertActive();
return r;
};
return {
on(n, r) {
t.assertActive();
const i = e.handlers.get(n) ?? [];
i.push(r);
e.handlers.set(n, i);
},
registerTool(n) {
t.assertActive();
e.tools.set(n.name, {
definition: n,
sourceInfo: e.sourceInfo
});
t.refreshTools();
},
registerCommand(n, r) {
t.assertActive();
e.commands.set(n, {
name: n,
sourceInfo: e.sourceInfo,
...r
});
},
registerShortcut(n, r) {
t.assertActive();
e.shortcuts.set(n, {
shortcut: n,
extensionPath: e.path,
...r
});
},
registerFlag(n, r) {
t.assertActive();
e.flags.set(n, {
name: n,
extensionPath: e.path,
...r
});
if (r.default !== void 0 && !t.flagValues.has(n)) t.flagValues.set(n, r.default);
},
registerMessageRenderer(n, r) {
t.assertActive();
e.messageRenderers.set(n, r);
},
getFlag(n) {
t.assertActive();
if (!e.flags.has(n)) return;
return t.flagValues.get(n);
},
sendMessage: (e, t) => {
activeRuntime().sendMessage(e, t);
},
sendUserMessage: (e, t) => {
activeRuntime().sendUserMessage(e, t);
},
appendEntry: (e, t) => {
warnSessionPersistenceDeprecation("ExtensionAPI.appendEntry", "appendEntryAsync");
activeRuntime().appendEntry(e, t);
},
appendEntryAsync: (e, t) => persist((n) => n.appendEntryAsync?.(e, t)),
setSessionName: (e) => {
warnSessionPersistenceDeprecation("ExtensionAPI.setSessionName", "setSessionNameAsync");
activeRuntime().setSessionName(e);
},
setSessionNameAsync: (e) => persist((t) => t.setSessionNameAsync?.(e)),
getSessionName: () => activeRuntime().getSessionName(),
setLabel: (e, t) => {
warnSessionPersistenceDeprecation("ExtensionAPI.setLabel", "setLabelAsync");
activeRuntime().setLabel(e, t);
},
setLabelAsync: (e, t) => persist((n) => n.setLabelAsync?.(e, t)),
exec(e, r, i) {
t.assertActive();
return execCommand(e, r, i?.cwd ?? n, i);
},
getActiveTools: () => activeRuntime().getActiveTools(),
getAllTools: () => activeRuntime().getAllTools(),
setActiveTools: (e) => {
activeRuntime().setActiveTools(e);
},
getCommands: () => activeRuntime().getCommands(),
setModel: (e) => activeRuntime().setModel(e),
getThinkingLevel: () => activeRuntime().getThinkingLevel(),
setThinkingLevel: (e) => activeRuntime().setThinkingLevel(e),
registerProvider: (t, n) => {
activeRuntime().registerProvider(t, n, e.path);
},
unregisterProvider: (t) => {
activeRuntime().unregisterProvider(t, e.path);
},
events: r
};
}
async function loadExtensionFromFactory(e, t, n, r, i = "<inline>") {
const a = i.startsWith("<") && i.endsWith(">") ? i.slice(1, -1).split(":")[0] || "temporary" : "local";
const o = i.startsWith("<") ? void 0 : path$1.dirname(i);
const s = {
path: i,
resolvedPath: i,
sourceInfo: createSyntheticSourceInfo(i, {
source: a,
baseDir: o
}),
handlers: /* @__PURE__ */ new Map(),
tools: /* @__PURE__ */ new Map(),
messageRenderers: /* @__PURE__ */ new Map(),
commands: /* @__PURE__ */ new Map(),
flags: /* @__PURE__ */ new Map(),
shortcuts: /* @__PURE__ */ new Map()
};
await e(createExtensionAPI(s, r, t, n));
return s;
}
//#endregion
//#region src/agents/sessions/extensions/metadata-actions.ts
function bindPersistenceScope(e, t) {
return (n) => {
t.assertActive();
const r = e.getSessionTarget();
const assertCurrent = () => {
t.assertActive();
const n = e.getSessionTarget();
if (!sameSessionTranscriptTargetBinding(r, n)) throw new Error("Extension session manager changed before metadata persistence");
};
return withSessionManagerWriteAssertion(e, assertCurrent, () => r ? withSessionTranscriptWriteAssertion(r, assertCurrent, n) : n());
};
}
/** Retain the bound runtime and manager through queued metadata transaction/commit grants. */
function bindExtensionMetadataActions(e, t, n) {
const r = bindPersistenceScope(e, t);
t.setModel = (e) => r(() => n.setModel(e));
t.setThinkingLevel = (e) => r(() => n.setThinkingLevel(e));
}
/** Bind awaited writes to the same runtime and transcript target through worker commit. */
function bindExtensionPersistenceActions(e, t, n) {
const r = bindPersistenceScope(e, t);
t.appendEntryAsync = (e, t) => r(() => n.appendEntryAsync(e, t));
t.setSessionNameAsync = (e) => r(() => n.setSessionNameAsync(e));
t.setLabelAsync = (e, t) => r(() => n.setLabelAsync(e, t));
}
//#endregion
//#region src/agents/sessions/extensions/provider-actions.ts
function bindExtensionProviderActions(e, t, n, r) {
const registerProvider = (e, n) => {
if (r?.registerProvider) r.registerProvider(e, n);
else t.registerProvider(e, n);
};
for (const { name: t, config: r, extensionPath: i } of e.pendingProviderRegistrations) try {
registerProvider(t, r);
} catch (e) {
n({
extensionPath: i,
event: "register_provider",
error: coerceErrorMessage(e),
stack: e instanceof Error ? e.stack : void 0
});
}
e.pendingProviderRegistrations = [];
e.registerProvider = registerProvider;
e.unregisterProvider = (e) => {
if (r?.unregisterProvider) {
r.unregisterProvider(e);
return;
}
t.unregisterProvider(e);
};
}
//#endregion
//#region src/agents/sessions/extensions/runner-defaults.ts
const noOpUIContext = {
select: async () => void 0,
confirm: async () => false,
input: async () => void 0,
notify: () => {},
onTerminalInput: () => () => {},
setStatus: () => {},
setWorkingMessage: () => {},
setWorkingVisible: () => {},
setWorkingIndicator: () => {},
setHiddenThinkingLabel: () => {},
setWidget: () => {},
setFooter: () => {},
setHeader: () => {},
setTitle: () => {},
custom: async () => void 0,
pasteToEditor: () => {},
setEditorText: () => {},
getEditorText: () => "",
editor: async () => void 0,
addAutocompleteProvider: () => {},
setEditorComponent: () => {},
getEditorComponent: () => void 0,
get theme() {
return interactiveAgentTheme;
},
getAllThemes: () => [],
getTheme: () => void 0,
setTheme: () => ({
success: false,
error: "UI not available"
}),
getToolsExpanded: () => false,
setToolsExpanded: () => {}
};
const noOpCommandContextActions = {
waitForIdle: async () => {},
newSession: async () => ({ cancelled: false }),
fork: async () => ({ cancelled: false }),
navigateTree: async () => ({ cancelled: false }),
switchSession: async () => ({ cancelled: false }),
reload: async () => {}
};
//#endregion
//#region src/agents/sessions/extensions/runner.ts
const RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [
"app.interrupt",
"app.clear",
"app.exit",
"app.suspend",
"app.thinking.cycle",
"app.model.cycleForward",
"app.model.cycleBackward",
"app.model.select",
"app.tools.expand",
"app.thinking.toggle",
"app.editor.external",
"app.message.followUp",
"tui.input.submit",
"tui.select.confirm",
"tui.select.cancel",
"tui.input.copy",
"tui.editor.deleteToLineEnd"
];
const buildBuiltinKeybindings = (e) => {
const t = {};
for (const [n, r] of Object.entries(e)) {
if (r === void 0) continue;
const e = Array.isArray(r) ? r : [r];
const i = RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS.includes(n);
for (const r of e) {
const e = r.toLowerCase();
if (t[e]?.restrictOverride && !i) continue;
t[e] = {
keybinding: n,
restrictOverride: i
};
}
}
return t;
};
async function emitSessionShutdownEvent(e, t) {
if (e.hasHandlers("session_shutdown")) {
await e.emit(t);
return true;
}
return false;
}
var ExtensionRunner = class {
constructor(e, t, n, r, i) {
this.extensions = e;
this.runtime = t;
this.cwd = n;
this.sessionManager = r;
this.modelRegistry = i;
this.errorListeners = /* @__PURE__ */ new Set();
this.getModel = () => void 0;
this.isIdleFn = () => true;
this.getSignalFn = () => void 0;
this.waitForIdleFn = noOpCommandContextActions.waitForIdle;
this.abortFn = () => {};
this.hasPendingMessagesFn = () => false;
this.getContextUsageFn = () => void 0;
this.compactFn = () => {};
this.getSystemPromptFn = () => "";
this.newSessionHandler = noOpCommandContextActions.newSession;
this.forkHandler = noOpCommandContextActions.fork;
this.navigateTreeHandler = noOpCommandContextActions.navigateTree;
this.switchSessionHandler = noOpCommandContextActions.switchSession;
this.reloadHandler = noOpCommandContextActions.reload;
this.shutdownHandler = () => {};
this.shortcutDiagnostics = [];
this.commandDiagnostics = [];
this.uiContext = noOpUIContext;
}
/** Bind host actions with worker-backed persistence; legacy bindCore remains source-compatible. */
bindCoreAsync(e, t, n) {
this.bindCoreActions(e, t, n);
bindExtensionPersistenceActions(this.sessionManager, this.runtime, e);
}
/** @deprecated Use bindCoreAsync with ExtensionActionsV2. Supported through 2026-12-31; removal ships in the first January 2027 stable release. */
bindCore(e, t, n) {
warnSessionPersistenceDeprecation("ExtensionRunner.bindCore", "bindCoreAsync with ExtensionActionsV2");
this.bindCoreActions(e, t, n);
}
bindCoreActions(e, t, n) {
this.runtime.sendMessage = e.sendMessage;
this.runtime.sendUserMessage = e.sendUserMessage;
this.runtime.appendEntry = e.appendEntry;
this.runtime.setSessionName = e.setSessionName;
this.runtime.getSessionName = e.getSessionName;
this.runtime.setLabel = e.setLabel;
this.runtime.getActiveTools = e.getActiveTools;
this.runtime.getAllTools = e.getAllTools;
this.runtime.setActiveTools = e.setActiveTools;
this.runtime.refreshTools = e.refreshTools;
this.runtime.getCommands = e.getCommands;
bindExtensionMetadataActions(this.sessionManager, this.runtime, e);
this.runtime.getThinkingLevel = e.getThinkingLevel;
this.getModel = t.getModel;
this.isIdleFn = t.isIdle;
this.getSignalFn = t.getSignal;
this.abortFn = t.abort;
this.hasPendingMessagesFn = t.hasPendingMessages;
this.shutdownHandler = t.shutdown;
this.getContextUsageFn = t.getContextUsage;
this.compactFn = t.compact;
this.getSystemPromptFn = t.getSystemPrompt;
bindExtensionProviderActions(this.runtime, this.modelRegistry, (e) => this.emitError(e), n);
}
bindCommandContext(e) {
const t = e ?? noOpCommandContextActions;
this.waitForIdleFn = t.waitForIdle;
this.newSessionHandler = t.newSession;
this.forkHandler = t.fork;
this.navigateTreeHandler = t.navigateTree;
this.switchSessionHandler = t.switchSession;
this.reloadHandler = t.reload;
}
setUIContext(e) {
this.uiContext = e ?? noOpUIContext;
}
getUIContext() {
return this.uiContext;
}
hasUI() {
return this.uiContext !== noOpUIContext;
}
getExtensionPaths() {
return this.extensions.map((e) => e.path);
}
/** Get all registered tools from all extensions (first registration per name wins). */
getAllRegisteredTools() {
const e = /* @__PURE__ */ new Map();
for (const t of this.extensions) for (const n of t.tools.values()) if (!e.has(n.definition.name)) e.set(n.definition.name, n);
return Array.from(e.values());
}
getToolDefinition(e) {
for (const t of this.extensions) {
const n = t.tools.get(e);
if (n) return n.definition;
}
}
getFlags() {
const e = /* @__PURE__ */ new Map();
for (const t of this.extensions) for (const [n, r] of t.flags) if (!e.has(n)) e.set(n, r);
return e;
}
setFlagValue(e, t) {
this.runtime.flagValues.set(e, t);
}
getFlagValues() {
return new Map(this.runtime.flagValues);
}
getShortcuts(e) {
this.shortcutDiagnostics = [];
const t = buildBuiltinKeybindings(e);
const n = /* @__PURE__ */ new Map();
const addDiagnostic = (e, t) => {
this.shortcutDiagnostics.push({
type: "warning",
message: e,
path: t
});
if (!this.hasUI()) console.warn(e);
};
for (const e of this.extensions) for (const [r, i] of e.shortcuts) {
const e = r.toLowerCase();
const a = t[e];
if (a?.restrictOverride === true) {
addDiagnostic(`Extension shortcut '${r}' from ${i.extensionPath} conflicts with built-in shortcut. Skipping.`, i.extensionPath);
continue;
}
if (a?.restrictOverride === false) addDiagnostic(`Extension shortcut conflict: '${r}' is built-in shortcut for ${a.keybinding} and ${i.extensionPath}. Using ${i.extensionPath}.`, i.extensionPath);
const o = n.get(e);
if (o) addDiagnostic(`Extension shortcut conflict: '${r}' registered by both ${o.extensionPath} and ${i.extensionPath}. Using ${i.extensionPath}.`, i.extensionPath);
n.set(e, i);
}
return n;
}
getShortcutDiagnostics() {
return this.shortcutDiagnostics;
}
invalidate(e = "This extension ctx is stale after session replacement or reload. Do not use a captured api or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().") {
if (!this.staleMessage) {
this.staleMessage = e;
this.runtime.invalidate(e);
}
}
requireActive() {
if (this.staleMessage) throw new Error(this.staleMessage);
this.runtime.assertActive();
return this;
}
onError(e) {
return registerListener(this.errorListeners, e);
}
emitError(e) {
for (const t of this.errorListeners) t(e);
}
hasHandlers(e) {
for (const t of this.extensions) if ((t.handlers.get(e)?.length ?? 0) > 0) return true;
return false;
}
getMessageRenderer(e) {
for (const t of this.extensions) {
const n = t.messageRenderers.get(e);
if (n) return n;
}
}
resolveRegisteredCommands() {
const e = [];
const t = /* @__PURE__ */ new Map();
for (const n of this.extensions) for (const r of n.commands.values()) {
e.push(r);
t.set(r.name, (t.get(r.name) ?? 0) + 1);
}
const n = /* @__PURE__ */ new Map();
const r = /* @__PURE__ */ new Set();
return e.map((e) => {
const i = (n.get(e.name) ?? 0) + 1;
n.set(e.name, i);
let a = (t.get(e.name) ?? 0) > 1 ? `${e.name}:${i}` : e.name;
if (r.has(a)) {
let t = i;
do {
t++;
a = `${e.name}:${t}`;
} while (r.has(a));
}
r.add(a);
return Object.assign({}, e, { invocationName: a });
});
}
getRegisteredCommands() {
this.commandDiagnostics = [];
return this.resolveRegisteredCommands();
}
getCommandDiagnostics() {
return this.commandDiagnostics;
}
getCommand(e) {
return this.resolveRegisteredCommands().find((t) => t.invocationName === e);
}
/**
* Request a graceful shutdown. Called by extension tools and event handlers.
* The actual shutdown behavior is provided by the mode via bindExtensions().
*/
shutdown() {
this.shutdownHandler();
}
/**
* Create an ExtensionContext for use in event handlers and tool execution.
* Context values are resolved at call time, so changes via bindCore/bindUI are reflected.
*/
createContext() {
const requireActiveRunner = () => this.requireActive();
const e = this.getModel;
return {
get ui() {
return requireActiveRunner().uiContext;
},
get hasUI() {
return requireActiveRunner().hasUI();
},
get cwd() {
return requireActiveRunner().cwd;
},
get sessionManager() {
return requireActiveRunner().sessionManager;
},
get modelRegistry() {
return requireActiveRunner().modelRegistry;
},
get model() {
requireActiveRunner();
return e();
},
isIdle: () => requireActiveRunner().isIdleFn(),
get signal() {
return requireActiveRunner().getSignalFn();
},
abort: () => requireActiveRunner().abortFn(),
hasPendingMessages: () => requireActiveRunner().hasPendingMessagesFn(),
shutdown: () => requireActiveRunner().shutdownHandler(),
getContextUsage: () => requireActiveRunner().getContextUsageFn(),
compact: (e) => requireActiveRunner().compactFn(e),
getSystemPrompt: () => requireActiveRunner().getSystemPromptFn()
};
}
createCommandContext() {
return Object.assign(this.createContext(), {
waitForIdle: () => this.requireActive().waitForIdleFn(),
newSession: (e) => this.requireActive().newSessionHandler(e),
fork: (e, t) => this.requireActive().forkHandler(e, t),
navigateTree: (e, t) => this.requireActive().navigateTreeHandler(e, t),
switchSession: (e, t) => this.requireActive().switchSessionHandler(e, t),
reload: () => this.requireActive().reloadHandler()
});
}
async dispatchHandlers(e, t, n) {
let r = n;
for (const n of this.extensions) for (const i of n.handlers.get(e) ?? []) {
r ??= this.createContext();
try {
const e = await t(i, r, n.path);
if (e !== void 0) return e;
} catch (t) {
if (e === "tool_call") throw t;
rethrowIncognitoSessionError(t);
if (t instanceof SessionMetadataCommittedError) throw t;
this.emitError({
extensionPath: n.path,
event: e,
error: coerceErrorMessage(t),
stack: t instanceof Error ? t.stack : void 0
});
}
}
}
async emit(e) {
let t;
return await this.dispatchHandlers(e.type, async (n, r) => {
const i = await n(e, r);
if ((e.type === "session_before_switch" || e.type === "session_before_fork" || e.type === "session_before_compact" || e.type === "session_before_tree") && i) {
t = i;
if (t.cancel) return t;
}
}) ?? t;
}
async emitMessageEnd(e) {
let t = e.message;
let n = false;
await this.dispatchHandlers("message_end", async (r, i, a) => {
const o = await r({
...e,
message: t
}, i);
if (o?.message) {
if (o.message.role !== t.role) this.emitError({
extensionPath: a,
event: "message_end",
error: "message_end handlers must return a message with the same role"
});
else {
t = o.message;
n = true;
}
}
});
return n ? t : void 0;
}
async emitToolResult(e) {
const t = { ...e };
let n = false;
await this.dispatchHandlers("tool_result", async (e, r) => {
const i = await e(t, r);
if (i?.content !== void 0) {
t.content = i.content;
n = true;
}
if (i?.details !== void 0) {
t.details = i.details;
n = true;
}
if (i?.isError !== void 0 || isToolResultError(i)) {
t.isError = i?.isError ?? true;
n = true;
}
if (i?.terminate !== void 0) {
t.terminate = i.terminate;
n = true;
}
});
if (!n) return;
return {
content: t.content,
details: t.details,
isError: t.isError,
terminate: t.terminate
};
}
async emitToolCall(e) {
let t;
await this.dispatchHandlers("tool_call", async (n, r) => {
const i = await n(e, r);
if (i) {
t = i;
if (t.block) return t;
}
});
return t;
}
async emitUserBash(e) {
return await this.dispatchHandlers("user_bash", async (t, n) => {
const r = await t(e, n);
return r ? r : void 0;
});
}
async emitContext(e) {
if (!this.hasHandlers("context")) return e;
let t = cloneTranscriptView(e, { shareImmutablePayloads: false });
await this.dispatchHandlers("context", async (e, n) => {
t = (await e({
type: "context",
messages: t
}, n))?.messages || t;
});
return t;
}
async emitBeforeProviderRequest(e) {
let t = e;
await this.dispatchHandlers("before_provider_request", async (e, n) => {
const r = await e({
type: "before_provider_request",
payload: t
}, n);
if (r !== void 0) t = r;
});
return t;
}
async emitBeforeAgentStart(e, t, n, r) {
let i = n;
const a = this.createContext();
a.getSystemPrompt = () => {
this.requireActive();
return i;
};
const o = [];
let s = false;
await this.dispatchHandlers("before_agent_start", async (n, a) => {
const c = await n({
type: "before_agent_start",
prompt: e,
images: t,
systemPrompt: i,
systemPromptOptions: r
}, a);
if (c?.message) o.push(c.message);
if (c?.systemPrompt !== void 0) {
i = c.systemPrompt;
s = true;
}
}, a);
if (o.length > 0 || s) return {
messages: o.length > 0 ? o : void 0,
systemPrompt: s ? i : void 0
};
}
async emitResourcesDiscover(e, t) {
const n = {
skillPaths: [],
promptPaths: [],
themePaths: []
};
await this.dispatchHandlers("resources_discover", async (r, i, a) => {
const o = await r({
type: "resources_discover",
cwd: e,
reason: t
}, i);
for (const e of [
"skillPaths",
"promptPaths",
"themePaths"
]) {
const t = o?.[e];
if (t?.length) n[e].push(...t.map((e) => ({
path: e,
extensionPath: a
})));
}
});
return n;
}
/** Emit input event. Transforms chain, "handled" short-circuits. */
async emitInput(e, t, n) {
let r = e;
let i = t;
const a = await this.dispatchHandlers("input", async (e, t) => {
const a = await e({
type: "input",
text: r,
images: i,
source: n
}, t);
if (a?.action === "handled") return a;
if (a?.action === "transform") {
r = a.text;
i = a.images ?? i;
}
});
if (a) return a;
return r !== e || i !== t ? {
action: "transform",
text: r,
images: i
} : { action: "continue" };
}
};
//#endregion
//#region src/agents/sessions/queued-user-message-retirement.ts
const queuedUserMessageRetirements = /* @__PURE__ */ new WeakMap();
/** Binds one runtime message to the exact display entry created for it. */
function registerQueuedUserMessageRetirement(e, t) {
queuedUserMessageRetirements.set(e, t);
}
/** Consumes the display retirement owned by this exact runtime message. */
function retireQueuedUserMessage(e) {
const t = queuedUserMessageRetirements.get(e);
if (!t) return false;
queuedUserMessageRetirements.delete(e);
return t();
}
//#endregion
//#region src/agents/sessions/session-tool-result-preparation.ts
const preparers = createSessionManagerRuntimeRegistry();
const unchangedToolResult = () => false;
/** Bind the guard's size cap without extending the public SessionManager contract. */
function setSessionToolResultPreparer(e, t) {
preparers.set(e, t);
}
function createSessionToolResultPreparer(e, t) {
if (t.type !== "message_end" || t.message.role !== "toolResult") return unchangedToolResult;
return () => {
if (t.message.role !== "toolResult") return false;
const n = t.message;
const r = preparers.get(e)?.cap(n) ?? n;
if (r === n) return false;
if (Object.isFrozen(n)) t.message = copyInternalToolResultState(n, freezeJsonSnapshot(r));
else n.content = r.content;
return true;
};
}
//#endregion
//#region src/agents/sessions/steering-message-identity.ts
const STEERING_MESSAGE_IDENTITY = Symbol.for("openclaw.steeringMessageIdentity");
const steeringMessagePersistenceFailureListeners = /* @__PURE__ */ new Map();
function setSteeringMessageIdentity(e, t) {
if (t) Object.defineProperty(e, STEERING_MESSAGE_IDENTITY, {
configurable: true,
value: t
});
}
function getSteeringMessageIdentity(e) {
return e && typeof e === "object" ? e[STEERING_MESSAGE_IDENTITY] : void 0;
}
/** Keeps persistence failures private to the exact in-flight steering identity. */
function subscribeSteeringMessagePersistenceFailure(e, t) {
const n = steeringMessagePersistenceFailureListeners.get(e) ?? /* @__PURE__ */ new Set();
n.add(t);
steeringMessagePersistenceFailureListeners.set(e, n);
return () => {
n.delete(t);
if (n.size === 0 && steeringMessagePersistenceFailureListeners.get(e) === n) steeringMessagePersistenceFailureListeners.delete(e);
};
}
/** Rejects a queued receipt before a failed append can strand or acknowledge its source. */
function reportSteeringMessagePersistenceFailure(e, t) {
const n = getSteeringMessageIdentity(e);
if (n) steeringMessagePersistenceFailureListeners.get(n)?.forEach((e) => e(t));
}
//#endregion
//#region src/agents/sessions/agent-session-base.ts
const log = createSubsystemLogger("agents/session");
var AgentSessionBase = class {
constructor(e) {
this.eventListeners = [];
this.steeringMessages = [];
this.followUpMessages = [];
this.pendingNextTurnMessages = [];
this.compactionAbortController = void 0;
this.autoCompactionAbortController = void 0;
this.overflowRecoveryAttempts = 0;
this.extensionModifiedToolResultIds = /* @__PURE__ */ new Set();
this.retryAbortController = void 0;
this.retryCount = 0;
this.turnIndex = 0;
this.toolRegistry = /* @__PURE__ */ new Map();
this.toolDefinitions = /* @__PURE__ */ new Map();
this.lastAssistantMessage = void 0;
this.lastRunEndedForTurnHandoff = false;
this.handleAgentEvent = (e, t) => {
const n = createSessionToolResultPreparer(this.sessionManager, e);
if (e.type === "agent_end") {
const e = t?.reason;
this.lastRunEndedForTurnHandoff = t?.aborted === true && typeof e === "object" && e !== null && e.turnHandoff === true;
}
if (e.type === "message_end" || this.currentExtensionRunner.hasHandlers(e.type)) return this.runWithSessionWriteSettlement(() => this.handleAgentEventUnlocked(e, n)).then(() => {
n();
});
return this.handleAgentEventUnlocked(e, n, e.type === "message_update" ? false : void 0);
};
this.agent = e.agent;
this.baseSystemPrompt = e.systemPrompt;
this.sessionManager = e.sessionManager;
this.settingsManager = e.settingsManager;
this.sessionResourceLoader = e.resourceLoader;
this.customTools = e.customTools ?? [];
this.cwd = e.cwd;
this.sessionModelRegistry = e.modelRegistry;
this.extensionRunnerRef = e.extensionRunnerRef;
this.allowedToolNames = new Set(e.allowedToolNames);
this.withExternalSessionWriteSettlement = e.withSessionWriteSettlement;
this.contextOverflowRecoveryOwner = e.contextOverflowRecoveryOwner ?? "session";
this.resolveCompactionThinkingLevel = e.resolveCompactionThinkingLevel;
this.cleanupProviderSessionResourcesOnDispose = e.cleanupProviderSessionResourcesOnDispose ?? true;
}
get modelRegistry() {
return this.sessionModelRegistry;
}
async getRequiredRequestAuth(e) {
const t = await this.sessionModelRegistry.getApiKeyAndHeaders(e);
if (!t.ok) {
if (t.error.startsWith("No API key found")) throw new Error(formatNoApiKeyFoundMessage(e.provider));
throw new Error(t.error);
}
if (t.apiKey) return {
apiKey: t.apiKey,
headers: t.headers
};
if (this.sessionModelRegistry.isUsingOAuth(e)) throw new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`);
throw new Error(formatNoApiKeyFoundMessage(e.provider));
}
async getCompactionRequestAuth(e) {
if (getStreamLlmRuntime(this.agent.streamFn) === getModelRegistryRuntime(this.sessionModelRegistry).llmRuntime) return this.getRequiredRequestAuth(e);
const t = await this.sessionModelRegistry.getApiKeyAndHeaders(e);
return t.ok ? {
apiKey: t.apiKey,
headers: t.headers
} : {};
}
async runWithSessionWriteSettlement(e) {
return this.withExternalSessionWriteSettlement ? await this.withExternalSessionWriteSettlement(e) : await e();
}
/**
* Hooks resolve the current extension runner at execution time so reloads
* need no reinstall. Wrappers only adapt registered tools to extension context.
*/
installAgentToolHooks() {
this.agent.beforeToolCall = async ({ toolCall: e, args: t }) => {
const n = this.currentExtensionRunner;
return await this.runWithSessionWriteSettlement(async () => {
if (!n.hasHandlers("tool_call")) return;
try {
return await n.emitToolCall({
type: "tool_call",
toolName: e.name,
toolCallId: e.id,
input: t
});
} catch (e) {
if (e instanceof Error) throw e;
throw new Error(`Extension failed, blocking execution: ${String(e)}`, { cause: e });
}
});
};
this.agent.afterToolCall = async ({ toolCall: e, args: t, result: n, isError: r }) => {
const i = r || isToolResultError(n);
const a = this.currentExtensionRunner;
if (!a.hasHandlers("tool_result")) return { isError: i };
const o = await this.runWithSessionWriteSettlement(async () => await a.emitToolResult({
type: "tool_result",
toolName: e.name,
toolCallId: e.id,
input: t,
content: n.content,
details: n.details,
isError: i,
...n.terminate !== void 0 ? { terminate: n.terminate } : {}
}));
if (o) this.extensionModifiedToolResultIds.add(e.id);
return {
...o,
isError: o?.isError ?? i
};
};
this.agent.afterToolOutcome = async ({ executionStarted: e, result: t, isError: n }) => e ? void 0 : { isError: n || isToolResultError(t) };
}
/** Copy-on-write listener registration keeps dispatch stable without per-event snapshots. */
emit(e) {
for (const t of this.eventListeners) t(e);
}
/** Terminal listeners form a barrier before retry, compaction, or queue draining. */
async emitTerminal(e) {
const t = this.eventListeners;
for (const n of t) try {
await n(e);
} catch (e) {
log.warn(`agent_end listener failed: ${String(e)}`);
}
}
emitQueueUpdate() {
this.emit({ type: "queue_update" });
}
trackQueuedUserMessage(e, t, n) {
const r = t === "steering" ? this.steeringMessages : this.followUpMessages;
const i = { text: n };
r.push(i);
registerQueuedUserMessageRetirement(e, () => {
if (r !== this.steeringMessages && r !== this.followUpMessages) return false;
const e = r.indexOf(i);
if (e === -1) return false;
r.splice(e, 1);
this.emitQueueUpdate();
return true;
});
}
async handleAgentEventUnlocked(e, t, n) {
if (e.type === "agent_start") {
this.lastAssistantEntryId = void 0;
this.turnIndex = 0;
}
if (e.type === "message_start" && e.message.role === "user") {
this.overflowRecoveryAttempts = 0;
retireQueuedUserMessage(e.message);
}
let r = false;
if (n ?? this.currentExtensionRunner.hasHandlers(e.type)) r = await this.emitExtensionEvent(e);
if (e.type === "turn_end") this.turnIndex++;
r = t() || r;
const i = e.type === "message_end" && e.message.role === "user";
if (e.type === "agent_end") await this.emitTerminal({
...e,
willRetry: this.willRetryAfterAgentEnd(e),
...this.lastAssistantEntryId ? { assistantEntryId: this.lastAssistantEntryId } : {}
});
else if (!i) this.emit(e);
r = t() || r;
if (e.type === "message_end") {
if (e.message.role === "custom") {
const t = e.message;
const n = getModelPromptProjectionAppend(t);
if (n) await this.sessionManager[sessionManagerAppendPromptContext](t, n);
else await this.sessionManager.appendCustomMessageEntryAsync(t.customType, t.content, t.display, t.details, t.timestamp);
} else if (e.message.role === "user" || e.message.role === "assistant" || e.message.role === "toolResult") {
const t = e.message.role === "toolResult" && this.extensionModifiedToolResultIds.delete(e.message.toolCallId);
try {
const n = e.message.role === "user" && shouldRetainSteeringRuntimeContext(this) ? getSteeringRuntimeContext(e.message) : void 0;
if (n) await this.sessionManager.appendCustomMessageEntryAsync(n.customType, n.content, n.display, n.details, n.timestamp);
const i = await persistAgentSessionMessage(this.sessionManager, e.message, { invalidateSerializedPrefixCache: r || t });
if (e.message.role === "assistant") this.lastAssistantEntryId = i;
} catch (t) {
if (e.message.role === "user") reportSteeringMessagePersistenceFailure(e.message, t);
throw t;
}
if (e.message.role === "user") this.emit(e);
}
if (e.message.role === "assistant") this.lastAssistantMessage = e.message;
}
if (e.type === "turn_end" && e.message.role === "assistant") {
const t = e.message;
if (t.stopReason !== "error" && t.stopReason !== "length") this.overflowRecoveryAttempts = 0;
if (t.stopReason !== "error" && this.retryCount > 0) {
this.emit({ type: "auto_retry_end" });
this.retryCount = 0;
}
}
}
willRetryAfterAgentEnd(e) {
const t = this.settingsManager.getRetrySettings();
if (!t.enabled || this.retryCount >= t.maxRetries) return false;
const n = e.messages.findLast((e) => e.role === "assistant");
return n !== void 0 && this.isRetryableError(n);
}
/** Find the last assistant message in agent state (including aborted ones) */
findLastAssistantMessage() {
return this.agent.state.messages.findLast((e) => e.role === "assistant");
}
async emitExtensionEvent(e) {
if (e.type === "turn_start") await this.currentExtensionRunner.emit({
type: "turn_start",
turnIndex: this.turnIndex,
timestamp: Date.now()
});
else if (e.type === "turn_end") await this.currentExtensionRunner.emit({
type: "turn_end",
turnIndex: this.turnIndex,
message: e.message,
toolResults: e.toolResults
});
else if (e.type === "message_end") {
const t = await this.currentExtensionRunner.emitMessageEnd({
type: "message_end",
message: e.message
});
if (t) {
replaceAgentMessageInPlace(e.message, t);
return true;
}
} else if (e.type === "tool_execution_start") await this.currentExtensionRunner.emit({
type: "tool_execution_start",
toolCallId: e.toolCallId,
toolName: e.toolName,
args: e.args
});
else if (e.type === "tool_execution_update") await this.currentExtensionRunner.emit({
type: "tool_execution_update",
toolCallId: e.toolCallId,
toolName: e.toolName,
args: e.args,
partialResult: e.partialResult
});
else if (e.type === "tool_execution_end") await this.currentExtensionRunner.emit({
type: "tool_execution_end",
toolCallId: e.toolCallId,
toolName: e.toolName,
result: e.result,
isError: e.isError
});
else await this.currentExtensionRunner.emit({ ...e });
return false;
}
/**
* Subscribe to agent events.
* Session persistence is handled internally (saves messages on message_end).
* Multiple listeners can be added. Returns unsubscribe function for this listener.
*/
subscribe(e) {
this.eventListeners = [...this.eventListeners, e];
return () => {
const t = this.eventListeners.indexOf(e);
if (t !== -1) this.eventListeners = this.eventListeners.toSpliced(t, 1);
};
}
/**
* Temporarily disconnect from agent events.
* User listeners are preserved and will receive events again after resubscribe().
* Used internally during operations that need to pause event processing.
*/
disconnectFromAgent() {
if (this.unsubscribeAgent) {
this.unsubscribeAgent();
this.unsubscribeAgent = void 0;
}
}
/**
* Reconnect to agent events after disconnectFromAgent().
* Preserves all existing listeners.
*/
reconnectToAgent() {
if (this.unsubscribeAgent) return;
this.unsubscribeAgent = this.agent.subscribe(this.handleAgentEvent);
}
/**
* Remove all listeners and disconnect from agent.
* Call this when completely done with the session.
*/
dispose() {
notifyListeners([
() => this.abortRetry(),
() => this.abortCompaction(),
() => this.agent.abort()
], void 0);
this.currentExtensionRunner.invalidate();
this.disconnectFromAgent();
this.eventListeners = [];
if (this.cleanupProviderSessionResourcesOnDispose) cleanupSessionResources(this.sessionId);
}
get state() {
return this.agent.state;
}
get model() {
return this.agent.state.model;
}
get thinkingLevel() {
return this.agent.state.thinkingLevel;
}
get isStreaming() {
return this.agent.state.isStreaming;
}
/** Current effective system prompt (includes any per-turn extension modifications) */
get systemPrompt() {
return this.agent.state.systemPrompt;
}
getActiveToolNames() {
return this.agent.state.tools.map((e) => e.name);
}
/** All configured tools with their schema and source metadata. */
getAllTools() {
return Array.from(this.toolDefinitions.values()).map(({ definition: e, sourceInfo: t }) => ({
name: e.name,
description: e.description,
parameters: e.parameters,
sourceInfo: t
}));
}
getToolDefinition(e) {
return this.toolDefinitions.get(e)?.definition;
}
/**
* Set active tools by name.
* Only tools in the registry can be enabled. Unknown tool names are ignored.
* An execution cap preserves these definitions and refuses denied calls.
* Refreshes extension prompt metadata while preserving the runtime-owned prompt.
* Changes take effect on the next agent turn.
*/
setActiveToolsByName(e, t) {
const n = [];
const r = [];
const i = t ? new Set(t) : void 0;
for (const t of e) {
const e = this.toolRegistry.get(t);
if (e) {
n.push(!i || i.has(t) ? e : gateAgentToolExecution(e, `${t} is not available in this turn. Do not retry ${t}.`));
r.push(t);
}
}
this.agent.state.tools = n;
this.refreshSystemPromptMetadata(r);
this.agent.state.systemPrompt = this.systemPromptOverride ?? this.baseSystemPrompt;
}
/** Set an exact base prompt owned by the current runtime. */
setBaseSystemPrompt(e) {
this.baseSystemPrompt = e;
this.refreshSystemPromptMetadata(this.getActiveToolNames());
this.agent.state.systemPrompt = e;
}
/** Whether manual or automatic compaction is currently running */
get isCompacting() {
return this.autoCompactionAbortController !== void 0 || this.compactionAbortController !== void 0;
}
/** All messages including custom types like BashExecutionMessage */
get messages() {
return this.agent.state.messages;
}
get steeringMode() {
return this.agent.steeringMode;
}
get followUpMode() {
return this.agent.followUpMode;
}
/** Current persisted transcript target, or undefined for in-memory sessions. */
get sessionTarget() {
return this.sessionManager.getSessionTarget();
}
/** Current persisted session key, or undefined for in-memory sessions. */
get sessionKey() {
return this.sessionTarget?.sessionKey;
}
/** @deprecated Compatibility token; returns the session key, not a file path. */
get sessionFile() {
return this.sessionKey;
}
get sessionId() {
return this.sessionManager.getSessionId();
}
get sessionName() {
return this.sessionManager.getSessionName();
}
/** File-based prompt templates */
get promptTemplates() {
return this.sessionResourceLoader.getPrompts().prompts;
}
refreshSystemPromptMetadata(e) {
const t = e.filter((e) => this.toolRegistry.has(e));
const n = {};
const r = [];
for (const e of t) {
const t = this.toolDefinitions.get(e)?.definition;
const i = t?.promptSnippet?.replace(/\s+/g, " ").trim();
if (i) n[e] = i;
r.push(...new Set(t?.promptGuidelines?.map((e) => e.trim()).filter(Boolean)));
}
this.baseSystemPromptOptions = {
cwd: this.cwd,
customPrompt: this.baseSystemPrompt,
selectedTools: t,
toolSnippets: n,
promptGuidelines: r
};
}
};
//#endregion
//#region src/shared/tilde-path.ts
/**
* Expands a leading `~` against the OS home dir, keeping relative inputs
* relative so callers can resolve them against their own base dir. Unlike
* `resolveHomeRelativePath`, `~name` is treated as `<home>/name` (shipped
* loader behavior for prompt/skill path lists).
*/
function expandTildePath(e) {
const t = e.trim();
if (t === "~") return homedir();
if (t.startsWith("~/")) return join(homedir(), t.slice(2));
if (t.startsWith("~")) return join(homedir(), t.slice(1));
return t;
}
//#endregion
//#region src/agents/sessions/prompt-templates.ts
function loadTemplateFromFile(e, t) {
try {
const n = readFileSync(e, "utf-8");
const { frontmatter: r, body: i } = parsePromptFrontmatter(n);
const a = basename(e).replace(/\.md$/, "");
let o = r.description || "";
if (!o) {
const e = i.split("\n").find((e) => e.trim());
if (e) o = truncateUtf16Safe(e, 60) + (e.length > 60 ? "..." : "");
}
return {
name: a,
description: o,
...r["argument-hint"] && { argumentHint: r["argument-hint"] },
content: i,
sourceInfo: t,
filePath: e
};
} catch {
return null;
}
}
function resolvePromptPath(e, t) {
const n = expandTildePath(e);
return isAbsolute(n) ? n : resolve(t, n);
}
/** Load explicit prompt paths with metadata for their source scope. */
function loadPromptTemplates({ cwd: e, agentDir: t, promptPaths: n }) {
const r = [];
const i = t ? join(t, "prompts") : t;
const a = resolve(e, CONFIG_DIR_NAME, "prompts");
const getSourceInfo = (e) => {
for (const [t, n] of [[i, "user"], [a, "project"]]) if (isPathInside(t, e)) return createSyntheticSourceInfo(e, {
source: "local",
scope: n,
baseDir: t
});
return createSyntheticSourceInfo(e, {
source: "local",
baseDir: dirname(e)
});
};
for (const t of n) {
const n = resolvePromptPath(t, e);
try {
const e = statSync(n);
let t = [];
if (e.isDirectory()) {
const { entries: e } = walkDirectorySync(n, {
maxDepth: 1,
symlinks: "follow",
include: (e) => e.kind === "file" && e.name.endsWith(".md")
});
t = e.map((e) => join(n, e.name));
} else if (e.isFile() && n.endsWith(".md")) t = [n];
for (const e of t) {
const t = loadTemplateFromFile(e, getSourceInfo(e));
if (t) r.push(t);
}
} catch {}
}
return r;
}
/**
* Expand a prompt template if it matches a template name.
* Returns the expanded content or the original text if not a template.
*/
function expandPromptTemplate(e, t) {
const n = e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);
if (!n) return e;
const r = n[1];
const i = n[2] ?? "";
const a = t.find((e) => e.name === r);
if (a) {
const e = parseCommandArgs(i);
return substituteArgs(a.content, e);
}
return e;
}
//#endregion
//#region src/agents/sessions/agent-session-prompting.ts
function createCustomMessage(e) {
return {
role: "custom",
customType: e.customType,
content: e.content,
display: e.display,
details: e.details,
timestamp: Date.now()
};
}
/** @internal Host preparation runs after SDK prompt hooks and owns its run cancellation. */
const agentSessionSetPromptPreparation = Symbol.for("openclaw.agent-session.set-prompt-preparation");
/** @internal Queue prompt-owned context with cleanup for preflight exits. */
const agentSessionQueuePromptContext = Symbol.for("openclaw.agent-session.queue-prompt-context");
var AgentSessionPrompting = class extends AgentSessionBase {
constructor(...e) {
super(...e);
this.logicalPromptActive = false;
}
[agentSessionQueuePromptContext](e, t) {
if (t?.delivery === "current-request") return this.persistCustomMessage(e);
if (this.logicalPromptActive && isOpenClawSystemUpdateMessage(e)) {
this.agent.steer(e);
return () => {
this.agent.cancelSteeringMessage((t) => t === e);
};
}
if (isOpenClawSystemUpdateMessage(e)) this.pendingNextTurnMessages.push(e);
else this.pendingNextTurnMessages.unshift(e);
return () => {
this.pendingNextTurnMessages = this.pendingNextTurnMessages.filter((t) => t !== e);
};
}
[agentSessionSetPromptPreparation](e) {
this.promptPreparation = e;
}
dispose() {
this.promptPreparation = void 0;
super.dispose();
}
async runAgentPrompt(e) {
if (this.logicalPromptActive) throw new Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");
this.logicalPromptActive = true;
let t = false;
try {
await this.runPreparedAgentLoop(() => this.agent.prompt(e));
while (true) {
const e = await this.handlePostAgentRun();
if (e !== "continue") {
t = e === "handoff";
break;
}
await this.runPreparedAgentLoop(() => this.agent.continue());
}
} finally {
this.systemPromptOverride = void 0;
this.logicalPromptActive = false;
t ||= this.lastRunEndedForTurnHandoff;
this.lastRunEndedForTurnHandoff = false;
if (t) this.emit({ type: "agent_handoff" });
else {
this.emit({ type: "agent_settled" });
await this.currentExtensionRunner.emit({ type: "agent_settled" });
}
}
}
async runPreparedAgentLoop(e) {
const t = this.promptPreparation;
if (!t) return e();
const n = await t();
const assertCurrent = () => {
if (t !== this.promptPreparation) throw new Error("Session prompt preparation is stale after replacement or disposal.");
};
assertCurrent();
let r;
const start = (t) => {
assertCurrent();
t?.();
assertCurrent();
r = e().then((e) => ({
status: "fulfilled",
value: e
}), (e) => ({
status: "rejected",
reason: e
}));
};
try {
if (n) await n(start);
else start();
} catch (e) {
await r;
throw e;
}
if (!r) throw new Error("Session prompt admission did not start the agent loop.");
const i = await r;
if (i.status === "rejected") throw i.reason;
}
async handlePostAgentRun() {
const e = this.lastAssistantMessage;
this.lastAssistantMessage = void 0;
const t = this.lastRunEndedForTurnHandoff;
this.lastRunEndedForTurnHandoff = false;
if (t) return "handoff";
if (!e || e.stopReason === "aborted") return "settled";
if (this.isRetryableError(e) && await this.prepareRetry(e)) return "continue";
if (e.stopReason === "error" && this.retryCount > 0) {
this.emit({ type: "auto_retry_end" });
this.retryCount = 0;
}
if (await this.checkCompaction(e)) return "continue";
return e.stopReason !== "error" && this.agent.hasQueuedMessages() ? "continue" : "settled";
}
createUserMessage(e, t, n) {
const r = readRuntimePromptImageFactIndexes(t);
const i = {
role: "user",
content: [{
type: "text",
text: e
}, ...t ?? []],
timestamp: Date.now(),
...r ? { __openclaw: { mediaImageBlockFactIndexes: r } } : {}
};
return Object.assign(i, mergePreparedUserTurnMessageForRuntime({
runtimeMessage: i,
preparedMessage: n
}), { content: i.content });
}
/**
* Send a prompt to the agent.
* - Handles extension commands immediately, even during streaming
* - Expands file-based prompt templates by default
* - During streaming, queues via steer() or followUp() based on streamingBehavior option
* - Validates model and API key before sending (when not streaming)
* @throws Error if streaming and no streamingBehavior specified
* @throws Error if no model selected or no API key available (when not streaming)
*/
async prompt(e, t) {
const n = takePromptCompactionRequestBudget(t);
const r = t?.expandPromptTemplates ?? true;
const i = t?.preflightResult;
let a = false;
let o = false;
let s;
try {
if (r && e.startsWith("/")) {
if (await this.tryExecuteExtensionCommand(e)) {
i?.(true);
return;
}
}
let c = e;
let l = t?.images;
if (this.currentExtensionRunner.hasHandlers("input")) {
const e = await this.currentExtensionRunner.emitInput(c, l, t?.source ?? "interactive");
if (e.action === "handled") {
i?.(true);
return;
}
if (e.action === "transform") {
c = e.text;
l = e.images ?? l;
}
}
const u = r ? this.expandPrompt(c) : c;
if (this.isStreaming || this.logicalPromptActive) {
if (!t?.streamingBehavior) throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
if (t.streamingBehavior === "followUp") this.queueFollowUp(u, l);
else {
const e = this.queueSteer(this.createSteeringMessage(u, l), u);
a = true;
e();
}
o = a;
i?.(true);
return;
}
if (!this.model) throw new Error(formatNoModelSelectedMessage());
if (!this.sessionModelRegistry.hasConfiguredAuth(this.model)) {
if (this.sessionModelRegistry.isUsingOAuth(this.model)) throw new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`);
throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
}
const d = t?.persistedUserIdempotencyKey;
const f = this.model.contextWindow;
const p = this.findLastAssistantMessage();
if (p) {
const e = resolvePendingRuntimeContextReplay({
messages: this.agent.state.messages,
pendingContextMessages: this.pendingNextTurnMessages,
persistedUserIdempotencyKey: d
}).pendingContextMessages;
await this.checkCompaction(p, false, n ? withCompactionQueuedContext(n, e) : typeof f === "number" && Number.isFinite(f) && f > 0 ? createCompactionRequestBudget({
contextWindow: f,
reserveTokens: this.settingsManager.getCompactionSettings().reserveTokens,
systemPrompt: this.agent.state.systemPrompt,
tools: this.agent.state.tools,
pendingPrompt: u,
pendingImageCount: l?.length,
pendingQueuedContextMessages: e,
pendingUserIdempotencyKey: d
}) : void 0);
}
const { persistedUserIndex: m, replayPersistedCarrier: h, pendingContextMessages: g } = resolvePendingRuntimeContextReplay({
messages: this.agent.state.messages,
pendingContextMessages: this.pendingNextTurnMessages,
persistedUserIdempotencyKey: d
});
const _ = m >= 0;
const v = this.agent.state.messages[m];
if (!h && v?.role === "user" && readModelPromptProjection(v) === void 0) {
const e = this.createUserMessage(u, l, v);
this.agent.state.messages = this.agent.state.messages.with(m, e);
}
s = [];
if (!_) s.push({
...this.createUserMessage(u, l),
...d ? { idempotencyKey: d } : {}
});
s.push(...g);
this.pendingNextTurnMessages = [];
const y = await this.currentExtensionRunner.emitBeforeAgentStart(u, l, this.baseSystemPrompt, this.baseSystemPromptOptions);
if (y?.messages) for (const e of y.messages) s.push(createCustomMessage(e));
this.systemPromptOverride = y?.systemPrompt;
this.agent.state.systemPrompt = this.systemPromptOverride !== void 0 ? this.systemPromptOverride : this.baseSystemPrompt;
} catch (e) {
if (a) {
let t = e;
if (!o) try {
i?.(true);
} catch (n) {
t = new AggregateError([e, n], "Steering feedback failed");
}
throw new MessageInjectionAcceptedUnconfirmedError({ cause: t });
}
i?.(false);
throw e;
}
i?.(true);
await this.runAgentPrompt(orderSystemUpdateMessages(s));
}
async tryExecuteExtensionCommand(e) {
const t = e.indexOf(" ");
const n = t === -1 ? e.slice(1) : e.slice(1, t);
const r = t === -1 ? "" : e.slice(t + 1);
const i = this.currentExtensionRunner.getCommand(n);
if (!i) return false;
const a = this.currentExtensionRunner.createCommandContext();
try {
await i.handler(r, a);
} catch (e) {
this.currentExtensionRunner.emitError({
extensionPath: `command:${n}`,
event: "command",
error: e instanceof Error ? e.message : String(e)
});
}
return true;
}
/**
* Expand skill commands (/skill:name args) to their full content.
* Returns the expanded text, or the original text if not a skill command or skill not found.
* Emits errors via extension runner if file read fails.
*/
expandSkillCommand(e) {
if (!e.startsWith("/skill:")) return e;
const t = e.indexOf(" ");
const n = t === -1 ? e.slice(7) : e.slice(7, t);
const r = t === -1 ? "" : e.slice(t + 1).trim();
const i = this.sessionResourceLoader.getSkills().skills.find((e) => e.name === n);
if (!i) return e;
try {
const e = readFileSync(i.filePath, "utf-8");
const t = stripFrontmatter(e).trim();
const n = `<skill name="${i.name}" location="${i.filePath}">\nReferences are relative to ${i.baseDir}.\n\n${t}\n</skill>`;
return r ? `${n}\n\n${r}` : n;
} catch (t) {
this.currentExtensionRunner.emitError({
extensionPath: i.filePath,
event: "skill_expansion",
error: t instanceof Error ? t.message : String(t)
});
return e;
}
}
expandPrompt(e) {
return expandPromptTemplate(this.expandSkillCommand(e), [...this.promptTemplates]);
}
/**
* Queue a steering message while the agent is running.
* Delivered before the next unstarted tool launch or model call. Running tools
* continue; suppressed calls receive paired synthetic results.
* Expands skill commands and prompt templates. Errors on extension commands.
* @param userTurnTranscriptRecorder Prepared channel fields for transcript-only persistence
* @param currentInboundContext This turn's runtime facts, separate from its command and transcript
* @throws Error if text is an extension command
*/
async steer(e, t, n, r, i, a, o, s, c, l) {
if (e.startsWith("/")) this.throwIfExtensionCommand(e);
const u = this.expandPrompt(e);
return enqueueMessageInjection(this, async () => {
const e = await n?.resolveMessage();
const d = this.createSteeringMessage(u, t, e && n ? {
message: e,
recorder: n
} : void 0, r, i, a, s);
let f;
let p;
try {
await withMessageInjectionAdmission(c, () => {
if (o && !o()) throw new Error("active session is finalizing");
f = this.queueSteer(d, u);
l?.();
});
} catch (e) {
p = { error: e };
}
try {
f?.();
} catch (e) {
throw new MessageInjectionAcceptedUnconfirmedError({ cause: p ? new AggregateError([p.error, e], "Steering admission and notification failed") : e });
}
if (p) throw p.error;
});
}
/**
* Queue a follow-up message to be processed after the agent finishes.
* Delivered only when agent has no more tool calls or steering messages.
* Expands skill commands and prompt templates. Errors on extension commands.
* @throws Error if text is an extension command
*/
async followUp(e, t) {
if (e.startsWith("/")) this.throwIfExtensionCommand(e);
this.queueFollowUp(this.expandPrompt(e), t);
}
createSteeringMessage(e, t, n, r, i, a, o) {
const s = this.createUserMessage(annotateInterSessionPromptText(e, n?.message.provenance), t, n?.message);
const c = r?.length ? attachRuntimePromptMediaFacts(s, r, i) : s;
attachSteeringRuntimeContext(c, o);
setSteeringMessageIdentity(c, a);
return n ? attachRuntimeUserTurnTranscriptContext(c, n) : c;
}
/** Install only queue state here; arbitrary listeners run after admission cleanup. */
queueSteer(e, t) {
this.trackQueuedUserMessage(e, "steering", t);
const n = this.agent.admitSteeringMessage(e);
return () => {
const e = [];
notifyListeners([() => this.emitQueueUpdate(), () => n()], void 0, (t) => e.push(t));
throwCollectedErrors(e, "Steering notifications failed");
};
}
/** Queue pre-expanded follow-up input without an extension-command check. */
queueFollowUp(e, t) {
const n = this.createUserMessage(e, t);
this.trackQueuedUserMessage(n, "followUp", e);
this.emitQueueUpdate();
this.agent.followUp(n);
}
throwIfExtensionCommand(e) {
const t = e.indexOf(" ");
const n = t === -1 ? e.slice(1) : e.slice(1, t);
if (this.currentExtensionRunner.getCommand(n)) throw new Error(`Extension command "/${n}" cannot be queued. Use prompt() or execute the command when not streaming.`);
}
/**
* Send a custom message to the session. Creates a CustomMessageEntry.
*
* Handles three cases:
* - Streaming: queues message, processed when loop pulls from queue
* - Not streaming + triggerTurn: appends to state/session, starts new turn
* - Not streaming + no trigger: appends to state/session, no turn
*
* @param options.triggerTurn If true and not streaming, triggers a new LLM turn
*/
async sendCustomMessage(e, t) {
const n = createCustomMessage(e);
if (t?.deliverAs === "nextTurn") this.pendingNextTurnMessages.push(n);
else if (this.isStreaming) {
if (t?.deliverAs === "followUp") this.agent.followUp(n);
else this.agent.steer(n);
} else if (t?.triggerTurn) await this.runAgentPrompt(n);
else await this.persistCustomMessage(n);
}
async persistCustomMessage(e) {
await withSessionManagerAppend(this.sessionManager, async () => {
await this.sessionManager.appendCustomMessageEntryAsync(e.customType, e.content, e.display, e.details, e.timestamp);
this.agent.state.messages.push(e);
});
this.emit({
type: "message_start",
message: e
});
this.emit({
type: "message_end",
message: e
});
}
/**
* Send a user message to the agent. Always triggers a turn.
* When the agent is streaming, use deliverAs to specify how to queue the message.
*/
async sendUserMessage(e, t) {
let n;
let r;
if (typeof e === "string") n = e;
else {
const t = [];
r = [];
for (const n of e) if (n.type === "text") t.push(n.text);
else r.push(n);
n = t.join("\n");
if (r.length === 0) r = void 0;
}
await this.prompt(n, {
expandPromptTemplates: false,
streamingBehavior: t?.deliverAs,
images: r,
source: "extension"
});
}
/**
* Clear all queued messages and return them.
* Useful for restoring to editor when user aborts.
*/
clearQueue() {
const e = this.steeringMessages.map((e) => e.text);
const t = this.followUpMessages.map((e) => e.text);
this.steeringMessages = [];
this.followUpMessages = [];
this.agent.clearAllQueues();
this.emitQueueUpdate();
return {
steering: e,
followUp: t
};
}
/** Number of pending messages (includes both steering and follow-up) */
get pendingMessageCount() {
return this.steeringMessages.length + this.followUpMessages.length;
}
getSteeringMessages() {
return this.steeringMessages.map((e) => e.text);
}
getFollowUpMessages() {
return this.followUpMessages.map((e) => e.text);
}
get resourceLoader() {
return this.sessionResourceLoader;
}
/** Abort the current run; yield callers pass a turnHandoff reason to skip interruption guidance. */
async abort(e) {
this.abortRetry();
this.agent.abort(e);
await this.agent.waitForIdle();
}
};
//#endregion
export { hasPersistedAssistantContent as _, expandTildePath as a, setSessionToolResultPreparer as c, emitSessionShutdownEvent as d, createExtensionRuntime as f, extractTextContent as g, estimateMessagesFromContent as h, loadPromptTemplates as i, retireQueuedUserMessage as l, formatNoModelSelectedMessage as m, agentSessionQueuePromptContext as n, getSteeringMessageIdentity as o, loadExtensionFromFactory as p, agentSessionSetPromptPreparation as r, subscribeSteeringMessagePersistenceFailure as s, AgentSessionPrompting as t, ExtensionRunner as u, unwrapCoreResult as v, sanitizeCompactionReplayMessages as y };