openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,284 lines (1,283 loc) • 44.1 kB
JavaScript
import { E as parseStrictNonNegativeInteger, n as MAX_TIMER_TIMEOUT_MS } from "./number-coercion-D6u-4YD8.mjs";
import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { n as waitForAbortSignal } from "./abort-signal-D4Q6SEw7.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { j as parseAgentSessionKey, r as agentSessionKeysMatchByRequestKey } from "./session-key-CqAyZeVk.mjs";
import { _ as resolveDefaultAgentId, a as resolveAgentDir, d as resolveAgentVerboseDefault, f as resolveAgentWorkspaceDir, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as GatewayScheduler } from "./gateway-scheduler-BApPBa3S.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { i as classifyAgentRunTerminalOutcome, s as isDefinitiveRunLifecycle } from "./agent-run-terminal-outcome-CurjWZiA.mjs";
import { l as getAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { m as onAgentEvent } from "./agent-events-BdfWYmot.mjs";
import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs";
import { t as captureRuntimeConfigAsyncReader, y as registerConfigWriteListener } from "./io.runtime-DsJ2dLCQ.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { y as isAgentLifecycleYieldedWaiting } from "./session-entry-patch-operation--iew--8y.mjs";
import { i as buildAgentRunTerminalOutcomeFromLifecycleEvent, t as AGENT_RUN_TERMINAL_RETRY_GRACE_MS } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { n as findAgentRunTerminalOutcome } from "./agent-run-terminal-error-CbmFnPGI.mjs";
import { X as captureSessionTarget, d as getSessionControllerOperation } from "./session-controller.state-BApgK0mV.mjs";
import { o as readToolValidationErrorSummary } from "./tool-error-summary-BTwB17cj.mjs";
import { T as resolveEffectiveChatHistoryMaxChars } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { t as CHAT_HISTORY_MAX_ENTRIES } from "./chat-history-constants-BGgHv5E_.mjs";
import "./config-CMA-J084.mjs";
import { m as applySessionPatchProjection } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs";
import { i as logWarn, r as logInfo } from "./logger-CIwfuhOU.mjs";
import { c as getSubagentSessionListReadSnapshotIdentity, f as prepareOptionalSubagentSessionListReadCache } from "./subagent-registry-state-CMZQXOjY.mjs";
import { r as resolveGatewaySessionStoreTargetInWorker, t as loadGatewaySessionEntryReadOnlyInWorker } from "./session-utils-store-worker-BU_tdh8T.mjs";
import { A as buildCollectPrompt, M as previewQueueSummaryPrompt, N as waitForQueueDebounce, k as applyQueueDropPolicy } from "./session-controller.mailbox-BcK8UF_b.mjs";
import "./model-selection-C2A4Wyix.mjs";
import { r as resolveThinkingDefaultCore } from "./model-thinking-default-DTaWSs8g.mjs";
import { t as ensureContextWindowCacheLoaded } from "./context-C1qC4w3b.mjs";
import { s as getPreparedModelRuntimeAuthMaterializations } from "./prepared-model-runtime-auth-DVZroiat.mjs";
import { r as resolvePublishedModelCatalogOwner } from "./prepared-model-catalog-owner-Cf9g0CZ4.mjs";
import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs";
import { i as readSessionRuntimeOwnershipAsync } from "./session-utils-model-selection-BGYqZws_.mjs";
import { n as projectSessionPatchResult, t as getSessionDefaults } from "./session-utils-model-BFA7PxHy.mjs";
import { L as buildGatewaySessionRow, s as withReadySessionRows } from "./session-row-prepared-read-B4U_T7SO.mjs";
import { n as resolveQueueSettingsCore } from "./settings-D_ru6nFL.mjs";
import { t as DEFAULT_QUEUE_DROP } from "./state-DGvM9kEH.mjs";
import { t as readAcpSessionMetaForEntries } from "./session-meta-readonly-B5S0IsZ_.mjs";
import { n as listAgentsForGateway, s as resolveCanonicalGatewaySessionStoreKey } from "./session-utils-store-CiI_s_OK.mjs";
import { S as refreshPreparedModelRuntimeSnapshots } from "./prepared-model-runtime-Bbo9uBdt.mjs";
import { n as loadAgentRuntimePluginRegistryHandle } from "./runtime-plugins-eG0JDbQ7.mjs";
import { a as loadPreparedModelCatalogSnapshot, d as readPreparedModelCatalog, p as withPreparedModelCatalogOwner } from "./prepared-model-catalog-DSktrHGK.mjs";
import { t as createDefaultDeps } from "./deps-CeXkTZma.mjs";
import { a as shouldSuppressAssistantEventForLiveChat, i as projectLiveAssistantBufferedText, r as normalizeLiveAssistantBufferedText, t as capLiveAssistantText } from "./live-chat-projector-C9HZP1xD.mjs";
import { i as resolveAssistantTextInput, n as mergeAssistantText } from "./agent-event-assistant-text-BJ77EXnU.mjs";
import { n as setEmbeddedMode } from "./embedded-mode-CncGOzNj.mjs";
import { i as setEmbeddedPluginApprovalBroker, n as clearEmbeddedPluginApprovalBroker, t as EmbeddedPluginApprovalBroker } from "./embedded-plugin-approval-broker-DbncI1uW.mjs";
import "./commands-registry-CwAxsNJ9.mjs";
import { r as resolveTextCommand } from "./commands-registry-normalize-dI3NYF5y.mjs";
import { i as parseGoalCommand, t as executeSessionGoalCommand } from "./commands-goal-BISKgDmP.mjs";
import { n as steerSessionControllerOperation } from "./session-controller.steer-BWjVys2Y.mjs";
import { t as capArrayByJsonBytes } from "./session-utils.fs-bIf8ZZfW.mjs";
import "./session-transcript-readers-D1WqgwbF.mjs";
import { n as isAbortRequestText } from "./abort-primitives-Bk9blQey.mjs";
import { x as claimPendingEmbeddedAgentQuestionAnswer } from "./runs-C1RO1Y6L.mjs";
import { n as listProjectedSessions } from "./session-utils-list-D0dvr3s4.mjs";
import "./session-utils-CavYkLyd.mjs";
import { t as createDraftStreamLoop } from "./draft-stream-loop-VIZuBFdU.mjs";
import { r as agentCommandFromIngress } from "./agent-command-FXkX3hj5.mjs";
import "./chat-display-projection-lHBiRfmJ.mjs";
import { t as bindEmbeddedSessionRowProjection } from "./embedded-gateway-stub-D0l-Ztkj.mjs";
import { a as createChatHistoryActivityProjection, c as getMaxChatHistoryMessagesBytes, l as replaceOversizedChatHistoryMessages, o as createChatHistoryByteCounter, t as CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES } from "./chat-history-budget-DoE23WjR.mjs";
import { n as readChatHistoryPage, r as enrichChatHistoryCompactionMarkers } from "./chat-history-pages-DJbqhqAa.mjs";
import { n as performGatewaySessionReset } from "./session-reset-service-DH7-Rpxw.mjs";
import { l as formatTuiErrorMessage } from "./tui-formatters-C-21edEr.mjs";
import { i as prepareGatewaySessionEntryReader } from "./combined-store-gateway-read-Bce0UNKu.mjs";
import { t as createGatewaySession } from "./session-create-service-D_50iC0B.mjs";
import { n as projectSessionsPatchEntry } from "./sessions-patch-BSneB8xP.mjs";
import { t as buildModelsListResult } from "./models-list-result-BOk0LqJ-.mjs";
import { t as createSessionRowProjection } from "./session-row-projection-Cx7KEDy3.mjs";
import { i as setEmbeddedQuestionBroker, n as clearEmbeddedQuestionBroker, t as EmbeddedQuestionBroker } from "./embedded-question-broker-C0WGw6Cx.mjs";
import { randomUUID } from "node:crypto";
//#region src/tui/embedded-chat-projection.ts
const TUI_STATE_BY_TERMINAL_CLASSIFICATION = {
success: void 0,
timeout: "error",
cancellation: "aborted",
failure: "error"
};
function resolveTerminalChatState(e) {
return TUI_STATE_BY_TERMINAL_CLASSIFICATION[classifyAgentRunTerminalOutcome(e)];
}
function assistantChatMessage(e) {
return {
role: "assistant",
content: [{
type: "text",
text: e
}],
timestamp: Date.now()
};
}
function projectLocalRunText(e, t = false) {
return projectLiveAssistantBufferedText(normalizeLiveAssistantBufferedText(e.buffer, {
final: t,
managedMediaUrls: [...e.managedMediaUrls]
}));
}
function payloadText(e) {
if (!Array.isArray(e)) return "";
return e.map((e) => {
const t = asOptionalObjectRecord(e);
return typeof t?.text === "string" ? t.text.trim() : "";
}).filter(Boolean).join("\n\n").trim();
}
function resolveDeltaPayload(e, t) {
if (t === void 0) return { deltaText: e };
if (!e.startsWith(t)) return {
deltaText: e,
replace: true
};
return { deltaText: e.slice(t.length) };
}
//#endregion
//#region src/tui/embedded-history-runtime.ts
function ensureEmbeddedHistoryRuntimePluginsLoaded(e) {
try {
const t = resolveAgentWorkspaceDir(e.cfg, e.sessionAgentId);
loadAgentRuntimePluginRegistryHandle({
config: e.cfg,
workspaceDir: t
});
return { status: "warmed" };
} catch (e) {
return {
status: "failed",
error: formatTuiErrorMessage(e)
};
}
}
//#endregion
//#region src/tui/local-run-shutdown.ts
const LOCAL_RUN_SHUTDOWN_GRACE_MS = 12e4;
/** Resolves the hard-exit grace period for local TUI shutdown. */
function resolveLocalRunShutdownGraceMs() {
const e = process.env.OPENCLAW_TUI_LOCAL_RUN_SHUTDOWN_GRACE_MS?.trim();
const t = parseStrictNonNegativeInteger(e);
if (t !== void 0) return Math.min(t, MAX_TIMER_TIMEOUT_MS);
return LOCAL_RUN_SHUTDOWN_GRACE_MS;
}
//#endregion
//#region src/tui/embedded-local-run.ts
function createLocalRunState(e, t) {
const n = new AbortController();
const r = createDeferredCore();
const i = {
...t,
controller: n,
buffer: "",
managedMediaUrls: /* @__PURE__ */ new Set(),
finishing: false,
lifecycleEnded: false,
registered: false,
queuedRunReady: r.promise,
markQueuedRunReady: r.resolve
};
n.signal.addEventListener("abort", () => {
if (getAgentRunContext(e)?.localModelWait) i.localModelMayStillBeFinishing = true;
}, { once: true });
return i;
}
function timeoutSecondsFromMs(e) {
if (typeof e !== "number" || !Number.isFinite(e) || e < 0) return;
return String(Math.max(0, Math.ceil(e / 1e3)));
}
function buildLocalQueuedPrompt(e) {
return [previewQueueSummaryPrompt(e), e.mode === "collect" && e.messages.length > 1 ? buildCollectPrompt({
title: "[Queued messages while agent was busy]",
items: e.messages,
renderItem: (e, t) => `---\nQueued #${t + 1}\n${e}`
}) : e.messages[0] ?? ""].filter(Boolean).join("\n\n");
}
async function waitForLocalRunShutdown(e) {
if (e.length === 0) return true;
const t = resolveLocalRunShutdownGraceMs();
if (t <= 0) return false;
return await settlesWithin(Promise.allSettled(e), t);
}
async function waitForQueuedLocalRun(e, t) {
await e.run.queuedRunReady;
if (e.run.controller.signal.aborted && e.run.queuedAfter) return await waitForQueuedLocalRun(e.run.queuedAfter, t);
if (!e.run.finishing && !e.run.lifecycleEnded) {
await e.promise;
return;
}
const n = resolveLocalRunShutdownGraceMs();
if (n <= 0 || !await settlesWithin(e.promise, n)) throw new Error(`timed out waiting for previous local run to finish post-turn maintenance for ${t}`);
}
function isSameLocalRunScope(e, t) {
return e.sessionKey === t.sessionKey && (t.sessionKey !== "global" || e.agentId === t.agentId);
}
//#endregion
//#region src/tui/embedded-local-queue.ts
function findQueuedSessionRun(e, t) {
let n;
for (const [r, i] of e) if (isSameLocalRunScope(i, t) && !i.question && i.promise) n = {
runId: r,
run: i,
promise: i.promise
};
return n;
}
function enqueuePendingLocalMessage(e, t) {
const n = [];
for (const r of e.values()) if (isSameLocalRunScope(r, t.runScope) && r.pendingQueue) r.pendingQueue.messages.forEach((e, t) => {
n.push({
run: r,
messageIndex: t,
message: e
});
});
const r = [];
const i = {
items: [...n],
cap: t.settings.cap ?? 20,
dropPolicy: t.settings.dropPolicy ?? "summarize",
droppedCount: 0,
summaryLines: r
};
if (!applyQueueDropPolicy({
queue: i,
summarize: (e) => e.message
})) return { kind: "rejected" };
const a = new Set(i.items);
const o = /* @__PURE__ */ new Map();
for (const e of n) {
if (a.has(e)) continue;
const t = o.get(e.run) ?? [];
t.push(e.messageIndex);
o.set(e.run, t);
}
const s = [];
for (const [e, t] of o) {
for (const n of t.toSorted((e, t) => t - e)) e.pendingQueue?.messages.splice(n, 1);
if (e.pendingQueue?.messages.length === 0) {
s.push(...e.pendingQueue.summaryLines);
i.droppedCount += e.pendingQueue.droppedCount;
e.controller.abort();
}
}
i.summaryLines.unshift(...s);
if (i.summaryLines.length > i.cap) i.summaryLines.splice(0, i.summaryLines.length - i.cap);
const c = Date.now();
for (const n of e.values()) {
if (!isSameLocalRunScope(n, t.runScope) || !n.pendingQueue) continue;
n.pendingQueue.lastEnqueuedAt = c;
n.pendingQueue.debounceMs = t.settings.debounceMs ?? 500;
}
if (t.settings.mode === "collect") {
const n = [...e.entries()].findLast(([, e]) => isSameLocalRunScope(e, t.runScope) && e.pendingQueue);
const r = n?.[1].pendingQueue;
if (n && r?.mode === "collect" && !n[1].controller.signal.aborted) {
const [e] = n;
r.messages.push(t.message);
r.dropPolicy = t.settings.dropPolicy ?? "summarize";
r.droppedCount += i.droppedCount;
r.summaryLines.push(...i.summaryLines);
return {
kind: "handled",
runId: e
};
}
}
return {
kind: "enqueue",
queue: {
mode: t.settings.mode === "collect" ? "collect" : "followup",
messages: [t.message],
debounceMs: t.settings.debounceMs ?? 500,
lastEnqueuedAt: c,
dropPolicy: t.settings.dropPolicy ?? "summarize",
droppedCount: i.droppedCount,
summaryLines: i.summaryLines
}
};
}
//#endregion
//#region src/tui/embedded-prepared-runtime.ts
var EmbeddedPreparedModelRuntimeHost = class {
constructor() {
this.ready = Promise.resolve();
}
publish(e) {
this.ready = refreshPreparedModelRuntimeSnapshots(e);
this.ready.catch(() => void 0);
}
async waitUntilReady() {
for (;;) {
const e = this.ready;
await e;
if (e === this.ready) return;
}
}
};
//#endregion
//#region src/tui/embedded-runtime.ts
const silentRuntime = {
log: (...e) => void 0,
error: (...e) => void 0,
exit: (e) => {
throw new Error(`embedded tui runtime exit ${String(e)}`);
}
};
const embeddedSessionStartupMigrationLog = {
info: (e) => logInfo(e, silentRuntime),
warn: (e) => logWarn(e, silentRuntime)
};
//#endregion
//#region src/tui/embedded-session-reader.ts
async function readEmbeddedHistorySession(e) {
if (!getSubagentSessionListReadSnapshotIdentity()) await prepareOptionalSubagentSessionListReadCache();
return loadGatewaySessionEntryReadOnlyInWorker({
cfg: readRuntimeConfig(),
key: e.sessionKey,
...e.agentId ? { agentId: e.agentId } : {},
includeStoreChildEntries: true
});
}
function readEmbeddedHistorySessionInfo(e, t, n) {
return withReadySessionRows(e, () => [t], (e) => {
const r = e.describe(t);
return r && r.entry.sessionId === n.sessionId && r.entry.lifecycleRevision === n.lifecycleRevision ? e.present(r) : void 0;
});
}
async function readEmbeddedPrivateHistorySessionInfo(e, t) {
const { cfg: n, agentId: r, canonicalKey: i, storePath: a, store: o, readSource: s } = e;
const [c] = await readAcpSessionMetaForEntries({
cfg: n,
entries: [{
agentId: r,
sessionKey: i,
entry: t
}]
});
const l = await readSessionRuntimeOwnershipAsync({
config: n,
agentId: r,
sessionKey: i,
storePath: s?.path ?? a,
sessionEntry: t,
readPreparedPreviousSessionId: () => t.previousSessionId
});
const u = l?.modelRef ? (e) => o[e] : await prepareGatewaySessionEntryReader({
...e,
sessionKey: i,
entry: t
});
return buildGatewaySessionRow({
cfg: n,
storePath: a,
store: o,
key: i,
entry: t,
preparedAcpMeta: c ?? null,
preparedRuntimeOwnership: l ?? null,
agentId: r,
modelSource: {
entry: t,
readSourceEntry: u
},
lightweightListRow: true
});
}
function createEmbeddedSessionReader(e) {
const read = async (t, n) => {
await e.ready();
const r = e.projection();
const i = await r;
if (!i || r !== e.projection()) throw new Error("Embedded session projection is unavailable");
const a = await listProjectedSessions({
projection: i,
opts: t ?? {},
...n !== void 0 ? { key: n } : {}
});
if (r !== e.projection()) throw new Error("Embedded session projection is unavailable");
return a;
};
return {
listSessions: (e) => read(e),
async describeSession(e) {
const t = parseAgentSessionKey(e.sessionKey);
const n = await read({
agentId: e.agentId ?? t?.agentId,
includeGlobal: e.sessionKey === "global" || t?.rest === "global",
includeUnknown: e.sessionKey === "unknown" || t?.rest === "unknown",
limit: 1
}, e.sessionKey);
return {
session: n.sessions[0] ?? null,
defaults: n.defaults
};
}
};
}
//#endregion
//#region src/tui/embedded-session-steering.ts
/** Prepare the local ingress caller independently of the active turn's authority. */
function steerEmbeddedSessionInput(e) {
const { sessionEntry: t, abortSignal: n } = e;
return steerSessionControllerOperation({
operation: e.operation,
text: e.text,
options: {
steeringMode: "all",
debounceMs: e.debounceMs,
isInboundUserMessage: true,
abortSignal: n,
assertCurrent: () => n.throwIfAborted(),
toolAuthorityOverlay: {
originatingChannel: INTERNAL_MESSAGE_CHANNEL,
messageProvider: INTERNAL_MESSAGE_CHANNEL,
senderId: e.senderId,
permissionMode: t?.permissionMode,
toolOverrides: t?.toolOverrides,
chatType: t?.chatType,
spawnedBy: t?.spawnedBy,
senderIsOwner: false,
traceAuthorized: false,
disableTools: false
}
}
});
}
//#endregion
//#region src/tui/embedded-backend.ts
var EmbeddedTuiBackend = class {
constructor() {
this.connection = { url: "local embedded" };
this.deps = createDefaultDeps();
this.localSenderId = randomUUID();
this.runs = /* @__PURE__ */ new Map();
this.seq = 0;
this.pendingLifecycleErrors = /* @__PURE__ */ new Map();
this.scheduler = new GatewayScheduler();
this.emitBrokerEvent = (e) => {
if (!this.scheduler.signal.aborted) this.emit(e.event, e.payload);
};
this.pluginApprovalBroker = new EmbeddedPluginApprovalBroker(this.emitBrokerEvent);
this.questionBroker = new EmbeddedQuestionBroker(this.scheduler, this.emitBrokerEvent);
this.preparedModelRuntime = new EmbeddedPreparedModelRuntimeHost();
this.ready = Promise.resolve();
this.sessionReader = createEmbeddedSessionReader({
ready: () => this.ready,
projection: () => this.sessionProjection
});
this.listSessions = this.sessionReader.listSessions;
this.describeSession = this.sessionReader.describeSession;
}
start() {
if (this.unsubscribe) return;
setEmbeddedMode(true);
ensureContextWindowCacheLoaded();
this.previousRuntimeLog = defaultRuntime.log;
this.previousRuntimeError = defaultRuntime.error;
defaultRuntime.log = silentRuntime.log;
defaultRuntime.error = silentRuntime.error;
this.unsubscribe = onAgentEvent((e) => this.handleAgentEvent(e));
setEmbeddedPluginApprovalBroker(this.pluginApprovalBroker);
setEmbeddedQuestionBroker(this.questionBroker);
this.sessionProjection = (async () => {
const e = await captureRuntimeConfigAsyncReader()();
const { runSessionStartupMigration: t } = await import("./startup-migration-G4xLSSxu.mjs");
await t({
cfg: e,
env: process.env,
log: embeddedSessionStartupMigrationLog
});
this.unsubscribeConfigWrites = registerConfigWriteListener((e) => {
this.preparedModelRuntime.publish(e.runtimeConfig);
});
this.preparedModelRuntime.publish(readRuntimeConfig());
return createSessionRowProjection({
cfg: readRuntimeConfig(),
getConfig: readRuntimeConfig
});
})();
this.ready = this.sessionProjection.then(() => {});
this.ready.catch(() => {});
this.unbindSessionProjection = bindEmbeddedSessionRowProjection(this.sessionProjection);
queueMicrotask(() => {
this.onConnected?.();
});
}
async stop() {
this.scheduler.beginClose();
clearEmbeddedPluginApprovalBroker(this.pluginApprovalBroker);
clearEmbeddedQuestionBroker(this.questionBroker);
const e = [];
for (const t of this.runs.values()) {
t.textUpdates?.stop();
if (t.finishing || t.lifecycleEnded) {
if (t.promise) e.push(t.promise);
continue;
}
t.controller.abort();
}
this.pluginApprovalBroker.stop();
this.questionBroker.stop();
await this.scheduler.stop();
if (!await waitForLocalRunShutdown(e)) {
for (const e of this.runs.values()) if (e.finishing || e.lifecycleEnded) e.controller.abort();
}
await Promise.allSettled([...this.runs.values()].flatMap((e) => e.promise ?? []));
this.unbindSessionProjection?.();
this.unbindSessionProjection = void 0;
const t = this.sessionProjection;
this.sessionProjection = void 0;
await t?.catch(() => void 0).then((e) => e?.dispose());
this.unsubscribeConfigWrites?.();
this.unsubscribeConfigWrites = void 0;
this.unsubscribe?.();
this.unsubscribe = void 0;
this.pendingLifecycleErrors.forEach(clearTimeout);
this.pendingLifecycleErrors.clear();
defaultRuntime.log = this.previousRuntimeLog ?? defaultRuntime.log;
defaultRuntime.error = this.previousRuntimeError ?? defaultRuntime.error;
this.previousRuntimeLog = void 0;
this.previousRuntimeError = void 0;
setEmbeddedMode(false);
await this.preparedModelRuntime.waitUntilReady();
}
async sendChat(e) {
await this.ready;
await this.preparedModelRuntime.waitUntilReady();
this.scheduler.signal.throwIfAborted();
const t = e.runId ?? randomUUID();
const n = resolveTextCommand(e.message);
const r = n?.command.key === "followup";
let i = e;
if (r) {
if (!n.args) throw new Error("Usage: /followup <message>");
i = {
...e,
message: n.args
};
}
const a = n?.command.key === "btw" ? n.args : void 0;
const o = !r && n?.command.key === "queue";
const s = resolveSessionAgentId({
sessionKey: i.sessionKey,
config: readRuntimeConfig(),
agentId: i.agentId
});
const c = {
sessionKey: i.sessionKey,
agentId: s
};
const l = findQueuedSessionRun(this.runs, c);
const u = !r && l !== void 0 && isAbortRequestText(i.message);
const d = a || u || o ? void 0 : l;
if (u) {
this.abortSessionRuns(c);
return { runId: t };
}
let f;
if (d) {
const e = i.agentId ? { agentId: i.agentId } : void 0;
const { cfg: t, canonicalKey: n, entry: a, storePath: o, agentId: s } = await loadGatewaySessionEntryReadOnlyInWorker({
cfg: readRuntimeConfig(),
key: i.sessionKey,
...e
});
this.scheduler.signal.throwIfAborted();
const l = getSessionControllerOperation(n, captureSessionTarget({
storeScope: o,
sessionKey: n,
aliases: [i.sessionKey],
agentId: s,
incarnation: a?.sessionId
}));
if (l && !r) {
const e = await claimPendingEmbeddedAgentQuestionAnswer(l, i.message);
if (e) return e;
this.scheduler.signal.throwIfAborted();
}
let u = resolveQueueSettingsCore({
cfg: t,
channel: INTERNAL_MESSAGE_CHANNEL,
sessionEntry: a,
...r ? { inlineMode: "followup" } : {}
});
if (u.mode === "steer") {
if (l) {
const e = await steerEmbeddedSessionInput({
operation: l,
text: i.message,
senderId: this.localSenderId,
sessionEntry: a,
debounceMs: u.debounceMs ?? 500,
abortSignal: this.scheduler.signal
});
if (e.status === "indeterminate") throw new Error(e.errorMessage);
if (e.status === "accepted") {
if (e.result?.transcriptCommit === "unconfirmed") throw new Error(e.result.errorMessage);
return { runId: d.runId };
}
}
this.scheduler.signal.throwIfAborted();
u = {
...u,
mode: "followup"
};
}
if (u.mode === "interrupt") this.abortSessionRuns(c);
else {
const e = enqueuePendingLocalMessage(this.runs, {
runScope: c,
message: i.message,
settings: u
});
if (e.kind === "rejected") {
if (r) throw new Error("Your followup was not queued because the session queue is full.");
return { runId: d.runId };
}
if (e.kind === "handled") return { runId: e.runId };
f = e.queue;
}
}
const p = createLocalRunState(t, {
sessionKey: i.sessionKey,
agentId: s,
question: a,
...r ? { explicitFollowup: true } : {},
...f ? { pendingQueue: f } : {},
...d ? { queuedAfter: d } : {}
});
this.runs.set(t, p);
const m = p.promise = this.runTurn(t, p, i);
if (o) await m;
return {
runId: t,
...r && d ? { status: "queued" } : {}
};
}
async abortChat(e) {
const t = [];
const n = e.runId ? [[e.runId, this.runs.get(e.runId)]] : this.runs;
for (const [r, i] of n) {
if (!i || !e.runId && i.question || i.sessionKey !== e.sessionKey) continue;
if (e.sessionKey === "global") {
const t = e.agentId && i.agentId ? void 0 : resolveDefaultAgentId(readRuntimeConfig());
const n = e.agentId ? normalizeAgentId(e.agentId) : t;
if ((i.agentId ? normalizeAgentId(i.agentId) : t) !== n) continue;
}
if (!this.isAbortableRun(i)) continue;
i.controller.abort();
t.push(r);
}
return {
ok: true,
aborted: t.length > 0,
runIds: t
};
}
async loadImage(e) {
const { loadEmbeddedImage: t } = await import("./embedded-image-loader-DbWfUboR.mjs");
return await t(e);
}
async loadHistory(e) {
await this.ready;
await this.preparedModelRuntime.waitUntilReady();
const t = await readEmbeddedHistorySession(e);
const { cfg: n, agentId: r, storePath: i, readSource: a, entry: o, canonicalKey: s } = t;
const c = o?.sessionId;
const l = ensureEmbeddedHistoryRuntimePluginsLoaded({
cfg: n,
sessionAgentId: r
});
const u = resolveSessionModelRef(n, o, r);
const d = Math.min(CHAT_HISTORY_MAX_ENTRIES, e.limit ?? 200);
const f = getMaxChatHistoryMessagesBytes();
const p = resolveEffectiveChatHistoryMaxChars();
const m = await readChatHistoryPage({
entry: o,
provider: u.provider,
sessionId: c,
storePath: i,
sessionAgentId: r,
canonicalKey: s,
max: d,
maxHistoryBytes: f,
effectiveMaxChars: p,
offset: void 0,
messageId: void 0
});
const h = enrichChatHistoryCompactionMarkers(m.messages, o);
const g = createChatHistoryActivityProjection(h, m.activity);
const _ = createChatHistoryByteCounter(g);
const v = replaceOversizedChatHistoryMessages({
messages: h,
byteCounter: _,
maxSingleMessageBytes: Math.min(CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES, f)
});
const y = capArrayByJsonBytes(v.messages, f - _.framingBytes(v.messages), _.messageBytes).items;
const b = [...this.runs.entries()].findLast(([, t]) => !t.question && t.terminalState !== "final" && agentSessionKeysMatchByRequestKey(t.sessionKey, e.sessionKey) && normalizeAgentId(t.agentId) === normalizeAgentId(r));
const x = b ? {
runId: b[0],
text: projectLocalRunText(b[1]).text.trim()
} : void 0;
let S = o?.thinkingLevel;
if (!S) {
const e = await readPreparedModelCatalog({
config: n,
agentId: r,
readOnly: true
});
S = resolveThinkingDefaultCore({
cfg: n,
agentId: r,
provider: u.provider,
model: u.model,
catalog: e
});
}
const C = getSessionDefaults(n, void 0, { allowPluginNormalization: false });
const w = await this.sessionProjection;
const T = {
key: s,
agentId: r,
storePath: a?.path ?? i
};
const E = o && (o.incognito || isIncognitoSessionKey(s)) ? await readEmbeddedPrivateHistorySessionInfo(t, o) : o && w ? await readEmbeddedHistorySessionInfo(w, T, {
sessionId: c,
lifecycleRevision: o.lifecycleRevision
}) : void 0;
const D = o?.verboseLevel ?? resolveAgentVerboseDefault(n, r);
if (E) {
E.thinkingLevel = S;
E.verboseLevel = D;
}
return {
sessionKey: e.sessionKey,
sessionId: c,
messages: y,
defaults: C,
activity: y.flatMap((e) => g.get(e) ?? []),
...E ? { sessionInfo: E } : {},
thinkingLevel: S,
fastMode: o?.fastMode,
verboseLevel: D,
runtimePluginsPrewarm: l,
...x ? { inFlightRun: x } : {}
};
}
async listAgents() {
return await listAgentsForGateway(readRuntimeConfig());
}
async patchSession(e) {
await this.ready;
await this.preparedModelRuntime.waitUntilReady();
const t = readRuntimeConfig();
const n = await resolveGatewaySessionStoreTargetInWorker({
cfg: t,
key: e.key,
agentId: e.agentId
});
const r = await applySessionPatchProjection({
...e.label === void 0 ? { sessionKeys: n.storeKeys } : {},
storePath: n.storePath,
resolveTarget: ({ store: r }) => {
const { target: i, primaryKey: a } = resolveCanonicalGatewaySessionStoreKey({
cfg: t,
key: e.key,
store: r,
agentId: e.agentId,
target: n
});
return {
primaryKey: a,
candidateKeys: i.storeKeys
};
},
project: async ({ primaryKey: r, existingEntry: i, isLabelInUse: a }) => await projectSessionsPatchEntry({
cfg: t,
existingEntry: i,
isLabelInUse: a,
storeKey: r,
agentId: n.agentId,
patch: e,
loadGatewayModelCatalogSnapshot: () => loadPreparedModelCatalogSnapshot({
config: t,
agentId: n.agentId,
readOnly: true
})
})
});
if (!r.ok) throw new Error(r.error.message);
const i = n.canonicalKey ?? e.key;
const [a] = await readAcpSessionMetaForEntries({
cfg: t,
entries: [{
agentId: n.agentId,
sessionKey: i,
entry: r.entry
}]
});
const o = projectSessionPatchResult({
canonicalKey: i,
cfg: t,
entry: r.entry,
preparedAcpMeta: a ?? null,
storePath: n.storePath,
targetAgentId: n.agentId
});
return {
...o,
entry: { ...o.entry }
};
}
async resetSession(e, t, n) {
await this.ready;
if ((await loadGatewaySessionEntryReadOnlyInWorker({
cfg: readRuntimeConfig(),
key: e,
...n
})).entry?.incognito === true) throw new Error("Incognito sessions cannot reset in place.");
const r = await performGatewaySessionReset({
key: e,
operatorRoleActor: { kind: "system" },
...n?.agentId ? { agentId: n.agentId } : {},
reason: t === "new" ? "new" : "reset",
commandSource: "tui:embedded",
armSessionDiffBaselineCapture: true
});
if (!r.ok) throw new Error(r.error.message);
if ("incognitoDeleted" in r) return {
ok: true,
key: r.key,
deleted: true
};
return {
ok: true,
key: r.key,
entry: r.entry,
resolved: r.resolved
};
}
async createSession(e) {
await this.ready;
await this.preparedModelRuntime.waitUntilReady();
const t = readRuntimeConfig();
const n = await createGatewaySession({
cfg: t,
operatorRoleActor: { kind: "system" },
...e,
creation: {
via: "operator",
actor: {
type: "human",
source: "unknown"
}
},
armSessionDiffBaselineCapture: true,
emitCommandHooks: Boolean(e.parentSessionKey),
commandSource: "tui:embedded",
loadGatewayModelCatalogSnapshot: () => loadPreparedModelCatalogSnapshot({
config: t,
agentId: resolveSessionAgentId({
sessionKey: e.key,
config: t,
agentId: e.agentId
}),
readOnly: true
})
});
if (!n.ok) throw new Error(n.error.message);
return {
ok: true,
key: n.key,
entry: n.entry,
resolved: n.resolved
};
}
async runBtwTurn(e) {
const t = e.agentId ? { agentId: e.agentId } : void 0;
const { cfg: n, agentId: r, canonicalKey: i, storePath: a, store: o, entry: s } = await loadGatewaySessionEntryReadOnlyInWorker({
cfg: readRuntimeConfig(),
key: e.sessionKey,
...t
});
if (!s?.sessionId) throw new Error("/btw requires an active session with existing context.");
const c = resolveSessionModelRef(n, s, r);
const l = timeoutSecondsFromMs(e.timeoutMs);
const { runBtwSideQuestion: u } = await import("./btw-VjipFRnZ.mjs");
const d = await u({
cfg: n,
agentId: r,
agentDir: resolveAgentDir(n, r),
provider: c.provider,
model: c.model,
question: e.question,
sessionEntry: s,
sessionStore: o,
sessionKey: i,
storePath: a,
resolvedThinkLevel: "off",
resolvedReasoningLevel: "off",
opts: {
runId: e.runId,
abortSignal: e.controller.signal,
...l !== void 0 ? { timeoutOverrideSeconds: Number(l) } : {}
},
isNewSession: false,
messageChannel: INTERNAL_MESSAGE_CHANNEL,
messageProvider: INTERNAL_MESSAGE_CHANNEL,
currentChannelId: INTERNAL_MESSAGE_CHANNEL,
senderId: this.localSenderId
});
const f = d?.text?.trim() ?? "";
if (!f) throw new Error("/btw produced no answer.");
return {
sessionKey: i,
text: f,
isError: d?.isError === true
};
}
async getGatewayStatus() {
return `local embedded mode${this.runs.size > 0 ? ` (${String(this.runs.size)} active run${this.runs.size === 1 ? "" : "s"})` : ""}`;
}
async listPluginApprovals() {
return this.pluginApprovalBroker.listPending();
}
async listQuestions() {
return this.questionBroker.list();
}
async getQuestion(e) {
return this.questionBroker.get({ id: e });
}
async resolveQuestion(e) {
return this.questionBroker.resolve(e);
}
async resolvePluginApproval(e, t) {
return { ok: this.pluginApprovalBroker.resolve(e, t) };
}
async listModels(e) {
await this.ready;
await this.preparedModelRuntime.waitUntilReady();
const t = readRuntimeConfig();
const n = e?.agentId ?? resolveDefaultAgentId(t);
return await withPreparedModelCatalogOwner({
config: t,
agentId: n,
readOnly: true
}, async (e) => (await buildModelsListResult({
source: {
kind: "published",
owner: {
...resolvePublishedModelCatalogOwner(e),
authMaterializations: getPreparedModelRuntimeAuthMaterializations(e)
}
},
agentId: n,
params: { includeDetails: true }
})).models);
}
async runGoalCommand(e) {
await this.ready;
const t = e.agentId ? { agentId: e.agentId } : void 0;
const { agentId: n, canonicalKey: r, storePath: i, entry: a } = await loadGatewaySessionEntryReadOnlyInWorker({
cfg: readRuntimeConfig(),
key: e.sessionKey,
...t
});
const o = parseGoalCommand(e.command.trim());
if (!o) throw new Error("invalid goal command");
const s = await executeSessionGoalCommand({
parsed: o,
sessionKey: r,
storePath: i,
fallbackEntry: a ?? {
sessionId: randomUUID(),
updatedAt: Date.now()
},
agentId: n
});
return s.continuationPrompt ? {
text: s.text,
continuationPrompt: s.continuationPrompt
} : { text: s.text };
}
async runUsageCostCommand(e) {
await this.ready;
const { cfg: t, agentId: n, canonicalKey: r, storePath: i, entry: a } = await loadGatewaySessionEntryReadOnlyInWorker({
cfg: readRuntimeConfig(),
key: e.sessionKey,
...e.agentId ? { agentId: e.agentId } : {}
});
const { formatSessionUsageCostSummary: o } = await import("./commands-session-cost.runtime.js");
return { text: await o({
cfg: t,
sessionKey: r,
agentId: n,
sessionEntry: a,
storePath: i
}) };
}
abortSessionRuns(e) {
for (const t of this.runs.values()) if (isSameLocalRunScope(t, e) && !t.question && this.isAbortableRun(t)) t.controller.abort();
}
isAbortableRun(e) {
return !e.lifecycleEnded || e.promise !== void 0;
}
emit(e, t) {
this.onEvent?.({
event: e,
payload: t,
seq: ++this.seq
});
}
emitRun(e, t, n, r) {
this.emit(e, {
runId: t,
sessionKey: n.sessionKey,
agentId: n.agentId,
...r
});
}
clearPendingLifecycleError(e) {
clearTimeout(this.pendingLifecycleErrors.get(e));
this.pendingLifecycleErrors.delete(e);
}
scheduleChatError(e, t, n) {
this.clearPendingLifecycleError(e);
const r = setTimeout(() => {
this.pendingLifecycleErrors.delete(e);
this.emitChatTerminal(e, t, "error", n, "provisional");
}, AGENT_RUN_TERMINAL_RETRY_GRACE_MS);
r.unref?.();
this.pendingLifecycleErrors.set(e, r);
}
emitChatDelta(e, t) {
const n = projectLocalRunText(t);
const r = n.text.trim();
if (t.buffer && (!r || n.suppress)) return;
const i = resolveDeltaPayload(r, t.lastBroadcastText);
if (!i.deltaText && !i.replace) return;
t.registered = true;
t.lastBroadcastText = r;
this.emitRun("chat", e, t, {
state: "delta",
...i,
message: assistantChatMessage(r)
});
}
flushChatDelta(e, t) {
if (t.textUpdates?.takePending()) this.emitChatDelta(e, t);
}
emitChatTerminal(e, t, n, r, i = "final") {
this.clearPendingLifecycleError(e);
if (t.terminalState === "final" || t.terminalState === i) return;
this.flushChatDelta(e, t);
t.textUpdates?.stop();
t.terminalState = i;
if (i === "final") {
t.markQueuedRunReady();
t.finishing = false;
t.lifecycleEnded = true;
}
t.registered = true;
t.lastBroadcastText = void 0;
const a = projectLocalRunText(t, true);
const o = n === "final" && !a.suppress ? a.text.trim() : "";
this.emitRun("chat", e, t, {
state: n,
...n === "aborted" && t.localModelMayStillBeFinishing ? { localModelMayStillBeFinishing: true } : {},
...n === "final" && r ? { stopReason: r } : {},
...n === "final" && t.lifecycleYielded ? { yielded: true } : {},
...o ? { message: assistantChatMessage(o) } : {},
...n !== "final" && (r || n === "aborted" && t.toolErrorSummary) ? { errorMessage: formatTuiErrorMessage(r ?? t.toolErrorSummary) } : {}
});
}
projectTerminalOutcome(e, t, n, r = {}) {
const i = n.error && typeof n.error === "object" && "message" in n.error ? n.error.message : n.error;
const a = r.terminalOutcome ?? buildAgentRunTerminalOutcomeFromLifecycleEvent({
phase: n.phase === "error" || i ? "error" : "end",
data: {
...n,
error: i ? formatTuiErrorMessage(i) : void 0
},
abortSignal: t.controller.signal
});
const o = resolveTerminalChatState(a);
if (!o) return false;
const s = o === "aborted" ? readToolValidationErrorSummary(n.toolErrorSummary) : a.reason === "failed" && r.visibleText || a.error || (a.status === "timeout" ? "The provider timed out. Please try again." : "Agent run failed.");
if (n.phase === "error" && !isDefinitiveRunLifecycle({
phase: "error",
data: n
})) this.scheduleChatError(e, t, s);
else this.emitChatTerminal(e, t, o, s);
return true;
}
ensureRunRegistered(e, t) {
if (t.registered || t.question) return;
t.registered = true;
t.lastBroadcastText = "";
this.emitRun("chat", e, t, {
state: "delta",
deltaText: "",
message: assistantChatMessage("")
});
}
handleAgentEvent(e) {
const t = this.runs.get(e.runId);
if (!t) return;
const n = e.stream === "lifecycle" && typeof e.data?.phase === "string" ? e.data.phase : "";
if (e.stream !== "lifecycle" || n !== "error") this.clearPendingLifecycleError(e.runId);
if (e.stream !== "assistant") {
this.flushChatDelta(e.runId, t);
this.ensureRunRegistered(e.runId, t);
}
const r = t.explicitFollowup && n === "start";
if (r) delete t.explicitFollowup;
this.emitRun("agent", e.runId, t, {
stream: e.stream,
data: r ? {
...e.data,
explicitFollowup: true
} : e.data
});
if (e.stream === "assistant" || e.stream === "tool" && e.data?.phase === "start") t.toolErrorSummary = void 0;
else if (e.stream === "tool" && e.data?.phase === "result") t.toolErrorSummary = readToolValidationErrorSummary(e.data.toolErrorSummary);
const i = e.assistantProjection ? resolveAssistantTextInput({
...e.assistantProjection,
managedMediaUrls: e.data.managedMediaUrls
}) : e.stream === "assistant" ? resolveAssistantTextInput(e.data) : void 0;
if (i && !t.question && !shouldSuppressAssistantEventForLiveChat(e.data)) {
if (i.text !== void 0 || i.itemId !== t.assistantScope?.itemId) this.flushChatDelta(e.runId, t);
for (const e of i.managedMediaUrls ?? []) t.managedMediaUrls.add(e);
const n = mergeAssistantText({
text: t.buffer,
scope: t.assistantScope
}, i, "live");
t.assistantScope = n.scope;
t.buffer = capLiveAssistantText(n);
if ((n.appendedText !== void 0 || t.lastBroadcastText === void 0) && !i.replace) {
t.textUpdates ??= createDraftStreamLoop({
throttleMs: 75,
coalesceInFlight: true,
emptyValue: false,
isEmpty: (e) => !e,
isStopped: () => this.scheduler.signal.aborted || t.terminalState === "final",
sendOrEditStreamMessage: async () => this.emitChatDelta(e.runId, t)
});
t.textUpdates.update(true);
} else this.emitChatDelta(e.runId, t);
return;
}
if (e.stream !== "lifecycle") return;
const a = n;
if (a === "finishing") {
t.finishing = true;
t.markQueuedRunReady();
t.lifecycleStopReason = typeof e.data?.stopReason === "string" ? e.data.stopReason : void 0;
return;
}
if (a !== "end" && a !== "error") return;
t.finishing = false;
if (a === "error") {
t.buffer = "";
delete t.assistantScope;
}
if (this.projectTerminalOutcome(e.runId, t, e.data)) return;
t.lifecycleEnded = true;
t.markQueuedRunReady();
t.lifecycleStopReason = typeof e.data?.stopReason === "string" ? e.data.stopReason : void 0;
t.lifecycleYielded = isAgentLifecycleYieldedWaiting(e.data);
}
async runTurn(e, t, n) {
const { controller: r, queuedAfter: i } = t;
try {
if (i) {
try {
await Promise.race([waitForQueuedLocalRun(i, e), waitForAbortSignal(r.signal)]);
} catch (n) {
const r = n instanceof Error ? n.message : String(n);
this.emitChatTerminal(e, t, "error", `previous run did not finish cleanly: ${r}`);
return;
}
if (r.signal.aborted) {
this.emitChatTerminal(e, t, "aborted");
return;
}
}
delete t.queuedAfter;
let a = n.message;
if (t.pendingQueue) {
await waitForQueueDebounce(t.pendingQueue, r.signal);
if (r.signal.aborted) {
this.emitChatTerminal(e, t, "aborted");
return;
}
a = buildLocalQueuedPrompt(t.pendingQueue);
delete t.pendingQueue;
}
if (i) {
await this.preparedModelRuntime.waitUntilReady();
if (r.signal.aborted) {
this.emitChatTerminal(e, t, "aborted");
return;
}
}
if (t.question) {
const i = await this.runBtwTurn({
runId: e,
sessionKey: n.sessionKey,
...n.agentId ? { agentId: n.agentId } : {},
question: t.question,
timeoutMs: n.timeoutMs,
controller: r
});
if (r.signal.aborted) {
this.emitChatTerminal(e, t, "aborted");
return;
}
this.emit("chat.side_result", {
kind: "btw",
runId: e,
sessionKey: i.sessionKey,
agentId: t.agentId,
question: t.question,
text: i.text,
...i.isError ? { isError: true } : {}
});
this.emitChatTerminal(e, t, "final");
return;
}
const o = n.agentId ? { agentId: n.agentId } : void 0;
const { agentId: s, canonicalKey: c, entry: l } = await loadGatewaySessionEntryReadOnlyInWorker({
cfg: readRuntimeConfig(),
key: n.sessionKey,
...o
});
const u = await agentCommandFromIngress({
message: a,
sessionKey: c,
agentId: s,
...l?.sessionId ? { sessionId: l.sessionId } : {},
thinking: n.thinking,
deliver: n.deliver,
channel: INTERNAL_MESSAGE_CHANNEL,
runContext: {
messageChannel: INTERNAL_MESSAGE_CHANNEL,
senderId: this.localSenderId
},
timeout: timeoutSecondsFromMs(n.timeoutMs),
runId: e,
abortSignal: r.signal,
allowModelOverride: false
}, silentRuntime, this.deps);
if (this.projectTerminalOutcome(e, t, u?.meta ?? {}, { visibleText: payloadText(u?.payloads) })) return;
t.lifecycleYielded ||= isAgentLifecycleYieldedWaiting({
phase: "end",
...u?.meta
});
if (t.terminalState !== "final") {
const n = payloadText(u?.payloads);
if (n) t.buffer = n;
const r = t.lifecycleStopReason ?? (typeof u?.meta?.stopReason === "string" ? u.meta.stopReason : void 0);
this.emitChatTerminal(e, t, "final", r);
}
} catch (n) {
const r = n instanceof Error ? n.message : String(n);
const i = findAgentRunTerminalOutcome(n);
this.projectTerminalOutcome(e, t, i ?? {
status: "error",
error: r
}, i ? { terminalOutcome: i } : {});
} finally {
t.textUpdates?.stop();
t.markQueuedRunReady();
this.runs.delete(e);
}
}
};
//#endregion
export { EmbeddedTuiBackend };