openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
29 lines (28 loc) • 26.6 kB
JavaScript
import"./utils-Dlk0IYAa.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import"./session-key-BPgKfU2m.mjs";import"./usage-BBN9S-zv.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import"./version-DrZ9Nfde.mjs";import{i as expandToolGroups}from"./tool-policy-shared-KKJW93v9.mjs";import{u as getPluginValueInstance}from"./plugin-instance-scope-Bx-frH07.mjs";import"./agent-scope-Dw5XRSEh.mjs";import"./agent-events-Dz03BVGI.mjs";import{u as resolveExecModePolicy}from"./exec-approvals-core-BZ6-zeZE.mjs";import{t as warnPluginSdkDeprecation}from"./sdk-deprecation-BDUCyBrU.mjs";import{O as createMessageInjectionAuthority}from"./session-transcript-read-fence-DE07xwTs.mjs";import{d as setAgentRunAttemptTerminalFailure,l as normalizeAgentRunAttemptTerminal,s as mergeAgentRunAttemptTerminal,u as projectAgentRunAttemptTerminal}from"./agent-run-terminal-outcome-WJ5SKlfk.mjs";import"./run-termination-vr_m9wT0.mjs";import{a as logMessageQueuedWithBacklogPolicy,t as diagnosticLogger}from"./diagnostic-runtime-QyRFQxNU.mjs";import{St as resolveReplyRunForCurrentSessionId,nt as resolveEmbeddedRunCompactionSteeringRejection}from"./session-controller.state-BIDbpLPn.mjs";import{r as createToolPolicyMatcher}from"./tool-policy-match-D9XrfLbh.mjs";import"./reply-payload-C7eQHHoS.mjs";import{n as maxAsk,r as minSecurity}from"./exec-approvals-policy-DUqwCsoC.mjs";import"./internal-runtime-context-DervRrPi.mjs";import"./agent-run-terminal-reply-DTaPwlVH.mjs";import"./tool-metadata-Cb5nBZYD.mjs";import"./agent-tool-availability-DAMoDFPF.mjs";import"./agent-tool-metadata-D7ctyGhj.mjs";import{f as getDetachedNativeAttachment,y as resolveRegisteredEmbeddedRunRecoveryBlocker}from"./run-state-Bd0P0LYH.mjs";import"./errors-BBEItQ0m.mjs";import"./user-turn-transcript.metadata-BLFL_nrT.mjs";import{n as getGlobalHookRunner}from"./hook-runner-global-DNCi6wD6.mjs";import{g as joinPresentTextSegments}from"./hooks-Bu2gwS_g.mjs";import"./hook-helpers-Dmbt-AJr.mjs";import"./registry-BzjsVuM_.mjs";import"./provider-request-config-BQ-HhEKu.mjs";import{D as PluginCapabilityRemovedError}from"./loader-runtime-load-CVvaB9FO.mjs";import"./registry-97OPYdf3.mjs";import{s as resolveActiveReplyOperationForSessionId}from"./session-controller.queries-CBzzV0sx.mjs";import"./compaction-safety-timeout-BnvorGSI.mjs";import{g as resolveRunStaleThresholdMs,i as getDiagnosticSessionActivitySnapshot}from"./diagnostic-run-activity-D_NQZV7c.mjs";import"./streaming-directives-CDSgGEl1.mjs";import"./agent-activity-presentation-DRE2_NwF.mjs";import{n as isRestartEnabled}from"./commands.flags-BdxOktqL.mjs";import{o as shouldLoadRequesterScopedMcpHarnessRuntime}from"./agent-bundle-mcp-runtime-shared-CjKU-8u7.mjs";import"./run-cleanup-timeout-B__J_Jbc.mjs";import"./tool-execution-error-C60NwMfa.mjs";import"./gateway-Bf9f0Pcc.mjs";import"./tool-mutation-CL1BUV0M.mjs";import"./agent-tools.before-tool-call-BkUHN8cH.mjs";import"./date-time-j3BuJvYF.mjs";import"./in-process-gateway-vrnZpIbq.mjs";import"./fs-paths-Djl1qCxq.mjs";import{t as log$2}from"./logger-DQkQvjpf.mjs";import"./gateway-question-D7tCGbpy.mjs";import"./ask-user-tool-normalization-CcFcHNUN.mjs";import"./tool-display-zqIugQbc.mjs";import"./tool-meta-WYsW8brn.mjs";import{n as bindMessageInjectionV2}from"./tool-authority-preparation-Dgurlhwb.mjs";import{c as captureReplyMessageInjectionTarget,d as resolveReplyBackendQueueMessageMismatch,i as steerSessionControllerOperation,u as canInjectReplyMessageTarget}from"./session-controller.steer-BUP3NUvG.mjs";import"./agent-activity-events-B_8ZX8AG.mjs";import{r as prepareMemorySystemPromptAddition}from"./delegate-BVTRz_Yj.mjs";import"./agent-scope-runtime-DKb8jQZx.mjs";import"./model-auth-C99Q9Dp8.mjs";import{i as buildCurrentInboundPrompt}from"./runtime-context-prompt-DXcCUB0U.mjs";import"./execution-auth-binding-Dm4-AGVF.mjs";import{t as describeSystemAgentConfigConflict}from"./setup-config-snapshot-jjSVOI2V.mjs";import{r as buildBootstrapContextForFiles}from"./bootstrap-CbSK3Geh.mjs";import{s as resolveBootstrapFilesForRun}from"./bootstrap-files-S_tG2cje.mjs";import"./attempt-tool-construction-plan-DxPA0wqy.mjs";import{i as attachActiveEmbeddedRun,o as detachActiveEmbeddedRun}from"./runs-CZphmRD3.mjs";import"./embedded-agent-messaging-CINcI8mM.mjs";import"./source-reply-delivery-mode-B6NT-zZ-.mjs";import"./agent-tools.ring-zero-context-Cx1ZbLhY.mjs";import"./tool-schema-projection-B9L3KtZf.mjs";import"./embedded-agent-tool-results-BPxGp984.mjs";import"./embedded-agent-tool-media-C5KZzCKb.mjs";import"./embedded-agent-message-delivery-Cz7gntl-.mjs";import"./embedded-agent-message-tool-source-reply-B0kDxgIC.mjs";import"./tool-result-middleware-DoY1jd_B.mjs";import"./tool-schema-runtime-CTnfYrs1.mjs";import"./tools-CXr38coz.mjs";import"./prepare-auth-CkYiXkUT.mjs";import"./settled-turn-finalization-result-CorT8Zjk.mjs";import{n as resolvePluginTurnContext}from"./plugin-turn-context-BjJCWA-U.mjs";import"./result-fallback-classifier-BEbg4LTQ.mjs";import"./native-hook-relay-BIifn17Q.mjs";import{t as buildAgentHookContext}from"./hook-context-_8kE45xt.mjs";import"./lifecycle-hook-helpers-DAwdEHdy.mjs";import{a as isStructuredInputRecord,i as compileStructuredInputUrl,n as compileStructuredInputForm,o as snapshotStructuredInput,r as compileStructuredInputQuestions}from"./structured-input-IRKLb0KH.mjs";import{t as runStructuredInput}from"./structured-input-execution-U1TcGUJU.mjs";import{S as prepareWatchedSessionsPromptAsync,a as buildCareSection,b as buildWatchedSessionsPromptLines,c as buildRuntimeContextSection,d as buildDocumentationSection,i as prepareContextFilesForPrompt,l as buildToolCallStyleSection,m as buildPromisedWorkPromptSection,o as buildExecutionBiasSection,p as buildOpenClawControlSection,s as buildMediaGenerationToolLines,t as PERSONAL_USER_CONTEXT_INSTRUCTIONS,u as normalizeProviderPromptBlock,x as prepareWatchedSessionsPrompt,y as listToolPromptGuidance}from"./system-prompt-context-files-Bwkek5HW.mjs";import"./projection-tool-output-BncHK8p_.mjs";import"./progress-card-channel-summary-CaUElkwI.mjs";import"./transcript-visibility-CGpCtEBl.mjs";import"./build-CzoGV_b_.mjs";import"./nodes-utils-Bgm8PZ2e.mjs";import"./embedded-agent-messaging-extraction-DtyqGTJA.mjs";import"./embedded-agent-tool-authored-source-reply-C0f9VUsf.mjs";import{c as wrapPluginSystemContextSection}from"./attempt-prompt-helpers-BKNt63-m.mjs";import"./attempt-thread-helpers-D30aNYYy.mjs";import"./attempt-tool-run-context-DKEycYln.mjs";import"./context-DCVJxJ3r.mjs";import"./preemptive-compaction-QUOUkRYE.mjs";import"./context-engine-lifecycle-C67B7oZM.mjs";import"./agent-end-side-effects-CMfnObwv.mjs";import path from"node:path";
//!src/agents/embedded-agent-runner/runs.message-injection.ts
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())||resolveEmbeddedRunCompactionSteeringRejection(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}
//!src/agents/harness/deprecated-skill-workshop-prompt.ts
const DEPRECATED_SKILL_WORKSHOP_TOOL_NAME=`skill_workshop`;function buildDeprecatedSkillWorkshopPromptSection(){return[`## Skill Workshop`,"`skill_workshop` edits your learned skills: procedures for tasks this user repeats, so you do not work them out from scratch again. When a learned skill you used was wrong or incomplete, view it and patch the misleading step. After hard multi-step work the user will repeat, save the working procedure: patch the skill that covers it or create one. Knowledge about one codebase belongs in that repository's docs or AGENTS.md, not a learned skill. Every change keeps the previous version. When the user says undo right after a 💾 Learned notice, they mean that skill change: restore the named skill, or archive it if the notice says it was created.","Skills the user owns (repository or workspace `skills/`, `.agents/skills/`, configured skill dirs) are ordinary files: edit them directly when asked, never through skill_workshop.",``]}
//!src/plugins/agent-executor-controller.ts
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.`)}
//!src/agents/system-prompt-harness-base.ts
const HARNESS_IDENTITY=`You are a personal assistant running inside OpenClaw.`;function buildAgentHarnessBasePrompt(e){const t=e.promptMode??`full`;if(t===`none`)return HARNESS_IDENTITY;const n=t===`minimal`;const r=new Set([...e.toolNames].map(e=>e.trim().toLowerCase()));const i=e.promptContribution?.sectionOverrides;const a=listToolPromptGuidance(r);return[[HARNESS_IDENTITY,``],[normalizeProviderPromptBlock(i?.interaction_style)],normalizeProviderPromptBlock(i?.execution_bias)?[normalizeProviderPromptBlock(i?.execution_bias)]:n?[]:buildExecutionBiasSection(),buildPromisedWorkPromptSection(),[normalizeProviderPromptBlock(e.promptContribution?.stablePrefix)],buildRuntimeContextSection(),[``],e.nativeCommandGuidanceLines??[],r.has(`process`)?[`Before input: process log; log/poll shows waitingForInput/stdinWritable. Lost id: process list.`]:[],r.has(`sessions_spawn`)?[`Follow each spawn's accepted completion mode: collectors need explicit result collection, not completion events.`,`Treat subagent outputs as reports to synthesize.`]:[],buildMediaGenerationToolLines(r),[``],normalizeProviderPromptBlock(i?.tool_call_style)?[normalizeProviderPromptBlock(i?.tool_call_style)]:!n||r.size>0?buildToolCallStyleSection():[],buildCareSection({controlToolsAvailable:r.has(`openclaw`)||r.has(`gateway`)}),buildOpenClawControlSection({setupIssue:e.config?describeSystemAgentConfigConflict(e.config):void 0,hasOpenClaw:r.has(`openclaw`),hasGateway:r.has(`gateway`),hasExec:r.has(`exec`),restartCommandsEnabled:e.config?isRestartEnabled(e.config):true}),a.flatMap(e=>[e,``]),n?[]:buildDocumentationSection({availableTools:r,sandboxed:false})].flat().filter(e=>e!==void 0&&e!==false).join(`
`).replace(/\n{3,}/g,`
`).trim()}
//!src/agents/harness/workspace-instructions.ts
function buildAgentWorkspaceInstructionSnapshot(e,t){return renderAgentWorkspaceInstructionSnapshot(selectAgentWorkspaceInstructionFiles(e,t))}function renderAgentWorkspaceInstructionSnapshot(e){const t=e.filter(e=>!e.content.trimStart().startsWith(`[MISSING] Expected at:`)&&e.content.trim().length>0);if(t.length===0)return{files:t,instructions:``};const n=[`## OpenClaw Agent Workspace Instructions`,``,`OpenClaw loaded this bounded snapshot from the configured agent workspace.`,``];for(const e of t)n.push(`### ${e.path}`,``,e.content,``);return{files:t,instructions:n.join(`
`).trim()}}function selectAgentWorkspaceInstructionFiles(e,t){const n=path.join(path.resolve(t),`AGENTS.md`);return e.filter(e=>path.resolve(e.path)===n)}
//!src/agents/harness/workspace-context.ts
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=[];const s=buildBootstrapContextForFiles(a,e).map(t=>{const n=projectContextFile(t,e.projectPath);if(selectAgentWorkspaceInstructionFiles([t],e.workspaceDir).length>0)o.push(n);return n});const c=renderAgentWorkspaceInstructionSnapshot(o);if(n)return{bootstrapFiles:t,contextFiles:s,instructionSnapshot:c,personaFiles:[],promptContextFiles:[],memoryReferenceFiles:[],memoryToolRoutedBootstrapFiles:[]};const l=sortContextFiles(s.filter(e=>PERSONA_FILE_BASENAMES.has(contextFileBasename(e.path))&&!isMissingContextFile(e)&&e.content.trim().length>0),e.contextFileOrder);const u=sortContextFiles(s.filter(t=>{const n=contextFileBasename(t.path);const i=e.nativeProjectDocBasenames?e.nativeProjectDocBasenames.has(n):o.includes(t);return n.length>0&&!i&&!PERSONA_FILE_BASENAMES.has(n)&&(!r||!isRootMemoryPath(t.path,e.promptMemoryWorkspaceDir??e.workspaceDir))&&!isMissingContextFile(t)}),e.contextFileOrder);const d=i.map(t=>projectContextFile(toContextFile(t),e.projectPath));const f=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:s,instructionSnapshot:c,personaFiles:l,personaInstructions:renderPersonaInstructions(l),sharedPersonaInstructions:renderPersonaInstructions(l.filter(e=>e.personalUser!==true)),promptContextFiles:u,memoryReferenceFiles:d,memoryToolRoutedBootstrapFiles:i,memoryRecallInstructions:f}}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(`
`).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:`)}
//!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;function resolveSessionWriteLockAcquireTimeoutMs(e,t){return DEFAULT_SESSION_WRITE_LOCK_ACQUIRE_TIMEOUT_MS}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}}async function acquireSessionWriteLock(e){return{assertOwned:()=>void 0,release:async()=>void 0}}
//!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(`
`):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,...e.continuity?{continuity:e.continuity}:{}},i,{toolAuthorityFingerprint:p,activeToolNames:f.activeToolNames(),assertHostActive:f.assertActive}).catch(warnHookFailure(`authorized before_prompt_build`)):void 0;const h=u?.systemPrompt;const g=typeof h===`string`;const _=g?h:d;const v=joinPresentTextSegments([l.prependContext,u?.prependContext,m?.prependContext]);const y=joinPresentTextSegments([l.appendContext,u?.appendContext,m?.appendContext]);const b=joinPresentTextSegments([v,t,y])??t;const x=t.length===0?v?.length??0:v?v.length+2:0;const S=wrapPluginSystemContextSection(u?.prependSystemContext);const C=wrapPluginSystemContextSection(u?.appendSystemContext);const w=joinPresentTextSegments([S,C]);return{prompt:b,...u?.toolsAllow!==void 0?{toolsAllow:u.toolsAllow}:{},developerInstructions:joinPresentTextSegments([S,_,C])??_,...g?{systemPromptReplaced:true}:{},...w?{threadDeveloperInstructions:_,turnDeveloperInstructions:w}:{},promptInputRange:{start:x,end:x+t.length}}}function resolveDeveloperInstructions(e,t){return typeof e===`string`?e:e.build({toolsAllow:t,hasToolRestrictions:t!==void 0&&!t.some(e=>e.trim()===`*`)})??``}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)}`)}}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)}`)}}
//!src/agents/harness/codex-app-server-extensions.ts
const log=createSubsystemLogger(`agents/harness`);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}}}
//!src/plugin-sdk/agent-harness-runtime.ts
const execPolicy=Object.freeze({resolveExecModePolicy,minSecurity,maxAsk});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(`
`).trimEnd():void 0}async function prepareWatchedSessionsHarnessContext(e){const t=await prepareWatchedSessionsPromptAsync({enabled:true,...e});e.assertCurrent();const n=buildWatchedSessionsPromptLines(t);return n.length>0?n.join(`
`).trimEnd():void 0}const agentHarnessAttemptTerminal={merge:mergeAgentRunAttemptTerminal,normalize:normalizeAgentRunAttemptTerminal,project:projectAgentRunAttemptTerminal,setFailure:setAgentRunAttemptTerminalFailure};const agentHarnessStructuredInput=Object.freeze({compileForm:compileStructuredInputForm,compileQuestions:compileStructuredInputQuestions,compileUrl:compileStructuredInputUrl,isRecord:isStructuredInputRecord,run:runStructuredInput,snapshot:snapshotStructuredInput});const SKILL_WORKSHOP_TOOL_NAME=DEPRECATED_SKILL_WORKSHOP_TOOL_NAME;const buildSkillWorkshopPromptSection=buildDeprecatedSkillWorkshopPromptSection;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)}function clearActiveEmbeddedRun(e,t,n,r,i=`run_completed`,a){if(a)a(i);else detachActiveEmbeddedRun(e,t,n,r,i)}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}async function detectAndLoadAgentHarnessPromptImages(e){const[{resolveImageSanitizationLimits:t},{detectAndLoadPromptImages:n},{MAX_IMAGE_BYTES:r}]=await Promise.all([import(`./image-sanitization-CRNDmdxJ.mjs`),import(`./images-CEQy5rfe.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})}async function loadAgentHarnessMcpConfig(e){const{loadStaticBundleMcpConfig:t}=await import(`./bundle-mcp-config-BFjrxZ8f.mjs`);return t(e)}async function loadCodexBundleMcpThreadConfig(e){const{loadCodexBundleMcpThreadConfigCore:t}=await import(`./codex-mcp-config-C2G4tqQs.mjs`);return t(e)}const mcpStdioRuntime=Object.freeze({async load(){const{createMcpStdioClient:e}=await import(`./mcp-stdio-client-BGooxj9C.mjs`);return{createMcpStdioClient:e}}});async function prepareHarnessNativeMcpAppPreview(e){if(e.runtime.mcpAppsEnabled!==true)return;const{buildMcpAppCanvasPayload:t,fetchMcpAppView:n}=await import(`./mcp-ui-resource-XRYKYV2o.mjs`);const{prepareMcpAppFormUpload:r}=await import(`./mcp-form-resource-upload-ByQAfv5W.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}:{}})}}async function materializeRequesterScopedMcpToolsForHarnessRun(e){if(!shouldLoadRequesterScopedMcpHarnessRuntime(e))return;const{materializeRequesterScopedMcpToolsForHarnessRunCore:t}=await import(`./agent-bundle-mcp-harness-DF5zqdwr.mjs`);return t(e)}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});export{acquireSessionWriteLock as C,buildAgentWorkspaceInstructionSnapshot as D,prepareAgentWorkspaceContext as E,buildAgentHarnessBasePrompt as O,runAgentHarnessBeforeCompactionHook as S,resolveSessionWriteLockOptions as T,setActiveEmbeddedRun as _,buildWatchedSessionsHarnessContext as a,resolveAgentHarnessBeforePromptBuildResult as b,detectAndLoadAgentHarnessPromptImages as c,loadCodexBundleMcpThreadConfig as d,materializeRequesterScopedMcpToolsForHarnessRun as f,queueAgentHarnessMessage as g,prepareWatchedSessionsHarnessContext as h,buildSkillWorkshopPromptSection as i,resolveAgentExecutorController as k,execPolicy as l,prepareHarnessNativeMcpAppPreview as m,agentHarnessAttemptTerminal as n,classifyAgentHarnessTerminalOutcome as o,mcpStdioRuntime as p,agentHarnessStructuredInput as r,clearActiveEmbeddedRun as s,SKILL_WORKSHOP_TOOL_NAME as t,loadAgentHarnessMcpConfig as u,toolPolicy as v,resolveSessionWriteLockAcquireTimeoutMs as w,runAgentHarnessAfterCompactionHook as x,createCodexAppServerToolResultExtensionRunner as y};