UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

930 lines (929 loc) • 37.7 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { D as parseStrictPositiveInteger } from "./number-coercion-D6u-4YD8.mjs"; import { o as isFastTestRuntimeEnv } from "./env-HehwidXj.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import "./utils-C8YECn2Q.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { C as resolveSessionAgentIds } from "./agent-scope-config-DmXgFGKP.mjs"; import { s as emitTrustedDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs"; import { h as createChildDiagnosticTraceContext, s as measureDiagnosticsTimelineSpan, u as observeDiagnosticsTimelinePhases, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { d as runWithSessionSourceScope, f as sessionEntryCommitGuardOptions, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { g as resolveAdmittedRunActiveAssertion } from "./admitted-run-context-D3Jvk_f_.mjs"; import "./tool-policy-BR4v75RA.mjs"; import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs"; import { d as readSessionEntryInWorker, i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { r as isOpenClawSystemUpdateMessage } from "./operator-messages-B9HgXnnQ.mjs"; import "./internal-runtime-context-BEUlDNuI.mjs"; import { l as isTranscriptOnlyOpenClawAssistantMessage } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs"; import { l as resolveQuotaSuspensionEntryMaintenance } from "./store-maintenance-Ba-_6wiR.mjs"; import { f as hasSessionTranscriptMessage } from "./session-accessor-CizTbDQj.mjs"; import { r as SessionWorkStartInvalidatedError } from "./work-start-error-DaHE71YG.mjs"; import { i as patchSessionEntryCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs"; import { a as resolveSessionTranscriptRuntimeTarget } from "./session-accessor.transcript-target-njOktg4F.mjs"; import { s as withSandboxRuntimeStatusInWorker } from "./runtime-status-C5ZOG7YR.mjs"; import { i as captureWorktreeRunEndContext } from "./run-end-lifecycle-CvtGWdnp.mjs"; import { d as readRegistryWorktree } from "./registry-read-DAFI5cQY.mjs"; import { c as recordRegistryWorktreeActivity } from "./registry-C6O4gwRx.mjs"; import { r as logDecisionToolPrefilter } from "./diagnostics-BSitDHjX.mjs"; import { n as resolveEffectiveToolFsWorkspaceOnly } from "./tool-fs-policy-dDd9W7xo.mjs"; import { n as recordAgentCleanupFailure, r as runAgentCleanupStep } from "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import { n as assertMemoryAudienceSession, t as assertMemoryAudienceCurrent } from "./memory-audience-RRQiHS6M.mjs"; import { s as runWithAgentToolSourceExecutionScope } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs"; import { n as formatStageTimings } from "./stage-timing-By2RFvzf.mjs"; import { t as log } from "./logger-DgCpB-Fs.mjs"; import { r as getToolDefinitionSource } from "./agent-tool-definition-adapter-CAIOgFtX.mjs"; import { n as agentSessionQueuePromptContext, y as sanitizeCompactionReplayMessages } from "./agent-session-prompting-DwE3NoeR.mjs"; import { i as withSessionManagerWrite } from "./session-manager-write-admission-CUQ2naL2.mjs"; import { n as attachPromptCompactionRequestBudget } from "./request-budget-CDN2iAaH.mjs"; import { b as updateActiveEmbeddedRunSnapshot } from "./runs-C1RO1Y6L.mjs"; import { n as buildAgentHookContextIdentityFields, t as buildAgentHookContextChannelFields } from "./hook-agent-context-sUFGgK45.mjs"; import { a as declarePromptHistoryRewrite, s as recordAggregateTruncation } from "./prompt-cache-observability-BBkCY6BX.mjs"; import { r as buildUsageWithNoCost } from "./stream-message-shared-CBUzFwdv.mjs"; import { n as toTrajectoryToolDefinitions } from "./runtime-Bsp-rPbR.mjs"; import { r as prepareSessionPlacementSandbox } from "./session-placement-admission-CBCEtade.mjs"; import { l as truncateOversizedToolResultsInMessages } from "./tool-result-truncation-CpAX82MP.mjs"; import { i as isMidTurnPrecheckSignal, r as isMidTurnPrecheckAssistantError } from "./midturn-precheck-DByie_kO.mjs"; import { t as createAgentHarnessPromptToolPolicy } from "./prompt-tool-policy-C3u9Ea5g.mjs"; import { t as buildSessionsYieldContextMessage } from "./sessions-yield-context-D0_KqS8B.mjs"; import { n as installModelPromptProjection, r as installRuntimeContextMessageForPrompt, s as resolveModelPromptText, t as wrapStreamFnWithMessageTransform } from "./message-transform-stream-wrapper-B--6dKUi.mjs"; import "./session-tool-result-guard-wrapper-z-jVIqGv.mjs"; import fs from "node:fs/promises"; import { isMainThread, threadId } from "node:worker_threads"; //#region src/agents/embedded-agent-runner/run/agent-hook-context.ts function buildEmbeddedAgentHookContext(e, t, n) { if (e.memoryAudience) assertMemoryAudienceSession(e.memoryAudience, e.sessionKey); return { runId: e.runId, jobId: e.jobId, trace: n, agentId: t, sessionKey: e.sessionKey, sessionId: e.sessionId, memoryAudience: e.memoryAudience, assertMemoryAudienceCurrent: e.memoryAudience ? () => assertMemoryAudienceCurrent(e.memoryAudience) : void 0, sandboxed: e.sandbox?.enabled === true, workspaceDir: e.workspaceDir, trigger: e.trigger, ...buildAgentHookContextChannelFields(e), ...buildAgentHookContextIdentityFields(e) }; } //#endregion //#region src/agents/embedded-agent-runner/abort.ts function isRunnerAbortError(e) { if (!e || typeof e !== "object") return false; if (("name" in e ? String(e.name) : "") === "AbortError") return true; return ("message" in e && typeof e.message === "string" ? normalizeLowercaseStringOrEmpty(e.message) : "").includes("aborted"); } //#endregion //#region src/agents/embedded-agent-runner/run/transcript-tail-metadata.ts const preserveTrailingTranscriptMetadata = (e) => e.type === "custom" || e.type === "label" || e.type === "session_info" || e.type === "message" && isTranscriptOnlyOpenClawAssistantMessage(e.message); //#endregion //#region src/agents/embedded-agent-runner/run/attempt-sessions-yield.ts const SESSIONS_YIELD_INTERRUPT_CUSTOM_TYPE = "openclaw.sessions_yield_interrupt"; function createYieldAbortedResponse(e) { const t = { role: "assistant", content: [{ type: "text", text: "" }], stopReason: "aborted", api: e.api ?? "", provider: e.provider ?? "", model: e.id ?? "", usage: buildUsageWithNoCost({}), timestamp: Date.now() }; return { async *[Symbol.asyncIterator]() {}, result: async () => t }; } const SESSIONS_YIELD_ABORT_REASON = { code: "sessions_yield", turnHandoff: true }; function isSessionsYieldAbortError(e) { return isRunnerAbortError(e) && e instanceof Error && isSessionsYieldAbortReason(e.cause); } function isSessionsYieldAbortReason(e) { return typeof e === "object" && e !== null && e.code === "sessions_yield"; } function queueSessionsYieldInterruptMessage(e) { e.agent.steer({ role: "custom", customType: SESSIONS_YIELD_INTERRUPT_CUSTOM_TYPE, content: "[sessions_yield interrupt]", display: false, details: { source: "sessions_yield" }, timestamp: Date.now() }); } async function stripSessionsYieldArtifacts(e) { const t = e.messages.slice(); t.length = t.findLastIndex((e) => e?.role !== "assistant" && !(e?.role === "custom" && e.customType === SESSIONS_YIELD_INTERRUPT_CUSTOM_TYPE)) + 1; const n = e.messages.slice(t.length); if (n.length === 0) return false; let r = n.filter((e) => e.role === "assistant").length; const i = await e.sessionManager.removeTrailingEntriesAsync((e) => { if (e.type === "custom_message" && e.customType === SESSIONS_YIELD_INTERRUPT_CUSTOM_TYPE) return true; if (e.type !== "message" || e.message.role !== "assistant" || r === 0) return false; r -= 1; return true; }, { preserveTrailing: preserveTrailingTranscriptMetadata }); e.agent.state.messages = t; return i > 0; } //#endregion //#region src/agents/embedded-agent-runner/run/compaction-timeout.ts /** Flags only run-timeout events that overlap pending, retrying, or active compaction work. */ function shouldFlagCompactionTimeout(e) { return e.isTimeout && (e.isCompactionPendingOrRetrying || e.isCompactionInFlight); } /** * Grants a single timeout grace window when compaction is still responsible for * the delay. A second timeout, or a timeout unrelated to compaction, aborts the * run instead of extending indefinitely. */ function resolveRunTimeoutDuringCompaction(e) { if (!e.isCompactionPendingOrRetrying && !e.isCompactionInFlight) return "abort"; return e.graceAlreadyUsed ? "abort" : "extend"; } const CONTINUABLE_MESSAGE_ROLES = /* @__PURE__ */ new Set([ "user", "toolResult", "branchSummary", "compactionSummary", "custom", "bashExecution" ]); function canContinueFromMessage(e) { if (!e || "excludeFromContext" in e && e.excludeFromContext === true) return false; return CONTINUABLE_MESSAGE_ROLES.has(e.role); } function trimToContinuableTail(e) { const t = e.findLastIndex(canContinueFromMessage) + 1; return t > 0 ? e.slice(0, t) : null; } /** * Selects the transcript snapshot used after a compaction timeout. Prefer the * pre-compaction view when it can be continued cleanly; otherwise fall back to a * trimmed current snapshot so retry does not replay past an unsafe tail. */ function selectCompactionTimeoutSnapshot(e) { if (e.timedOutDuringCompaction && e.preCompactionSnapshot) { const t = trimToContinuableTail(e.preCompactionSnapshot); if (t) return { messagesSnapshot: t, sessionIdUsed: e.preCompactionSessionId, source: "pre-compaction" }; } return { messagesSnapshot: e.timedOutDuringCompaction ? trimToContinuableTail(e.currentSnapshot) ?? [] : e.currentSnapshot, sessionIdUsed: e.currentSessionId, source: "current" }; } //#endregion //#region src/agents/embedded-agent-runner/run/preparation-timing.ts /** Measures async pre-provider work under the canonical agent preparation span. */ function measureEmbeddedAgentPreparation(e, t, n = {}) { return measureDiagnosticsTimelineSpan("agent.prepare", t, { config: n.config, phase: "agent.prepare", attributes: { stage: e } }); } //#endregion //#region src/agents/workspace-sandbox.ts function assertSandboxCwd(e, t) { if (e && e !== t) throw new Error("cwd override is not supported for sandboxed embedded agent runs; omit cwd or use the agent workspace as cwd"); } /** Preserve prepared local projection roots without overriding a remote placement owner. */ function resolveHarnessWorkspace(e, t, n, r) { const i = n?.sandbox?.workspaceSource === "managed-worktree" && n.sandbox === r; if (i) assertSandboxCwd(t.cwd ? resolveUserPath(t.cwd) : void 0, n.resolvedWorkspace); return { workspaceDir: i ? n.effectiveWorkspace : e, cwd: i ? n.effectiveCwd : t.cwd, sessionRoot: i ? n.sessionPermissionRoot : t.sessionRoot }; } /** Retains placement custody across local workspace preparation and harness dispatch. */ async function preparePluginHarnessWorkspace(e) { const t = await prepareSessionPlacementSandbox(e); try { t.assertCurrent(); const n = await resolveAttemptWorkspaceSandbox({ ...e, placementSandbox: t.sandbox }); try { t.assertCurrent(); return { ...t, workspace: n, [Symbol.dispose]: () => { n[Symbol.dispose](); t[Symbol.dispose](); } }; } catch (e) { n[Symbol.dispose](); throw e; } } catch (e) { t[Symbol.dispose](); throw e; } } /** Resolves the shared workspace and sandbox policy used by native and plugin harnesses. */ async function resolveAttemptWorkspaceSandbox(e) { try { var t = _usingCtx(); const n = t.u(observeDiagnosticsTimelinePhases("attempt.setup.workspace.policy")); const r = e.admittedRunContext ? resolveAdmittedRunActiveAssertion(e.admittedRunContext, e.abortSignal) : void 0; if (e.admittedRunContext && !r) throw new Error("Sandbox preparation requires an active admitted run"); const i = composeSessionSourceAssertion([r], (t) => { e.abortSignal?.throwIfAborted(); t(); }); i(); const { sessionAgentId: a } = resolveSessionAgentIds({ sessionKey: e.sessionKey, config: e.config, agentId: e.agentId }); const o = resolveUserPath(e.workspaceDir); const s = e.sessionKey?.trim() || e.sessionId; const c = e.sandboxSessionKey?.trim() || s; if (e.sessionKey?.trim()) { const t = await readSessionEntryReadOnlyInWorker({ agentId: a, sessionKey: s, storePath: resolveSessionStorePathCore(e.config?.session?.store, { agentId: a }) }, i); if (t?.archivedAt === void 0 && t?.worktree) { const e = captureWorktreeRunEndContext(process.env); const n = await readRegistryWorktree(e, t.worktree.id); i(); if (n?.removedAt !== void 0) throw new SessionWorkStartInvalidatedError(`This session's worktree was removed by cleanup or deletion. Use Restore in Settings > Worktrees (worktrees.restore), or start a new session. Worktree: ${t.worktree.id}.`); if (n) await recordRegistryWorktreeActivity(e.environment, n, i); } } const prepareWorkspace = async (t) => runWithAgentToolSourceExecutionScope(i, async () => { i(); if (t?.sandboxed) { n.mark("attempt.setup.workspace.baseline_wait"); await e.awaitSessionDiffBaseline?.(); i(); } n.mark("attempt.setup.workspace.mkdir"); await fs.mkdir(o, { recursive: true }); i(); n.mark("attempt.setup.workspace.sandbox"); const r = t?.sandboxed ? await import("./context-D8no3ydn.mjs") : void 0; i(); const s = r && t ? await r.resolveSandboxContext({ config: e.config, agentId: t.agentId, execOverrides: e.execOverrides, sessionKey: c, skillsSnapshot: e.skillsSnapshot, workspaceDir: o, assertCurrent: i, admittedRunContext: e.admittedRunContext, preparedRuntimeStatus: t }) : null; try { n.mark("attempt.setup.workspace.roots"); i(); const r = s?.enabled && s.workspaceSource === "managed-worktree"; const l = s?.enabled && (s.workspaceAccess !== "rw" || r) ? s.workspaceCwd ?? s.workspaceDir : o; const u = e.cwd ? resolveUserPath(e.cwd) : void 0; const d = r ? s.workspaceDir : e.sessionRoot ?? await fs.realpath(o); const f = e.permissionMode ? { root: d, mode: e.permissionMode } : void 0; if (s?.enabled) assertSandboxCwd(u, o); i(); if (l !== o) await fs.mkdir(l, { recursive: true }); i(); n.mark("attempt.setup.workspace.policy_finalize"); return { effectiveCwd: s?.enabled ? l : u ?? l, effectiveFsWorkspaceOnly: e.requireWorkspaceOnly === true || resolveEffectiveToolFsWorkspaceOnly({ cfg: e.config, agentId: a }), effectiveWorkspace: l, resolvedWorkspace: o, sessionPermissionRoot: d, sessionPermissionPolicy: f, sandbox: s, ...t ? { sandboxRuntime: t } : {}, sandboxReport: t ? { mode: t.mode, sandboxed: t.sandboxed } : void 0, sandboxSessionKey: c, sessionAgentId: a, [Symbol.dispose]: () => s?.[Symbol.dispose]?.() }; } catch (e) { s?.[Symbol.dispose]?.(); throw e; } }); return await (e.placementSandbox ? prepareWorkspace() : withSandboxRuntimeStatusInWorker({ cfg: e.config, agentId: e.sandboxAgentId ?? (c === s ? a : void 0), sessionKey: c }, { env: process.env, cwd: process.cwd(), assertCurrent: i }, prepareWorkspace)); } catch (e) { t.e = e; } finally { t.d(); } } //#endregion //#region src/agents/embedded-agent-runner/run/attempt-context-summary.ts function summarizeSessionContext(e) { const t = /* @__PURE__ */ new Map(); let n = 0; let r = 0; let i = 0; for (const a of e) { const e = a.role; t.set(e, (t.get(e) ?? 0) + 1); const o = a.content; let s = typeof o === "string" ? o.length : 0; if (Array.isArray(o)) for (const e of o) { if (!e || typeof e !== "object") continue; const t = e; if (t.type === "image") r++; else if (typeof t.text === "string") s += t.text.length; } n += s; i = Math.max(i, s); } return { roleCounts: [...t.entries()].sort((e, t) => e[0].localeCompare(t[0])).map(([e, t]) => `${e}:${t}`).join(",") || "none", totalTextChars: n, totalImageBlocks: r, maxMessageTextChars: i }; } function snapshotRecentMessages(e) { return e.slice(-100); } //#endregion //#region src/agents/embedded-agent-runner/run/attempt-subscription-cleanup.ts const EMBEDDED_ABORT_SETTLE_TIMEOUT_MS = parseStrictPositiveInteger(process.env.OPENCLAW_EMBEDDED_ABORT_SETTLE_TIMEOUT_MS) ?? (isFastTestRuntimeEnv() ? 250 : 2e3); async function waitForEmbeddedAbortSettle(e) { if (!e.promise) return; await runAgentCleanupStep({ runId: e.runId, sessionId: e.sessionId, step: `${e.reason ?? "embedded"}-abort-settle`, log, timeoutMs: EMBEDDED_ABORT_SETTLE_TIMEOUT_MS, cleanup: async () => { await e.promise; } }); } /** * Tears down per-attempt resources after the transcript lifecycle has drained: * remove guards, settle aborted prompts, join cleanup writes, then dispose runtimes. */ async function cleanupEmbeddedAttemptResources(e) { try { e.removeToolResultContextGuard?.(); } catch { recordAgentCleanupFailure(); } if (e.aborted && e.abortSettlePromise) await waitForEmbeddedAbortSettle({ promise: e.abortSettlePromise, runId: e.runId ?? "unknown", sessionId: e.sessionId ?? "unknown" }); try { await e.flushPendingToolResultsAfterIdle({ agent: e.session?.agent, sessionManager: e.sessionManager, ...e.aborted ? { timeoutMs: 0 } : {}, ...e.abortSignal ? { abortSignal: e.abortSignal } : {} }); } catch { recordAgentCleanupFailure(); } try { e.session?.dispose(); } catch { recordAgentCleanupFailure(); } for (const t of ["bundleMcpRuntime", "bundleLspRuntime"]) try { await e[t]?.dispose(); } catch { recordAgentCleanupFailure(); } } //#endregion //#region src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts async function submitEmbeddedAttemptPrompt(e) { const { activeSession: t, attempt: n } = e; if (n.inputAlreadyDelivered) { n.abortSignal?.throwIfAborted(); e.assertHostActive?.(); return; } const r = n.userTurnTranscriptRecorder; const i = n.skipPreparedUserTurnMessage || e.runtimeOnly || r?.isBlocked() ? void 0 : r; const a = n.skipPreparedUserTurnMessage !== true && r?.hasPersisted() === true ? (r.getPersistedMessage?.() ?? r.message)?.idempotencyKey : void 0; const installProviderPromptHistoryTransform = () => { const a = t.agent.streamFn; const o = t.agent.prepareNextTurnWithContext; const s = []; const prepareNextTurn = async (e, n) => { const r = o ? await o.call(t.agent, e, n) : await t.agent.prepareNextTurn?.(n); if (s.length === 0) return r; const i = s.splice(0); const a = r?.context ?? e.context; const c = a.messages.indexOf(e.message); if (c < 0) return r; const l = e.newMessages.indexOf(e.message); if (l >= 0) e.newMessages.splice(l, 0, ...i.filter((t) => !e.newMessages.includes(t))); const u = i.filter((e) => !a.messages.includes(e)); return { ...r, context: { ...a, messages: [ ...a.messages.slice(0, c), ...u, ...a.messages.slice(c) ] } }; }; t.agent.prepareNextTurnWithContext = prepareNextTurn; const persistThenStream = async (n, o, l) => runWithSessionSourceScope(e.assertHostActive, async () => { const assertRequestCurrent = () => { l?.signal?.throwIfAborted(); (e.assertHostActive?.assertScopeCurrent ?? e.assertHostActive)?.(); }; await r?.waitForRuntimePersistence(); assertRequestCurrent(); await e.persistToolResultProjections(); assertRequestCurrent(); let u = o; const d = c && !t.isCompacting; const f = d ? await e.onModelRequest?.(n, u, l?.signal) : void 0; assertRequestCurrent(); if (d && e.compactBeforeRequest) { const t = await e.compactBeforeRequest(async (t, n, r) => { await e.onModelRequest?.(t, n, r?.signal); assertRequestCurrent(); return a(t, n, r); }, n, u, l, f); assertRequestCurrent(); if (t) { s.push(t); u = { ...u, messages: [...u.messages, t] }; await e.onModelRequest?.(n, u, l?.signal); } } assertRequestCurrent(); e.assertHostActive?.(); if (d) i?.markSentToProvider?.(); return await a(n, u, l); }, { checkAfter: false }); const l = wrapStreamFnWithMessageTransform(persistThenStream, (t, r) => { const i = truncateOversizedToolResultsInMessages(t, e.contextTokenBudget, e.toolResultMaxChars, e.toolResultAggregateMaxChars, e.toolResultPromptProjectionState); const a = i.messages; if (i.truncatedCount > 0) declarePromptHistoryRewrite({ ...n, reason: "pruning" }); if (i.aggregateTruncatedCount > 0) recordAggregateTruncation(n); return e.normalizeToolCallIds?.(a, r) ?? a; }); t.agent.streamFn = l; return () => { if (t.agent.prepareNextTurnWithContext === prepareNextTurn) t.agent.prepareNextTurnWithContext = o; if (t.agent.streamFn === l) t.agent.streamFn = a; }; }; e.onFinalPromptText(e.transcriptPrompt); e.trajectoryRecorder?.recordEvent("prompt.submitted", { prompt: e.modelPrompt, systemPrompt: e.systemPrompt, messages: t.messages, imagesCount: e.images.length }); updateActiveEmbeddedRunSnapshot(e.registration, { transcriptLeafId: e.transcriptLeafId, messages: snapshotRecentMessages(t.messages), inFlightPrompt: e.transcriptPrompt }); const o = n.skipPreparedUserTurnMessage === true || n.suppressNextUserMessagePersistence === true && r === void 0; const s = o ? resolveModelPromptText({ ...e, text: e.transcriptPrompt }) : e.transcriptPrompt; let c = false; const l = o ? () => {} : installModelPromptProjection({ session: t, carrier: e.appendOnlyRuntimeContext ? e.runtimeContextMessage : void 0, transcriptPrompt: e.transcriptPrompt, modelPrompt: e.modelPrompt, prependContext: e.prependContext, appendContext: e.appendContext, shouldCapturePrompt: () => c, recorder: i, withTranscriptWrite: e.withTranscriptWrite, getUserTranscriptContexts: e.getUserTranscriptContexts, assertCurrent: e.assertHostActive }); const armModelPromptTransform = (e) => { c ||= e; }; const u = { ...!e.runtimeOnly && e.images.length > 0 ? { images: e.images } : {}, ...a ? { persistedUserIdempotencyKey: a } : {}, preflightResult: armModelPromptTransform }; attachPromptCompactionRequestBudget(u, e.compactionRequestBudget); const d = installProviderPromptHistoryTransform(); const f = e.runtimeOnly || o; if (f) e.setNextUserMessagePersistence?.("runtime"); try { const n = e.runtimeContextMessage && (e.appendOnlyRuntimeContext || isOpenClawSystemUpdateMessage(e.runtimeContextMessage)) ? t[agentSessionQueuePromptContext](e.runtimeContextMessage) : installRuntimeContextMessageForPrompt({ session: t, message: e.runtimeContextMessage, persistedUserIdempotencyKey: a }); try { await e.promptActiveSession(s, u); } finally { n(); } } finally { if (f) e.setNextUserMessagePersistence?.("normal"); d(); l(); } } /** Classifies prompt submissions that have no visible current-turn content. */ function resolvePromptSubmissionSkipReason(e) { if (e.prompt.trim().length > 0 || e.imageCount > 0) return null; return e.messages.some(hasVisiblePromptHistory) ? "blank_user_prompt" : "empty_prompt_history_images"; } function hasVisiblePromptHistory(e) { if (!e || typeof e !== "object") return false; const t = e; if (t.role !== "user" && t.role !== "assistant") return false; return hasNonEmptyContent(t.content); } function hasNonEmptyContent(e) { if (typeof e === "string") return e.trim().length > 0; if (Array.isArray(e)) return e.some(hasNonEmptyContent); if (!e || typeof e !== "object") return false; const t = e; return hasNonEmptyContent(t.text) || hasNonEmptyContent(t.content); } async function handleEmbeddedAttemptPromptError(e) { const t = e.yieldDetected && isSessionsYieldAbortError(e.error); if (t) e.markYieldAborted(); if (t) { await waitForEmbeddedAbortSettle({ promise: e.yieldAbortSettled, runId: e.attempt.runId, sessionId: e.attempt.sessionId, reason: "sessions_yield" }); await e.withOwnedTranscriptWrite(async () => { const t = await withSessionManagerWrite(e.activeSession.sessionManager, () => stripSessionsYieldArtifacts(e.activeSession)); if (e.yieldMessage) await e.activeSession.sendCustomMessage(buildSessionsYieldContextMessage(e.yieldMessage), { triggerTurn: false }); const n = t && e.activeSession.sessionManager.getSessionTarget(); if (n) { const { waitForSessionTranscriptProjection: t } = await import("./config/sessions/session-transcript-reconcile.js"); await t(n, e.attempt.abortSignal); } }); return {}; } if (isMidTurnPrecheckSignal(e.error)) { const t = e.error.request; await e.withOwnedTranscriptWrite(() => withSessionManagerWrite(e.activeSession.sessionManager, () => e.handleMidTurnPrecheckRequest(t))); return {}; } return { promptFailure: { error: e.error, source: "prompt" } }; } //#endregion //#region src/agents/embedded-agent-runner/run/attempt-prompt-support.ts /** Retains the prompt hook's cap while replacing the host-owned tool generation. */ function createPromptBuildToolPolicy(e) { const captureBaseline = () => ({ activeToolNames: e.session.getActiveToolNames(), catalogEntries: [...e.catalogRef?.current?.entries ?? []] }); let t = captureBaseline(); let n; let r = false; const i = { activeToolNames: [...t.activeToolNames], callableToolNames: [...t.activeToolNames], effectiveTools: e.effectiveTools, uncompactedEffectiveTools: e.uncompactedEffectiveTools, tools: e.tools }; const applyCurrent = () => { Object.assign(i, applyPromptBuildToolsAllow({ ...e, baseline: t, toolsAllow: r ? [] : n })); e.onApplied?.(i); return i; }; const apply = (e, t = false) => { const a = i.effectiveTools.length; n = e; r = t; const o = applyCurrent(); if (r) logDecisionToolPrefilter({ effect: "applied", modelFacingToolsBefore: a, modelFacingToolsAfter: o.effectiveTools.length }); return o; }; return { current: i, apply, hasBaselineTools: () => t.activeToolNames.length > 0, refresh: () => { t = captureBaseline(); return applyCurrent(); } }; } function applyResolvedToolPromptFinalizer(e) { if (!e.finalize) return e.prompt; return e.finalize({ prompt: e.prompt, messageToolAvailable: e.activeToolNames.some((e) => normalizeToolPolicyName(e) === "message") }); } /** * Applies a prompt-hook execution cap without changing the provider definitions. * The concrete host baseline still bounds both direct and catalog execution. */ function applyPromptBuildToolsAllow(e) { const t = { toolsAllow: e.toolsAllow, forceToolNames: e.forceToolNames }; const n = e.baseline.activeToolNames.flatMap((t) => { const n = e.session.getToolDefinition(t); return n ? [getToolDefinitionSource(n) ?? n] : []; }); const r = createAgentHarnessPromptToolPolicy({ tools: n, catalogRef: e.catalogRef, catalogEntries: e.baseline.catalogEntries, codeModeControlsEnabled: e.codeModeControlsEnabled }).apply(t); const i = new Set(r.callableToolNames.map(normalizeToolPolicyName)); const filterTools = (e) => createAgentHarnessPromptToolPolicy({ tools: e, codeModeControlsEnabled: false }).apply(t).tools.filter((e) => i.has(normalizeToolPolicyName(e.name))); const a = filterTools(e.uncompactedEffectiveTools); const o = filterTools(e.tools); const s = [...e.baseline.activeToolNames]; e.session.setActiveToolsByName(s, r.callableToolNames); return { activeToolNames: s, callableToolNames: r.callableToolNames, effectiveTools: e.effectiveTools, uncompactedEffectiveTools: a, tools: o }; } function observeEmbeddedAttemptPrompt(e) { const { attempt: t } = e; let n = e.skipPromptSubmission; if (!n) { e.cacheTrace?.recordStage("prompt:before", { prompt: e.promptForModel, messages: e.sessionMessages }); e.cacheTrace?.recordStage("prompt:images", { prompt: e.promptForModel, messages: e.sessionMessages, note: `images: prompt=${e.imageCount}` }); const t = e.trajectoryRecorder; if (t) { const n = toTrajectoryToolDefinitions(e.effectiveTools); const r = e.toolSearchCompacted ? toTrajectoryToolDefinitions(e.uncompactedEffectiveTools) : n; t.recordEvent("context.compiled", { systemPrompt: e.systemPromptForHook, prompt: e.promptForModel, messages: e.sessionMessages, tools: r, ...e.toolSearchCompacted ? { providerVisibleTools: n } : {}, imagesCount: e.imageCount, streamStrategy: e.streamStrategy, transport: e.transport, transcriptLeafId: e.transcriptLeafId }); } } const r = n ? null : resolvePromptSubmissionSkipReason({ prompt: e.promptForModel, messages: e.sessionMessages, imageCount: e.imageCount }); if (r) { n = true; const i = `runId=${t.runId} sessionId=${t.sessionId} trigger=${t.trigger} provider=${t.provider}/${t.modelId}`; if (r === "blank_user_prompt") log.warn(`embedded run prompt skipped: blank user prompt ${i}`); else log.info(`embedded run prompt skipped: empty prompt/history/images ${i}`); e.trajectoryRecorder?.recordEvent("prompt.skipped", { reason: r, prompt: e.promptForModel, messages: e.sessionMessages, imagesCount: e.imageCount }); } const i = summarizeSessionContext(e.sessionMessages); emitTrustedDiagnosticEvent({ type: "context.assembled", runId: t.runId, ...t.sessionKey && { sessionKey: t.sessionKey }, ...t.sessionId && { sessionId: t.sessionId }, provider: t.provider, model: t.modelId, ...t.messageChannel ?? t.messageProvider ? { channel: t.messageChannel ?? t.messageProvider } : {}, trigger: t.trigger, messageCount: e.sessionMessages.length, historyTextChars: i.totalTextChars, historyImageBlocks: i.totalImageBlocks, maxMessageTextChars: i.maxMessageTextChars, systemPromptChars: e.systemPromptText?.length ?? 0, promptChars: e.effectivePrompt.length, promptImages: e.imageCount, contextTokenBudget: e.contextTokenBudget, reserveTokens: e.reserveTokens, trace: freezeDiagnosticTraceContext(createChildDiagnosticTraceContext(e.runTrace)) }); t.onExecutionPhase?.({ phase: "context_assembled", provider: t.provider, model: t.modelId }); if (log.isEnabled("debug")) log.debug(`[context-diag] pre-prompt: sessionKey=${t.sessionKey ?? t.sessionId} messages=${e.sessionMessages.length} roleCounts=${i.roleCounts} historyTextChars=${i.totalTextChars} maxMessageTextChars=${i.maxMessageTextChars} historyImageBlocks=${i.totalImageBlocks} systemPromptChars=${e.systemPromptText?.length ?? 0} promptChars=${e.effectivePrompt.length} promptImages=${e.imageCount} provider=${t.provider}/${t.modelId} sessionFile=${t.sessionFile}`); if (t.operation !== "settled-tool-finalization" && !n && !e.isRawModelRun && e.hookRunner?.hasHooks("llm_input")) e.hookRunner.runLlmInput({ runId: t.runId, sessionId: t.sessionId, provider: t.provider, model: t.modelId, systemPrompt: e.systemPromptForHook, prompt: e.llmBoundaryPromptForPrecheck, /** Gives hooks an isolated message snapshot they cannot mutate in-session. */ historyMessages: e.hookMessagesForCurrentPrompt.map((e) => structuredClone(e)), imagesCount: e.imageCount, tools: e.tools }, buildEmbeddedAgentHookContext(t, e.hookAgentId, freezeDiagnosticTraceContext(e.diagnosticTrace))).catch((e) => { log.warn(`llm_input hook failed: ${String(e)}`); }); return { skipPromptSubmission: n }; } //#endregion //#region src/agents/embedded-agent-runner/run/attempt-stage-timing.ts const EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE = { workspace: "attempt-workspace", prompt: "attempt-prompt", runtimePlan: "attempt-runtime-plan", dispatch: "attempt-dispatch" }; const EMBEDDED_RUN_STAGE_WARN_TOTAL_MS = 1e4; const EMBEDDED_RUN_STAGE_WARN_STAGE_MS = 5e3; function createEmbeddedRunStageSummaryEmitter(e) { return (t) => logEmbeddedRunStageSummary(e.tracker.snapshot(), e.log, () => `[trace:embedded-run] ${e.label}: runId=${e.runId} sessionId=${e.sessionId} phase=${t}`); } function logEmbeddedRunStageSummary(e, t, n, r) { const i = e.totalMs >= (r?.totalThresholdMs ?? EMBEDDED_RUN_STAGE_WARN_TOTAL_MS) || e.stages.some((e) => e.durationMs >= (r?.stageThresholdMs ?? EMBEDDED_RUN_STAGE_WARN_STAGE_MS)); if (i || t.isEnabled("trace")) { const r = formatEmbeddedRunStageSummary(n(), e); t[i ? "warn" : "trace"](r); } } function formatEmbeddedRunStageSummary(e, t) { const n = formatStageTimings(t.stages); return `${e} pid=${process.pid} threadId=${threadId} isMainThread=${isMainThread} totalMs=${t.totalMs} stages=${n}`; } //#endregion //#region src/agents/embedded-agent-runner/run/attempt-transcript-helpers.ts /** Reuse the admitted prompt target, otherwise resolve the dispatch's exact transcript. */ async function resolveAttemptDispatchSessionTarget(e) { const t = e.promptState; const n = t.sessionTarget; const r = (n?.sessionKey === e.sessionKey || t.sessionTargetAdopted ? n : void 0) ?? (e.sessionKey ? await resolveSessionTranscriptRuntimeTarget({ agentId: e.agentId, sessionId: t.sessionId, sessionKey: e.sessionKey, storePath: resolveSessionStorePathCore(e.config?.session?.store, { agentId: e.agentId }) }) : void 0); return r || t.sessionTarget ? { ...t.sessionTarget, ...r, ...t.sessionWriterFence } : void 0; } async function removeTrailingMidTurnPrecheckAssistantError(e) { const t = e.activeSession.agent.state.messages; const n = isMidTurnPrecheckAssistantError(t.at(-1)); const r = e.sessionManager.getEntries().findLast((e) => !preserveTrailingTranscriptMetadata(e)); const i = r?.type === "message" && isMidTurnPrecheckAssistantError(r.message); const a = i && await e.sessionManager.removeTrailingEntriesAsync((e) => e.type === "message" && isMidTurnPrecheckAssistantError(e.message), { preserveTrailing: preserveTrailingTranscriptMetadata }) > 0; if (n) e.activeSession.agent.state.messages = t.slice(0, -1); if (i && n && !a) log.warn("[context-overflow-midturn-precheck] removed synthetic assistant error from active session but could not locate matching persisted SessionManager entry"); } async function normalizeCompactionRecoveryTranscriptTail(e) { const t = e.activeSession.agent.state.messages; const n = trimToContinuableTail(t) ?? []; const r = await e.sessionManager.removeTrailingEntriesAsync((e) => e.type === "message" && !canContinueFromMessage(e.message), { preserveTrailing: preserveTrailingTranscriptMetadata }); e.activeSession.agent.state.messages = r > 0 ? sanitizeCompactionReplayMessages(e.sessionManager.buildSessionContext().messages) : n.length === t.length ? t : n; return r; } async function loadAttemptSessionEntryAfterQuotaMaintenance(e, t) { const n = await readSessionEntryInWorker(e, t); t(); if (!n?.quotaSuspension) return n; const r = Date.now(); if (!resolveQuotaSuspensionEntryMaintenance({ entry: n, now: r })) return n; const i = await patchSessionEntryCore(e, (e) => resolveQuotaSuspensionEntryMaintenance({ entry: e, now: r }), { skipMaintenance: true, takeCacheOwnership: true, ...sessionEntryCommitGuardOptions(t) }); t(); return i ?? n; } async function resolveAttemptTrajectorySessionFile(e) { const t = e.sessionTarget?.storePath ?? resolveSessionStorePathCore(e.config?.session?.store, { agentId: e.agentId }); if (!t || !e.sessionKey) return e.sessionFile; return (await resolveSessionTranscriptRuntimeTarget({ agentId: e.agentId, sessionId: e.sessionId, sessionKey: e.sessionKey, storePath: t })).sessionKey; } async function resolveExistingAttemptTranscriptState(e) { if (e.sessionManager) return { hasBootstrapTranscriptState: e.sessionManager.getEntries().some((e) => e.type === "message") }; const t = normalizeOptionalString(e.sessionTarget?.agentId) ?? e.agentId; const n = normalizeOptionalString(e.sessionTarget?.storePath) ?? resolveSessionStorePathCore(e.config?.session?.store, { agentId: t }); const r = normalizeOptionalString(e.sessionTarget?.sessionId) ?? e.sessionId; const i = normalizeOptionalString(e.sessionTarget?.sessionKey) ?? normalizeOptionalString(e.sessionKey); let a = false; if (n && i) try { a = await hasSessionTranscriptMessage({ agentId: t, sessionId: r, sessionKey: i, storePath: n }); } catch { a = false; } return { hasBootstrapTranscriptState: a }; } //#endregion export { SESSIONS_YIELD_ABORT_REASON as C, isRunnerAbortError as D, queueSessionsYieldInterruptMessage as E, buildEmbeddedAgentHookContext as O, shouldFlagCompactionTimeout as S, isSessionsYieldAbortReason as T, resolveAttemptWorkspaceSandbox as _, resolveAttemptTrajectorySessionFile as a, resolveRunTimeoutDuringCompaction as b, createEmbeddedRunStageSummaryEmitter as c, createPromptBuildToolPolicy as d, observeEmbeddedAttemptPrompt as f, preparePluginHarnessWorkspace as g, cleanupEmbeddedAttemptResources as h, resolveAttemptDispatchSessionTarget as i, logEmbeddedRunStageSummary as l, submitEmbeddedAttemptPrompt as m, normalizeCompactionRecoveryTranscriptTail as n, resolveExistingAttemptTranscriptState as o, handleEmbeddedAttemptPromptError as p, removeTrailingMidTurnPrecheckAssistantError as r, EMBEDDED_RUN_ATTEMPT_DISPATCH_STAGE as s, loadAttemptSessionEntryAfterQuotaMaintenance as t, applyResolvedToolPromptFinalizer as u, resolveHarnessWorkspace as v, createYieldAbortedResponse as w, selectCompactionTimeoutSnapshot as x, measureEmbeddedAgentPreparation as y };