UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

654 lines (653 loc) • 29 kB
import "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import "./session-key-CqAyZeVk.mjs"; import "./usage-CHLnzpJG.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import "./version-GlxUMdxI.mjs"; import { l as getPluginValueInstance } from "./plugin-instance-scope-oezVdCr2.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import "./agent-events-BdfWYmot.mjs"; import { u as resolveExecModePolicy } from "./exec-approvals-core-puBAw1bE.mjs"; import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs"; import { d as setAgentRunAttemptTerminalFailure, l as normalizeAgentRunAttemptTerminal, s as mergeAgentRunAttemptTerminal, u as projectAgentRunAttemptTerminal } from "./agent-run-terminal-outcome-wduf2occ.mjs"; import "./run-termination-0Ig0-bk6.mjs"; import { a as logMessageQueuedWithBacklogPolicy, t as diagnosticLogger } from "./diagnostic-runtime-BxwnWXDu.mjs"; import { pt as canSteerEmbeddedRunDuringCompaction, xt as resolveReplyRunForCurrentSessionId } from "./session-controller.state-BApgK0mV.mjs"; import { i as expandToolGroups } from "./tool-policy-shared-BHvBopvF.mjs"; import { r as createToolPolicyMatcher } from "./tool-policy-match-DzwVnbV4.mjs"; import "./reply-payload-k5WsQWxi.mjs"; import { n as maxAsk, r as minSecurity } from "./exec-approvals-policy-BGzNHuNm.mjs"; import "./tool-metadata-rqUpUHlb.mjs"; import "./agent-tool-availability-ecKW8hOH.mjs"; import "./agent-tool-metadata-nrQgRaqv.mjs"; import { f as getDetachedNativeAttachment, y as resolveRegisteredEmbeddedRunRecoveryBlocker } from "./run-state-jrY5s7TG.mjs"; import "./internal-runtime-context-BEUlDNuI.mjs"; import "./agent-run-terminal-reply-DXju8G9G.mjs"; import "./user-turn-transcript.metadata-GFtsH_a_.mjs"; import { l as createMessageInjectionAuthority } from "./message-injection-authority-B9SdalrV.mjs"; import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs"; import { d as joinPresentTextSegments } from "./hooks-BiZpB_10.mjs"; import "./hook-helpers-DKwpcDXZ.mjs"; import "./registry-ubpieJjd.mjs"; import "./provider-request-config-CCij-nof.mjs"; import { i as PluginCapabilityRemovedError } from "./registry-ClBzy_np.mjs"; import "./registry-BNPXTWdk.mjs"; import { c as resolveActiveReplyOperationForSessionId } from "./session-controller.queries-D7T8foQX.mjs"; import "./compaction-safety-timeout-Dm_4UNnX.mjs"; import { _ as resolveRunStaleThresholdMs, i as getDiagnosticSessionActivitySnapshot } from "./diagnostic-run-activity-BzWz2WN_.mjs"; import "./streaming-directives-C1RBdaQG.mjs"; import "./agent-activity-presentation-BIQtAp6v.mjs"; import "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import "./tool-result-error-B2GHe83l.mjs"; import "./gateway-DL_Nxi-v.mjs"; import "./embedded-agent-messaging-CBeq8Mz9.mjs"; import "./tool-mutation-BBJdXAL6.mjs"; import "./agent-tools.before-tool-call-CCkSq-k3.mjs"; import "./date-time-ChxDjIEM.mjs"; import "./in-process-gateway-Cy0xoBmg.mjs"; import { t as log$2 } from "./logger-DgCpB-Fs.mjs"; import "./gateway-question-u5Q7erev.mjs"; import "./ask-user-tool-normalization-BkE0uL3h.mjs"; import "./tool-display-BQXZgFy6.mjs"; import "./tool-meta-BPR-w7I7.mjs"; import { n as bindMessageInjectionV2 } from "./tool-authority-preparation-BOURfTvP.mjs"; import { c as canInjectReplyMessageTarget, l as resolveReplyBackendQueueMessageMismatch, n as steerSessionControllerOperation, o as captureReplyMessageInjectionTarget } from "./session-controller.steer-BWjVys2Y.mjs"; import { a as shouldLoadRequesterScopedMcpHarnessRuntime } from "./agent-bundle-mcp-runtime-shared-CHct-FOd.mjs"; import "./agent-activity-events-BvMnPRzr.mjs"; import { r as prepareMemorySystemPromptAddition } from "./delegate-7xQ3O-I9.mjs"; import "./agent-scope-runtime-CDpr-vor.mjs"; import "./model-auth-CEsyk_Yg.mjs"; import { i as buildCurrentInboundPrompt } from "./runtime-context-prompt-CRmsG0oC.mjs"; import "./execution-auth-binding-DfJE1iEP.mjs"; import { r as buildBootstrapContextForFiles } from "./bootstrap-BoYamcpL.mjs"; import { s as resolveBootstrapFilesForRun } from "./bootstrap-files-CdJt18lf.mjs"; import "./attempt-tool-construction-plan-Cp8YcsYs.mjs"; import { i as attachActiveEmbeddedRun, o as detachActiveEmbeddedRun } from "./runs-C1RO1Y6L.mjs"; import "./source-reply-delivery-mode-CYtLiYyC.mjs"; import "./agent-tools.ring-zero-context-Cg68_lTM.mjs"; import "./tool-schema-projection-D-AbMZEk.mjs"; import "./tool-schema-runtime-BdZF8AHc.mjs"; import "./tools-CX1i5Uw0.mjs"; import "./prepare-auth-Ck7RPVAG.mjs"; import "./settled-turn-finalization-result-DSvueaqd.mjs"; import { n as resolvePluginTurnContext } from "./plugin-turn-context-DWfKHRkT.mjs"; import "./result-fallback-classifier-CMNqkOLy.mjs"; import "./native-hook-relay-P9pIuF1y.mjs"; import { t as buildAgentHookContext } from "./hook-context-rf3tn_l4.mjs"; import "./lifecycle-hook-helpers-XBA2t8zZ.mjs"; import "./embedded-agent-message-delivery-ClVuBxqZ.mjs"; import "./embedded-agent-message-tool-source-reply-BLgXJNuN.mjs"; import "./tool-result-middleware-tMZkWoHr.mjs"; import { a as isStructuredInputRecord, i as compileStructuredInputUrl, n as compileStructuredInputForm, o as snapshotStructuredInput, r as compileStructuredInputQuestions } from "./structured-input-DSYgb17h.mjs"; import { t as runStructuredInput } from "./structured-input-execution-BMyxgore.mjs"; import { d as buildWatchedSessionsPromptLines, f as prepareWatchedSessionsPrompt, i as prepareContextFilesForPrompt, p as prepareWatchedSessionsPromptAsync, t as PERSONAL_USER_CONTEXT_INSTRUCTIONS } from "./system-prompt-context-files-BTDEQYK6.mjs"; import "./projection-tool-output-DX3_Ng9b.mjs"; import "./progress-card-channel-summary-CkIMdtP9.mjs"; import "./transcript-visibility-BBTBADQE.mjs"; import "./build-1KVS3lgO.mjs"; import "./nodes-utils-B4u6gtyR.mjs"; import "./embedded-agent-messaging-extraction-C5OCu-VM.mjs"; import "./embedded-agent-tool-authored-source-reply-D2Px90_h.mjs"; import "./embedded-agent-tool-results-DbtxSr9V.mjs"; import "./embedded-agent-tool-media-Bzv7p-IE.mjs"; import { c as wrapPluginSystemContextSection } from "./attempt-prompt-helpers-bQX_3CMZ.mjs"; import "./attempt-thread-helpers-BkXHw9TC.mjs"; import "./attempt-tool-run-context-DpLguX9-.mjs"; import "./context-DNnE7m_d.mjs"; import "./fs-paths-BcNIEM2k.mjs"; import "./preemptive-compaction-DWbzXuZy.mjs"; import "./context-engine-lifecycle-VWAug052.mjs"; import "./agent-end-side-effects-B-uaSvUn.mjs"; import path from "node:path"; //#region src/agents/embedded-agent-runner/runs.message-injection.ts /** Sessionless input belongs to its exact native registration, never a session scheduler. */ function queueDetachedEmbeddedAgentMessage(e, t, n) { if (resolveReplyRunForCurrentSessionId(e).kind !== "none") return false; const r = getDetachedNativeAttachment(e); if (!r) return false; const { handle: i } = r; const ownsRegistration = () => { r.toolAuthority?.assertActive(); return resolveReplyRunForCurrentSessionId(e).kind === "none" && getDetachedNativeAttachment(e) === r; }; const reportFailure = (t) => diagnosticLogger.debug(`queue message rejected: sessionId=${e} err=${formatErrorMessage(t)}`); let a; let o; try { const t = i.messageInjectionV2; const s = i.messageInjection; if (!(t ? t.isAvailable() : s ? s.isAvailable() : i.isStopped ? !i.isStopped() : i.isStreaming()) || !canSteerEmbeddedRunDuringCompaction(e, i)) return false; const c = resolveRegisteredEmbeddedRunRecoveryBlocker(r, ownsRegistration); const l = c === "human_input_wait" || c === "runtime_owned_wait"; const u = getDiagnosticSessionActivitySnapshot({ sessionId: e }); if (typeof u.lastProgressAgeMs === "number" && u.lastProgressAgeMs > resolveRunStaleThresholdMs(u) && !l) return false; const { toolAuthorityOverlay: d, ...f } = n ?? { steeringMode: "all" }; o = f; if (d) { o.toolAuthorityFingerprint = r.toolAuthority?.project(d); if (!o.toolAuthorityFingerprint) return false; } if (o.waitForTranscriptCommit === true && i.supportsTranscriptCommitWait !== true || resolveReplyBackendQueueMessageMismatch(i, o)) return false; if (!ownsRegistration()) return false; const p = createMessageInjectionAuthority(ownsRegistration); const m = createMessageInjectionAuthority(() => { n?.assertCurrent?.(); if (t && d) { const e = r.toolAuthority?.project(d); if (!e || e !== i.toolAuthorityFingerprint) return false; } return ownsRegistration(); }); a = t ? bindMessageInjectionV2(t, m, "run").queueMessage : (e, t) => { n?.assertCurrent?.(); p(); return (s ?? i).queueMessage(e, t); }; } catch (e) { reportFailure(e); return false; } logMessageQueuedWithBacklogPolicy({ sessionId: e, source: "embedded-agent-runner" }, false); a(t, o).catch(reportFailure); return true; } //#endregion //#region src/plugins/agent-executor-controller.ts /** Retained for published AgentsAPI imports; controller ownership cannot be recreated. */ function resolveAgentExecutorController(e) { throw new PluginCapabilityRemovedError("api.registerAgentExecutorController", `Executor controller "${e}" is unavailable. Retire or migrate its saved AgentsAPI sessions with the previous host before switching to an externally managed self_hosted environment.`); } //#endregion //#region src/agents/harness/workspace-instructions.ts /** Projects already-bounded agent instructions without changing bootstrap budgets. */ function buildAgentWorkspaceInstructionSnapshot(e, t) { const n = selectAgentWorkspaceInstructionFiles(e, t).filter((e) => !e.content.trimStart().startsWith("[MISSING] Expected at:") && e.content.trim().length > 0); if (n.length === 0) return { files: n, instructions: "" }; const r = [ "## OpenClaw Agent Workspace Instructions", "", "OpenClaw loaded this bounded snapshot from the configured agent workspace.", "" ]; for (const e of n) r.push(`### ${e.path}`, "", e.content, ""); return { files: n, instructions: r.join("\n").trim() }; } /** Selects only the configured workspace's root instruction document. */ function selectAgentWorkspaceInstructionFiles(e, t) { const n = path.join(path.resolve(t), "AGENTS.md"); return e.filter((e) => path.resolve(e.path) === n); } //#endregion //#region src/agents/harness/workspace-context.ts /** Prepares Gateway workspace facts; the harness owns their native carriers and lifetime. */ async function prepareAgentWorkspaceContext(e) { const t = await resolveBootstrapFilesForRun(e); const n = e.scope === "instructions-only"; const r = !n && e.memoryToolRouted === true; const i = r ? prepareContextFilesForPrompt(t.filter((t) => isRootMemoryPath(t.path, e.workspaceDir) && !t.missing && (t.content ?? "").trim().length > 0).map((e) => Object.assign(toContextFile(e), { bootstrapFile: e })), { order: e.contextFileOrder, caseInsensitivePathOrder: true, trimBasename: false }).map(({ file: e }) => e.bootstrapFile) : []; const a = n ? selectAgentWorkspaceInstructionFiles(t, e.workspaceDir).filter((e) => !e.missing) : r ? t.filter((t) => !isRootMemoryPath(t.path, e.workspaceDir)) : t; const o = buildBootstrapContextForFiles(a, e).map((t) => projectContextFile(t, e.projectPath)); const s = buildAgentWorkspaceInstructionSnapshot(o, e.workspaceDir); if (n) return { bootstrapFiles: t, contextFiles: o, instructionSnapshot: s, personaFiles: [], promptContextFiles: [], memoryReferenceFiles: [], memoryToolRoutedBootstrapFiles: [] }; const c = sortContextFiles(o.filter((e) => PERSONA_FILE_BASENAMES.has(contextFileBasename(e.path)) && !isMissingContextFile(e) && e.content.trim().length > 0), e.contextFileOrder); const l = sortContextFiles(o.filter((t) => { const n = contextFileBasename(t.path); const i = e.nativeProjectDocBasenames ? e.nativeProjectDocBasenames.has(n) : selectAgentWorkspaceInstructionFiles([t], e.workspaceDir).length > 0; return n.length > 0 && !i && !PERSONA_FILE_BASENAMES.has(n) && (!r || !isRootMemoryPath(t.path, e.promptMemoryWorkspaceDir ?? e.workspaceDir)) && !isMissingContextFile(t); }), e.contextFileOrder); const u = i.map((t) => projectContextFile(toContextFile(t), e.projectPath)); const d = e.memoryTools ? await prepareMemorySystemPromptAddition({ availableTools: new Set(e.memoryTools.toolNames), citationsMode: e.memoryTools.citationsMode, agentId: e.agentId, agentSessionKey: e.sessionKey, sandboxed: e.memoryTools.sandboxed }).catch((t) => { if (e.onMemoryPreparationError) e.onMemoryPreparationError(t); else e.warn?.(`failed to prepare workspace memory recall instructions: ${String(t)}`); }) : void 0; return { bootstrapFiles: t, contextFiles: o, instructionSnapshot: s, personaFiles: c, personaInstructions: renderPersonaInstructions(c), sharedPersonaInstructions: renderPersonaInstructions(c.filter((e) => e.personalUser !== true)), promptContextFiles: l, memoryReferenceFiles: u, memoryToolRoutedBootstrapFiles: i, memoryRecallInstructions: d }; } const PERSONA_FILE_BASENAMES = /* @__PURE__ */ new Set([ "identity.md", "soul.md", "user.md" ]); function renderPersonaInstructions(e) { if (e.length === 0) return; const t = [ "## OpenClaw Agent Soul", "", "OpenClaw loaded these workspace instruction files from the active agent workspace. They are the instructions that define who you are, how you think and work, and the human you work alongside. Internalize and follow them accordingly." + (e.some((e) => e.personalUser === true) ? ` ${PERSONAL_USER_CONTEXT_INSTRUCTIONS}` : ""), "", "<AGENT_SOUL>", "" ]; for (const n of e) t.push(`### ${n.path}`, "", n.content, ""); t.push("</AGENT_SOUL>"); return t.join("\n").trim(); } function sortContextFiles(e, t) { return prepareContextFilesForPrompt(e, { order: t, caseInsensitivePathOrder: true, trimBasename: false }).map(({ file: e }) => e); } function toContextFile(e) { return { path: e.path, content: e.content ?? "", ...e.personalUser === true ? { personalUser: true } : {} }; } function projectContextFile(e, t) { return t ? { ...e, path: t(e.path) } : e; } function isRootMemoryPath(e, t) { const n = e.trim(); if (!n) return false; return path.resolve(t, n) === path.join(path.resolve(t), "MEMORY.md"); } function contextFileBasename(e) { return e.trim().replaceAll("\\", "/").toLowerCase().split("/").pop() ?? ""; } function isMissingContextFile(e) { return e.content.trimStart().startsWith("[MISSING] Expected at:"); } //#endregion //#region src/plugin-sdk/session-write-lock-runtime.ts const DEFAULT_SESSION_WRITE_LOCK_ACQUIRE_TIMEOUT_MS = 6e4; const DEFAULT_SESSION_WRITE_LOCK_STALE_MS = 18e5; const DEFAULT_SESSION_WRITE_LOCK_MAX_HOLD_MS = 3e5; /** * @deprecated Session write leases were removed. This compatibility stub is scheduled for * removal in the 2026.10 release train; use the session lane and durable writer claim/fence. */ function resolveSessionWriteLockAcquireTimeoutMs(e, t) { return DEFAULT_SESSION_WRITE_LOCK_ACQUIRE_TIMEOUT_MS; } /** * @deprecated Session write leases were removed. This compatibility stub is scheduled for * removal in the 2026.10 release train; use the session lane and durable writer claim/fence. */ function resolveSessionWriteLockOptions(e, t = {}) { return { timeoutMs: DEFAULT_SESSION_WRITE_LOCK_ACQUIRE_TIMEOUT_MS, staleMs: DEFAULT_SESSION_WRITE_LOCK_STALE_MS, maxHoldMs: DEFAULT_SESSION_WRITE_LOCK_MAX_HOLD_MS }; } /** * @deprecated Session write leases were removed. This no-op compatibility stub is scheduled * for removal in the 2026.10 release train; use the session lane and durable writer claim/fence. */ async function acquireSessionWriteLock(e) { return { assertOwned: () => void 0, release: async () => void 0 }; } //#endregion //#region src/agents/harness/prompt-compaction-hook-helpers.ts const log$1 = createSubsystemLogger("agents/harness"); const warnHookFailure = (e) => (t) => { log$1.warn(`${e} hook failed: ${String(t)}`); }; async function resolveAgentHarnessBeforePromptBuildResult(e) { const t = buildCurrentInboundPrompt({ context: e.currentInboundContext, prompt: e.prompt }); const n = getGlobalHookRunner(); const r = Boolean(n?.hasHooks("before_prompt_build")); const i = buildAgentHookContext(e.ctx); const a = e.currentUserMessage; const o = typeof a === "string" ? a : a ? typeof a.content === "string" ? a.content : a.content.flatMap((e) => e.type === "text" ? [e.text] : []).join("\n") : void 0; const s = e.currentUserMessageId ?? (typeof a === "object" ? a.idempotencyKey : void 0); const c = { prompt: t, ...o !== void 0 ? { currentUserMessage: o } : {}, ...s !== void 0 ? { currentUserMessageId: s } : {}, messages: r || n?.hasHooks("agent_turn_prepare") ? typeof e.messages === "function" ? await e.messages() : e.messages : [] }; const l = await resolvePluginTurnContext({ config: e.ctx.config ?? {}, prompt: t, messages: c.messages, hookCtx: i, hookRunner: n }); const u = n && r ? await n.runBeforePromptBuild(c, i).catch(warnHookFailure("before_prompt_build")) : void 0; const d = resolveDeveloperInstructions(e.developerInstructions, u?.toolsAllow); const f = e.toolAuthority; const p = f?.fingerprint?.trim(); const m = n && p && f ? await n.runAuthorizedPromptBuild(c, i, { toolAuthorityFingerprint: p, activeToolNames: f.activeToolNames(), assertHostActive: f.assertActive }).catch(warnHookFailure("authorized before_prompt_build")) : void 0; const h = typeof u?.systemPrompt === "string" ? u.systemPrompt : d; const g = joinPresentTextSegments([ l.prependContext, u?.prependContext, m?.prependContext ]); const _ = joinPresentTextSegments([ l.appendContext, u?.appendContext, m?.appendContext ]); const v = joinPresentTextSegments([ g, t, _ ]) ?? t; const y = t.length === 0 ? g?.length ?? 0 : g ? g.length + 2 : 0; const b = wrapPluginSystemContextSection(u?.prependSystemContext); const x = wrapPluginSystemContextSection(u?.appendSystemContext); const S = joinPresentTextSegments([b, x]); return { prompt: v, ...u?.toolsAllow !== void 0 ? { toolsAllow: u.toolsAllow } : {}, developerInstructions: joinPresentTextSegments([ b, h, x ]) ?? h, ...S ? { threadDeveloperInstructions: h, turnDeveloperInstructions: S } : {}, promptInputRange: { start: y, end: y + t.length } }; } function resolveDeveloperInstructions(e, t) { return typeof e === "string" ? e : e.build({ toolsAllow: t, hasToolRestrictions: t !== void 0 && !t.some((e) => e.trim() === "*") }) ?? ""; } /** Runs best-effort before-compaction hooks for a harness session. */ async function runAgentHarnessBeforeCompactionHook(e) { const t = getGlobalHookRunner(); if (!t?.hasHooks("before_compaction")) return; try { await t.runBeforeCompaction({ messageCount: e.messages?.length ?? -1, ...e.messages ? { messages: e.messages } : {}, sessionFile: e.sessionFile }, buildAgentHookContext(e.ctx)); } catch (e) { log$1.warn(`before_compaction hook failed: ${String(e)}`); } } /** Runs best-effort after-compaction hooks for a harness session. */ async function runAgentHarnessAfterCompactionHook(e) { const t = getGlobalHookRunner(); if (!t?.hasHooks("after_compaction")) return; try { await t.runAfterCompaction({ messageCount: e.messages?.length ?? -1, compactedCount: e.compactedCount, sessionFile: e.sessionFile }, buildAgentHookContext(e.ctx)); } catch (e) { log$1.warn(`after_compaction hook failed: ${String(e)}`); } } //#endregion //#region src/agents/harness/codex-app-server-extensions.ts const log = createSubsystemLogger("agents/harness"); /** Retained for published Codex plugins; new transforms use runtime-neutral middleware. */ function createCodexAppServerToolResultExtensionRunner(e, t = []) { const n = []; const r = (async () => { for (const e of t) { const t = getPluginValueInstance(e); await e({ on(e, r) { if (e === "tool_result") { if (t) t.run(() => n.push(t.wrap(r))); else n.push(r); } } }); } })(); return { async applyToolResultExtensions(t) { await r; let i = t.result; for (const r of n) try { const n = await r({ ...t, result: i }, e); if (n?.result) i = n.result; } catch (e) { const n = e instanceof Error ? e.message : String(e); log.warn(`[codex] tool_result extension failed for ${t.toolName}: ${n}`); } return i; } }; } //#endregion //#region src/plugin-sdk/agent-harness-runtime.ts /** Core exec mode algebra for plugin-owned policy adapters. */ const execPolicy = Object.freeze({ resolveExecModePolicy, minSecurity, maxAsk }); /** * Renders the Watched Sessions prompt block for plugin-owned harness prompts. * Harness runtimes that assemble their own instruction layers (e.g. Codex) * must surface the same watched-session facts as the embedded prompt, or the * model keeps refusing cross-session questions on those runtimes (openclaw#114797). * @deprecated Await prepareWatchedSessionsHarnessContext with current host authority. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */ function buildWatchedSessionsHarnessContext(e) { warnPluginSdkDeprecation({ family: "watched-sessions-sync-harness-context", method: "buildWatchedSessionsHarnessContext", replacement: "await prepareWatchedSessionsHarnessContext() with a host-bound assertCurrent" }); const t = buildWatchedSessionsPromptLines(prepareWatchedSessionsPrompt({ enabled: true, ...e })); return t.length > 0 ? t.join("\n").trimEnd() : void 0; } /** Prepares current watched-session facts through the worker before rendering them. */ async function prepareWatchedSessionsHarnessContext(e) { const t = await prepareWatchedSessionsPromptAsync({ enabled: true, ...e }); e.assertCurrent(); const n = buildWatchedSessionsPromptLines(t); return n.length > 0 ? n.join("\n").trimEnd() : void 0; } const agentHarnessAttemptTerminal = { merge: mergeAgentRunAttemptTerminal, normalize: normalizeAgentRunAttemptTerminal, project: projectAgentRunAttemptTerminal, setFailure: setAgentRunAttemptTerminalFailure }; /** Bounded structured-input compilation and execution for native agent harnesses. */ const agentHarnessStructuredInput = Object.freeze({ compileForm: compileStructuredInputForm, compileQuestions: compileStructuredInputQuestions, compileUrl: compileStructuredInputUrl, isRecord: isStructuredInputRecord, run: runStructuredInput, snapshot: snapshotStructuredInput }); /** Registers within the host-bound attempt and returns cleanup for this exact native run. */ function setActiveEmbeddedRun(e, t, n, r, i) { const a = attachActiveEmbeddedRun(e, t, n, r, i); if (!a) return; return (i) => detachActiveEmbeddedRun(e, t, n, r, i, a); } /** A retained cleanup closes only its captured run, including after a successor registers. */ function clearActiveEmbeddedRun(e, t, n, r, i = "run_completed", a) { if (a) a(i); else detachActiveEmbeddedRun(e, t, n, r, i); } /** * @deprecated Active-run queueing is an internal runtime concern. This legacy * boolean API reports whether the active turn or sessionless native sink could * take input now; it cannot observe the later outcome and never retries a refusal. */ function queueAgentHarnessMessage(e, t, n) { const r = resolveActiveReplyOperationForSessionId(e); if (!r) return queueDetachedEmbeddedAgentMessage(e, t, n); const i = captureReplyMessageInjectionTarget(r); if (!i || !canInjectReplyMessageTarget(i, n)) return false; steerSessionControllerOperation({ operation: r, text: t, options: n ?? { steeringMode: "all" }, abortOnUnconfirmedTranscript: false }).then((t) => { if (t.status === "indeterminate") log$2.warn(`queue message outcome unconfirmed: sessionId=${e}; inspect the conversation before retrying`); else if (t.status !== "accepted") log$2.warn(`queue message not accepted: sessionId=${e} status=${t.status}`); }, (t) => log$2.warn(`queue message rejected: sessionId=${e} err=${formatErrorMessage(t)}`)); return true; } /** Detect prompt image references and load them through the same limits used by embedded runs. */ async function detectAndLoadAgentHarnessPromptImages(e) { const [{ resolveImageSanitizationLimits: t }, { detectAndLoadPromptImages: n }, { MAX_IMAGE_BYTES: r }] = await Promise.all([ import("./image-sanitization-nfpBrzKk.mjs"), import("./images-DOXZfEuR.mjs"), import("./media-core/constants.js") ]); return n({ prompt: e.prompt, workspaceDir: e.workspaceDir, agentWorkspaceDir: e.agentWorkspaceDir, model: e.model, existingImages: e.existingImages, imageOrder: e.imageOrder, media: e.media, userTurnTranscriptRecorder: e.userTurnTranscriptRecorder, maxBytes: r, maxDimensionPx: t(e.config).maxDimensionPx, workspaceOnly: e.workspaceOnly, localRoots: e.localRoots, sandbox: e.sandbox }); } /** Load static MCP metadata without connecting transports or discovering tools. */ async function loadAgentHarnessMcpConfig(e) { const { loadStaticBundleMcpConfig: t } = await import("./bundle-mcp-config-_Mp4syoU.mjs"); return t(e); } /** Load Codex bundle MCP thread config without forcing the heavy config module into SDK imports. */ async function loadCodexBundleMcpThreadConfig(e) { const { loadCodexBundleMcpThreadConfigCore: t } = await import("./codex-mcp-config-C--6O58W.mjs"); return t(e); } /** Lazily load the strict MCP proxy client with core-owned framing, startup, and shutdown. */ const mcpStdioRuntime = Object.freeze({ async load() { const { createMcpStdioClient: e } = await import("./mcp-stdio-client-J0oN0TzI.mjs"); return { createMcpStdioClient: e }; } }); /** * Materialize an MCP App view for a tool executed by a harness-native MCP client. * The harness supplies a runtime adapter so the view keeps using that exact connection. */ async function prepareHarnessNativeMcpAppPreview(e) { if (e.runtime.mcpAppsEnabled !== true) return; const { buildMcpAppCanvasPayload: t, fetchMcpAppView: n } = await import("./mcp-ui-resource-De9UMO3p.mjs"); const { prepareMcpAppFormUpload: r } = await import("./mcp-form-resource-upload-BRC1F9Tj.mjs"); const i = await n({ runtime: e.runtime, requesterId: e.runtime.appRequester?.profileId, uploadResources: e.agentId && e.runtime.sessionKey ? await r({ runtime: e.runtime, serverName: e.serverName, agentId: e.agentId, sessionKey: e.runtime.sessionKey, assertCurrent: () => { e.runtime.assertOwnerCurrent?.(); } }) : void 0, agentId: e.agentId, serverName: e.serverName, toolName: e.toolName, uiResourceUri: e.uiResourceUri, toolCallId: e.toolCallId, toolInput: e.toolInput, toolResult: e.toolResult, allowedAppToolNames: e.allowedAppToolNames }); if (!i) return; return { mcpAppPreview: t({ ...i, ...e.runtime.sessionKey ? { originSessionKey: e.runtime.sessionKey } : {}, ...e.resultMetaState ? { resultMetaState: e.resultMetaState } : {} }) }; } /** * Materialize requester-scoped MCP tools for a harness run (dynamic tools, not * harness-native MCP config). Lazy-loaded so harness plugins avoid the MCP manager graph. */ async function materializeRequesterScopedMcpToolsForHarnessRun(e) { if (!shouldLoadRequesterScopedMcpHarnessRuntime(e)) return; const { materializeRequesterScopedMcpToolsForHarnessRunCore: t } = await import("./agent-bundle-mcp-harness-DtY2puMp.mjs"); return t(e); } /** * Classify terminal harness turns that completed without assistant output that * should advance fallback. Deliberate silent replies such as NO_REPLY count as * intentional output, while whitespace-only text remains fallback-eligible. */ function classifyAgentHarnessTerminalOutcome(e) { if (!e.turnCompleted || e.promptError !== void 0 && e.promptError !== null || e.assistantTexts.some((e) => e.trim().length > 0)) return; if (e.planText?.trim()) return "planning-only"; if (e.reasoningText?.trim()) return "reasoning-only"; return "empty"; } const toolPolicy = Object.freeze({ createToolPolicyMatcher, expandToolGroups }); //#endregion export { resolveSessionWriteLockOptions as C, resolveAgentExecutorController as E, resolveSessionWriteLockAcquireTimeoutMs as S, buildAgentWorkspaceInstructionSnapshot as T, createCodexAppServerToolResultExtensionRunner as _, clearActiveEmbeddedRun as a, runAgentHarnessBeforeCompactionHook as b, loadAgentHarnessMcpConfig as c, mcpStdioRuntime as d, prepareHarnessNativeMcpAppPreview as f, toolPolicy as g, setActiveEmbeddedRun as h, classifyAgentHarnessTerminalOutcome as i, loadCodexBundleMcpThreadConfig as l, queueAgentHarnessMessage as m, agentHarnessStructuredInput as n, detectAndLoadAgentHarnessPromptImages as o, prepareWatchedSessionsHarnessContext as p, buildWatchedSessionsHarnessContext as r, execPolicy as s, agentHarnessAttemptTerminal as t, materializeRequesterScopedMcpToolsForHarnessRun as u, resolveAgentHarnessBeforePromptBuildResult as v, prepareAgentWorkspaceContext as w, acquireSessionWriteLock as x, runAgentHarnessAfterCompactionHook as y };