openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
43 lines • 55.4 kB
JavaScript
import{x as parseDateFirstTimestampMs}from"./number-coercion-B3CfI447.mjs";import{n as coerceErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{n as sliceUtf16Safe,r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as freezeJsonSnapshot}from"./immutable-data-CyaF4H_G.mjs";import{i as throwCollectedErrors}from"./error-graph-internal-Bt2pFJBM.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{E as walkDirectorySync}from"./fs-safe-Bxzu1j4h.mjs";import{r as isErrno}from"./errno-DUBt6SQQ.mjs";import{n as notifyListeners,r as registerListener}from"./listeners-awzYn4LE.mjs";import{l as makeZeroUsageSnapshot}from"./usage-BBN9S-zv.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as getProcessInstanceStartTime}from"./pid-alive-DDtSxW5l.mjs";import{a as hasCommandProcessCleanupError,t as CommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{t as GRACEFUL_CANCEL_TIMEOUT_MS}from"./cancellation-policy-BNa0Y54K.mjs";import{r as scheduleAbsoluteDeadline}from"./absolute-deadline-CE14TWdo.mjs";import{t as createWindowsOutputDecoder}from"./windows-encoding-hfsJ5_F8.mjs";import{a as createChildProcessOutputRelease}from"./exec-runner-BiCq-T1F.mjs";import{a as resolveCommandProcessSignal,i as resolveCommandEnv,o as retainCommandProcessCleanup,r as reserveCommandProcessCustody}from"./exec-spawn-DNCbDcyJ.mjs";import{A as withMessageInjectionAdmission,k as enqueueMessageInjection,x as MessageInjectionClosedError,y as MessageInjectionAcceptedUnconfirmedError}from"./session-transcript-read-fence-DE07xwTs.mjs";import{i as sameSessionTranscriptTargetBinding}from"./transcript-target-binding-CvS-QwUa.mjs";import{r as AGENT_RUN_RESTART_ABORT_ERROR_CODE}from"./run-termination-vr_m9wT0.mjs";import{o as annotateInterSessionPromptText}from"./input-provenance-TIcSrNt5.mjs";import{n as isOwnedTranscriptPayload}from"./transcript-payload-ownership-BdmEHknN.mjs";import{t as cloneTranscriptView}from"./transcript-snapshot-BE7v4A1W.mjs";import{r as attachRuntimePromptMediaFacts}from"./media-facts-03ZYaqC1.mjs";import{a as orderSystemUpdateMessages,r as isOpenClawSystemUpdateMessage}from"./operator-messages-CbMjNH4-.mjs";import{d as resolvePendingRuntimeContextReplay}from"./internal-runtime-context-DervRrPi.mjs";import{u as copyInternalToolResultState,x as setInternalBeforeRequest}from"./internal-hooks-Bn77tst6.mjs";import{a as gateAgentToolExecution}from"./agent-tool-availability-DAMoDFPF.mjs";import{c as substituteArgs,s as parseCommandArgs}from"./agent-core-9_CCYFLw.mjs";import{o as mergePreparedUserTurnMessageForRuntime,u as readModelPromptProjection}from"./user-turn-transcript.message-D0W4EzXs.mjs";import{i as rethrowIncognitoSessionError}from"./incognito-session-error-ClXAatS2.mjs";import{t as warnSessionPersistenceDeprecation}from"./session-persistence-deprecation--5O4MOIT.mjs";import{m as withOwnedSessionRestartAbortWrite,y as withSessionTranscriptWriteAssertion}from"./transcript-write-context-Z5Jo6xkS.mjs";import{t as isToolResultError}from"./tool-result-error-DAdEhHzf.mjs";import{t as applyAssistantDeliveryDirectives}from"./transcript-assistant-delivery-D7YdegBt.mjs";import{t as createChildAdapter}from"./child-DgxjWdrb.mjs";import{s as getStreamLlmRuntime}from"./model-runtime-binding-C5v05rsT.mjs";import{t as getModelRegistryRuntime}from"./model-registry-runtime-VNuLOQ9O.mjs";import{t as extractFrontmatterBlock}from"./frontmatter-juE3lAL1.mjs";import{n as createSyntheticSourceInfo}from"./source-info-gZY9Wjux.mjs";import{f as shouldRetainSteeringRuntimeContext,r as attachSteeringRuntimeContext,s as getSteeringRuntimeContext}from"./runtime-context-prompt-DXcCUB0U.mjs";import{t as createSessionManagerRuntimeRegistry}from"./session-manager-runtime-registry-rg1NipV6.mjs";import{n as stripStaleThinkingSignaturesForCompactionReplay}from"./thinking-signatures-BC9s1Ty-.mjs";import{n as readRuntimePromptImageFactIndexes}from"./runtime-prompt-image-provenance-CSbvcej4.mjs";import{t as attachRuntimeUserTurnTranscriptContext}from"./user-turn-transcript-runtime-context-BjcGASZh.mjs";import{a as replaceAgentMessageInPlace}from"./agent-session-utils-CZDU0aSq.mjs";import{n as CONFIG_DIR_NAME,r as getDocsPath}from"./package-metadata-DjdTQ5ic.mjs";import{b as SessionMetadataCommittedError,g as withSessionManagerAppend,v as getModelPromptProjectionAppend,y as sessionManagerAppendPromptContext}from"./session-manager-BPWwNp25.mjs";import{a as withSessionManagerWriteAssertion}from"./session-manager-write-admission-BTbqq72O.mjs";import{s as interactiveAgentTheme}from"./ignore-rules-D18czU9G.mjs";import{i as createCompactionRequestBudget,l as takePromptCompactionRequestBudget,u as withCompactionQueuedContext}from"./request-budget-BGnBCeSF.mjs";import{readFileSync,statSync}from"node:fs";import*as path$1 from"node:path";import{basename,dirname,isAbsolute,join,resolve}from"node:path";import{homedir}from"node:os";import{parse as parse$1}from"yaml";import{cleanupSessionResources}from"@openclaw/ai/internal/runtime";
//!src/agents/compaction-usage.ts
function stripStaleAssistantUsageBeforeLatestCompaction(e,t={}){const n=e.findLastIndex(e=>e?.role===`compactionSummary`);const r=n!==-1;if(!r&&t.whenMissingCompactionSummary!==`zeroAssistantUsage`)return e;const i=parseDateFirstTimestampMs(e[n]?.timestamp);let a=e;for(let o=0;o<e.length;o+=1){const s=e[o];if(s?.role!==`assistant`||!s.usage||typeof s.usage!==`object`)continue;const c=parseDateFirstTimestampMs(s.timestamp);if(!(!r||(i!==void 0&&c!==void 0?c<=i:o<n)))continue;if(a===e&&!t.mutate)a=[...e];a[o]={...s,usage:makeZeroUsageSnapshot()}}return a}
//!src/agents/compaction-replay.ts
function sanitizeCompactionReplayMessages(e){return stripStaleThinkingSignaturesForCompactionReplay(stripStaleAssistantUsageBeforeLatestCompaction(e))}
//!src/agents/utils/frontmatter.ts
const normalizeNewlines=e=>e.replace(/\r\n/g,`
`).replace(/\r/g,`
`);const parsePromptFrontmatter=e=>{const t=normalizeNewlines(e);const n=extractFrontmatterBlock(t);if(!n)return{frontmatter:{},body:t};return{frontmatter:parse$1(n.block)??{},body:n.body.trim()}};const stripFrontmatter=e=>parsePromptFrontmatter(e).body;
//!src/agents/sessions/agent-session-transcript.ts
async function persistAgentSessionMessage(e,t,n){applyAssistantDeliveryDirectives(t);const r={invalidateSerializedPrefixCache:n.invalidateSerializedPrefixCache};const append=()=>e.appendMessageAsync(t,r);const i=t.role===`assistant`&&(t.stopReason===`aborted`||t.stopReason===`error`)&&t.errorCode===`OPENCLAW_RESTART_ABORT`?await withOwnedSessionRestartAbortWrite(e.getSessionTarget(),append):await append();if(t.role===`assistant`&&!isOwnedTranscriptPayload(t))freezeJsonSnapshot(t);return i}
//!src/agents/sessions/auth-guidance.ts
const UNKNOWN_PROVIDER=`unknown`;function getProviderLoginHelp(){return[`Use /login to log into a provider via OAuth or API key. See:`,` ${join(getDocsPath(),`providers.md`)}`,` ${join(getDocsPath(),`models.md`)}`].join(`
`)}function formatNoModelSelectedMessage(){return`No model selected.\n\n${getProviderLoginHelp()}\n\nThen use /model to select a model.`}function formatNoApiKeyFoundMessage(e){return`No API key found for ${e===UNKNOWN_PROVIDER?`the selected model`:e}.\n\n${getProviderLoginHelp()}`}
//!src/agents/sessions/exec.ts
const DEFAULT_OUTPUT_LIMIT_CHARS=16777216;function decodeCapturedOutput(e,t){return Buffer.isBuffer(t)?e.decode(t):`${e.flush()}${t}`}function clampMaxOutputChars(e){if(typeof e!==`number`||!Number.isFinite(e)||e<=0)return DEFAULT_OUTPUT_LIMIT_CHARS;return Math.max(1,Math.floor(e))}function appendCapturedOutput(e,t,n,r){const i=`${e.text}${t}`;const a=Math.max(0,i.length-n);const o=a===0?i:r?sliceUtf16Safe(i,a):sliceUtf16Safe(i,0,n);return{text:o,truncatedChars:e.truncatedChars+i.length-o.length}}async function execCommand(e,t,n,r){const i=[e,...t];const a=reserveCommandProcessCustody(i);const o=resolveCommandProcessSignal();const s=resolveCommandProcessSignal(r?.signal);const c=new AbortController;const l=createDeferredCore();const u=createDeferredCore();retainCommandProcessCleanup(u.promise);u.promise.catch(()=>{});let d;let f;let p;let m=true;let h=true;let g=false;let _=false;let v=false;let y;const stopAdapter=()=>{if(d&&!v){v=true;d.kill(`SIGTERM`);if(process.platform===`win32`)y=scheduleAbsoluteDeadline(performance.now()+GRACEFUL_CANCEL_TIMEOUT_MS,()=>d?.kill(`SIGKILL`),()=>performance.now())}};let b;const killProcess=()=>{if(g)return;g=true;c.abort();stopAdapter();if(m)l.resolve({stdout:``,stderr:``,code:1,killed:true})};o?.addEventListener(`abort`,killProcess,{once:true});r?.signal?.addEventListener(`abort`,killProcess,{once:true});const x=r?.timeout&&r.timeout>0?scheduleAbsoluteDeadline(performance.now()+r.timeout,killProcess,()=>performance.now()):void 0;const S=(async()=>{try{const e=await createChildAdapter({executionIntent:`agent-tool`,argv:i,cwd:n,env:resolveCommandEnv({argv:i}),exactEnv:true,ownProcessTree:true,stdinMode:`pipe-closed`,abortSignal:c.signal,assertCurrent:()=>s?.throwIfAborted(),onSpawnCleanup:e=>{f=e}});d=e.adapter;const t={stdout:{text:``,truncatedChars:0},stderr:{text:``,truncatedChars:0}};const o={stdout:createWindowsOutputDecoder({preserveUtf8Bom:true}),stderr:createWindowsOutputDecoder({preserveUtf8Bom:true})};const l=createDeferredCore();let u;const _=createChildProcessOutputRelease(()=>l.resolve(u));b=_.dispose;d.onExit?.((e,t)=>{u={code:e,signal:t};_.onExit()});const v=clampMaxOutputChars(r?.maxOutputChars);const y=r?.maxOutputChars!==void 0;let x;const captureOutput=(e,n)=>{_.onData();const r=t[e].truncatedChars;t[e]=appendCapturedOutput(t[e],n,v,y);if(!y&&t[e].truncatedChars>r&&!x){x=e;if(!m)killProcess()}};for(const e of[`stdout`,`stderr`])(e===`stdout`?d.onStdout:d.onStderr)(t=>{if(h&&!d.supportsRawOutput)captureOutput(e,t)},t=>{if(h)captureOutput(e,decodeCapturedOutput(o[e],t))});const S=d.memoryRootPid??d.pid;if(S!==void 0)a?.spawned({pid:S,startedAt:getProcessInstanceStartTime(S)});await e.ready;m=false;if(x)killProcess();if(g)stopAdapter();let C;try{C=await Promise.race([d.wait(),l.promise])}finally{_.dispose()}for(const e of[`stdout`,`stderr`])captureOutput(e,o[e].flush());if(x)t.stderr=appendCapturedOutput(t.stderr,`${t.stderr.text?`
`:``}exec ${x} exceeded output limit ${v} chars`,v,true);p={stdout:t.stdout.text,stderr:t.stderr.text,stdoutTruncatedChars:t.stdout.truncatedChars||void 0,stderrTruncatedChars:t.stderr.truncatedChars||void 0,outputLimitExceeded:x,code:x?1:C.code??1,killed:g};return p}catch(e){_=true;stopAdapter();if(m&&isErrno(e)&&/^(?:spawn|posix_spawn)(?: |$)/u.test(e.syscall??``))return{stdout:``,stderr:``,code:1,killed:g};throw e}finally{b?.();x?.();r?.signal?.removeEventListener(`abort`,killProcess);const settle=async()=>{try{const e=await(d?.waitForExtinction?.()??f);if(e&&e.status===`uncertain`)throw new CommandProcessCleanupError({cause:p??e});a?.settled();u.resolve()}catch(e){const t=hasCommandProcessCleanupError(e)?e:new CommandProcessCleanupError({cause:p??e});u.reject(t);throw t}finally{y?.();o?.removeEventListener(`abort`,killProcess);d?.dispose()}};const e=settle();if(g||_)await e;else e.catch(e=>process.emitWarning(`Session exec cleanup failed: ${String(e)}`))}})();if(s?.aborted)killProcess();try{return await Promise.race([S,l.promise])}finally{h=false}}
//!src/agents/sessions/extensions/loader.ts
function createExtensionRuntime(){const notInitialized=()=>{throw new Error(`Extension runtime not initialized. Action methods cannot be called during extension loading.`)};let e;const assertActive=()=>{if(e)throw new Error(e)};const t={sendMessage:notInitialized,sendUserMessage:notInitialized,appendEntry:notInitialized,appendEntryAsync:notInitialized,setSessionName:notInitialized,setSessionNameAsync:notInitialized,getSessionName:notInitialized,setLabel:notInitialized,setLabelAsync:notInitialized,getActiveTools:notInitialized,getAllTools:notInitialized,setActiveTools:notInitialized,refreshTools:()=>{},getCommands:notInitialized,setModel:()=>Promise.reject(/* @__PURE__ */ new Error(`Extension runtime not initialized`)),getThinkingLevel:notInitialized,setThinkingLevel:notInitialized,flagValues:/* @__PURE__ */ new Map,pendingProviderRegistrations:[],assertActive,invalidate:t=>{e??=t??`This extension ctx is stale after session replacement or reload. Do not use a captured api or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().`},registerProvider:(e,n,r=`<unknown>`)=>{t.pendingProviderRegistrations.push({name:e,config:n,extensionPath:r})},unregisterProvider:e=>{t.pendingProviderRegistrations=t.pendingProviderRegistrations.filter(t=>t.name!==e)}};return t}function createExtensionAPI(e,t,n,r){const activeRuntime=()=>{t.assertActive();return t};const persist=async e=>{const t=activeRuntime();const n=e(t);if(!n)throw new Error(`Extension host must bind worker persistence with bindCoreAsync`);const r=await n;t.assertActive();return r};return{on(n,r){t.assertActive();const i=e.handlers.get(n)??[];i.push(r);e.handlers.set(n,i)},registerTool(n){t.assertActive();e.tools.set(n.name,{definition:n,sourceInfo:e.sourceInfo});t.refreshTools()},registerCommand(n,r){t.assertActive();e.commands.set(n,{name:n,sourceInfo:e.sourceInfo,...r})},registerShortcut(n,r){t.assertActive();e.shortcuts.set(n,{shortcut:n,extensionPath:e.path,...r})},registerFlag(n,r){t.assertActive();e.flags.set(n,{name:n,extensionPath:e.path,...r});if(r.default!==void 0&&!t.flagValues.has(n))t.flagValues.set(n,r.default)},registerMessageRenderer(n,r){t.assertActive();e.messageRenderers.set(n,r)},getFlag(n){t.assertActive();if(!e.flags.has(n))return;return t.flagValues.get(n)},sendMessage:(e,t)=>{activeRuntime().sendMessage(e,t)},sendUserMessage:(e,t)=>{activeRuntime().sendUserMessage(e,t)},appendEntry:(e,t)=>{warnSessionPersistenceDeprecation(`ExtensionAPI.appendEntry`,`appendEntryAsync`);activeRuntime().appendEntry(e,t)},appendEntryAsync:(e,t)=>persist(n=>n.appendEntryAsync?.(e,t)),setSessionName:e=>{warnSessionPersistenceDeprecation(`ExtensionAPI.setSessionName`,`setSessionNameAsync`);activeRuntime().setSessionName(e)},setSessionNameAsync:e=>persist(t=>t.setSessionNameAsync?.(e)),getSessionName:()=>activeRuntime().getSessionName(),setLabel:(e,t)=>{warnSessionPersistenceDeprecation(`ExtensionAPI.setLabel`,`setLabelAsync`);activeRuntime().setLabel(e,t)},setLabelAsync:(e,t)=>persist(n=>n.setLabelAsync?.(e,t)),exec(e,r,i){t.assertActive();return execCommand(e,r,i?.cwd??n,i)},getActiveTools:()=>activeRuntime().getActiveTools(),getAllTools:()=>activeRuntime().getAllTools(),setActiveTools:e=>{activeRuntime().setActiveTools(e)},getCommands:()=>activeRuntime().getCommands(),setModel:e=>activeRuntime().setModel(e),getThinkingLevel:()=>activeRuntime().getThinkingLevel(),setThinkingLevel:e=>activeRuntime().setThinkingLevel(e),registerProvider:(t,n)=>{activeRuntime().registerProvider(t,n,e.path)},unregisterProvider:t=>{activeRuntime().unregisterProvider(t,e.path)},events:r}}async function loadExtensionFromFactory(e,t,n,r,i=`<inline>`){const a=i.startsWith(`<`)&&i.endsWith(`>`)?i.slice(1,-1).split(`:`)[0]||`temporary`:`local`;const o=i.startsWith(`<`)?void 0:path$1.dirname(i);const s={path:i,resolvedPath:i,sourceInfo:createSyntheticSourceInfo(i,{source:a,baseDir:o}),handlers:/* @__PURE__ */ new Map,tools:/* @__PURE__ */ new Map,messageRenderers:/* @__PURE__ */ new Map,commands:/* @__PURE__ */ new Map,flags:/* @__PURE__ */ new Map,shortcuts:/* @__PURE__ */ new Map};await e(createExtensionAPI(s,r,t,n));return s}
//!src/agents/sessions/extensions/metadata-actions.ts
function bindPersistenceScope(e,t){return n=>{t.assertActive();const r=e.getSessionTarget();const assertCurrent=()=>{t.assertActive();const n=e.getSessionTarget();if(!sameSessionTranscriptTargetBinding(r,n))throw new Error(`Extension session manager changed before metadata persistence`)};return withSessionManagerWriteAssertion(e,assertCurrent,()=>r?withSessionTranscriptWriteAssertion(r,assertCurrent,n):n())}}function bindExtensionMetadataActions(e,t,n){const r=bindPersistenceScope(e,t);t.setModel=e=>r(()=>n.setModel(e));t.setThinkingLevel=e=>r(()=>n.setThinkingLevel(e))}function bindExtensionPersistenceActions(e,t,n){const r=bindPersistenceScope(e,t);t.appendEntryAsync=(e,t)=>r(()=>n.appendEntryAsync(e,t));t.setSessionNameAsync=e=>r(()=>n.setSessionNameAsync(e));t.setLabelAsync=(e,t)=>r(()=>n.setLabelAsync(e,t))}
//!src/agents/sessions/extensions/provider-actions.ts
function bindExtensionProviderActions(e,t,n,r){const registerProvider=(e,n)=>{if(r?.registerProvider)r.registerProvider(e,n);else t.registerProvider(e,n)};for(const{name:t,config:r,extensionPath:i}of e.pendingProviderRegistrations)try{registerProvider(t,r)}catch(e){n({extensionPath:i,event:`register_provider`,error:coerceErrorMessage(e),stack:e instanceof Error?e.stack:void 0})}e.pendingProviderRegistrations=[];e.registerProvider=registerProvider;e.unregisterProvider=e=>{if(r?.unregisterProvider){r.unregisterProvider(e);return}t.unregisterProvider(e)}}
//!src/agents/sessions/extensions/runner-defaults.ts
const noOpUIContext={select:async()=>void 0,confirm:async()=>false,input:async()=>void 0,notify:()=>{},onTerminalInput:()=>()=>{},setStatus:()=>{},setWorkingMessage:()=>{},setWorkingVisible:()=>{},setWorkingIndicator:()=>{},setHiddenThinkingLabel:()=>{},setWidget:()=>{},setFooter:()=>{},setHeader:()=>{},setTitle:()=>{},custom:async()=>void 0,pasteToEditor:()=>{},setEditorText:()=>{},getEditorText:()=>``,editor:async()=>void 0,addAutocompleteProvider:()=>{},setEditorComponent:()=>{},getEditorComponent:()=>void 0,get theme(){return interactiveAgentTheme},getAllThemes:()=>[],getTheme:()=>void 0,setTheme:()=>({success:false,error:`UI not available`}),getToolsExpanded:()=>false,setToolsExpanded:()=>{}};const noOpCommandContextActions={waitForIdle:async()=>{},newSession:async()=>({cancelled:false}),fork:async()=>({cancelled:false}),navigateTree:async()=>({cancelled:false}),switchSession:async()=>({cancelled:false}),reload:async()=>{}};
//!src/agents/sessions/extensions/runner.ts
const RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS=[`app.interrupt`,`app.clear`,`app.exit`,`app.suspend`,`app.thinking.cycle`,`app.model.cycleForward`,`app.model.cycleBackward`,`app.model.select`,`app.tools.expand`,`app.thinking.toggle`,`app.editor.external`,`app.message.followUp`,`tui.input.submit`,`tui.select.confirm`,`tui.select.cancel`,`tui.input.copy`,`tui.editor.deleteToLineEnd`];const buildBuiltinKeybindings=e=>{const t={};for(const[n,r]of Object.entries(e)){if(r===void 0)continue;const e=Array.isArray(r)?r:[r];const i=RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS.includes(n);for(const r of e){const e=r.toLowerCase();if(t[e]?.restrictOverride&&!i)continue;t[e]={keybinding:n,restrictOverride:i}}}return t};async function emitSessionShutdownEvent(e,t){if(e.hasHandlers(`session_shutdown`)){await e.emit(t);return true}return false}var ExtensionRunner=class{constructor(e,t,n,r,i){this.extensions=e;this.runtime=t;this.cwd=n;this.sessionManager=r;this.modelRegistry=i;this.errorListeners=/* @__PURE__ */ new Set;this.getModel=()=>void 0;this.isIdleFn=()=>true;this.getSignalFn=()=>void 0;this.waitForIdleFn=noOpCommandContextActions.waitForIdle;this.abortFn=()=>{};this.hasPendingMessagesFn=()=>false;this.getContextUsageFn=()=>void 0;this.compactFn=()=>{};this.getSystemPromptFn=()=>``;this.newSessionHandler=noOpCommandContextActions.newSession;this.forkHandler=noOpCommandContextActions.fork;this.navigateTreeHandler=noOpCommandContextActions.navigateTree;this.switchSessionHandler=noOpCommandContextActions.switchSession;this.reloadHandler=noOpCommandContextActions.reload;this.shutdownHandler=()=>{};this.shortcutDiagnostics=[];this.commandDiagnostics=[];this.uiContext=noOpUIContext}bindCoreAsync(e,t,n){this.bindCoreActions(e,t,n);bindExtensionPersistenceActions(this.sessionManager,this.runtime,e)}bindCore(e,t,n){warnSessionPersistenceDeprecation(`ExtensionRunner.bindCore`,`bindCoreAsync with ExtensionActionsV2`);this.bindCoreActions(e,t,n)}bindCoreActions(e,t,n){this.runtime.sendMessage=e.sendMessage;this.runtime.sendUserMessage=e.sendUserMessage;this.runtime.appendEntry=e.appendEntry;this.runtime.setSessionName=e.setSessionName;this.runtime.getSessionName=e.getSessionName;this.runtime.setLabel=e.setLabel;this.runtime.getActiveTools=e.getActiveTools;this.runtime.getAllTools=e.getAllTools;this.runtime.setActiveTools=e.setActiveTools;this.runtime.refreshTools=e.refreshTools;this.runtime.getCommands=e.getCommands;bindExtensionMetadataActions(this.sessionManager,this.runtime,e);this.runtime.getThinkingLevel=e.getThinkingLevel;this.getModel=t.getModel;this.isIdleFn=t.isIdle;this.getSignalFn=t.getSignal;this.abortFn=t.abort;this.hasPendingMessagesFn=t.hasPendingMessages;this.shutdownHandler=t.shutdown;this.getContextUsageFn=t.getContextUsage;this.compactFn=t.compact;this.getSystemPromptFn=t.getSystemPrompt;bindExtensionProviderActions(this.runtime,this.modelRegistry,e=>this.emitError(e),n)}bindCommandContext(e){const t=e??noOpCommandContextActions;this.waitForIdleFn=t.waitForIdle;this.newSessionHandler=t.newSession;this.forkHandler=t.fork;this.navigateTreeHandler=t.navigateTree;this.switchSessionHandler=t.switchSession;this.reloadHandler=t.reload}setUIContext(e){this.uiContext=e??noOpUIContext}getUIContext(){return this.uiContext}hasUI(){return this.uiContext!==noOpUIContext}getExtensionPaths(){return this.extensions.map(e=>e.path)}getAllRegisteredTools(){const e=/* @__PURE__ */ new Map;for(const t of this.extensions)for(const n of t.tools.values())if(!e.has(n.definition.name))e.set(n.definition.name,n);return Array.from(e.values())}getToolDefinition(e){for(const t of this.extensions){const n=t.tools.get(e);if(n)return n.definition}}getFlags(){const e=/* @__PURE__ */ new Map;for(const t of this.extensions)for(const[n,r]of t.flags)if(!e.has(n))e.set(n,r);return e}setFlagValue(e,t){this.runtime.flagValues.set(e,t)}getFlagValues(){return new Map(this.runtime.flagValues)}getShortcuts(e){this.shortcutDiagnostics=[];const t=buildBuiltinKeybindings(e);const n=/* @__PURE__ */ new Map;const addDiagnostic=(e,t)=>{this.shortcutDiagnostics.push({type:`warning`,message:e,path:t});if(!this.hasUI())console.warn(e)};for(const e of this.extensions)for(const[r,i]of e.shortcuts){const e=r.toLowerCase();const a=t[e];if(a?.restrictOverride===true){addDiagnostic(`Extension shortcut '${r}' from ${i.extensionPath} conflicts with built-in shortcut. Skipping.`,i.extensionPath);continue}if(a?.restrictOverride===false)addDiagnostic(`Extension shortcut conflict: '${r}' is built-in shortcut for ${a.keybinding} and ${i.extensionPath}. Using ${i.extensionPath}.`,i.extensionPath);const o=n.get(e);if(o)addDiagnostic(`Extension shortcut conflict: '${r}' registered by both ${o.extensionPath} and ${i.extensionPath}. Using ${i.extensionPath}.`,i.extensionPath);n.set(e,i)}return n}getShortcutDiagnostics(){return this.shortcutDiagnostics}invalidate(e=`This extension ctx is stale after session replacement or reload. Do not use a captured api or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().`){if(!this.staleMessage){this.staleMessage=e;this.runtime.invalidate(e)}}requireActive(){if(this.staleMessage)throw new Error(this.staleMessage);this.runtime.assertActive();return this}onError(e){return registerListener(this.errorListeners,e)}emitError(e){for(const t of this.errorListeners)t(e)}hasHandlers(e){for(const t of this.extensions)if((t.handlers.get(e)?.length??0)>0)return true;return false}getMessageRenderer(e){for(const t of this.extensions){const n=t.messageRenderers.get(e);if(n)return n}}resolveRegisteredCommands(){const e=[];const t=/* @__PURE__ */ new Map;for(const n of this.extensions)for(const r of n.commands.values()){e.push(r);t.set(r.name,(t.get(r.name)??0)+1)}const n=/* @__PURE__ */ new Map;const r=/* @__PURE__ */ new Set;return e.map(e=>{const i=(n.get(e.name)??0)+1;n.set(e.name,i);let a=(t.get(e.name)??0)>1?`${e.name}:${i}`:e.name;if(r.has(a)){let t=i;do{t++;a=`${e.name}:${t}`}while(r.has(a))}r.add(a);return Object.assign({},e,{invocationName:a})})}getRegisteredCommands(){this.commandDiagnostics=[];return this.resolveRegisteredCommands()}getCommandDiagnostics(){return this.commandDiagnostics}getCommand(e){return this.resolveRegisteredCommands().find(t=>t.invocationName===e)}shutdown(){this.shutdownHandler()}createContext(){const requireActiveRunner=()=>this.requireActive();const e=this.getModel;return{get ui(){return requireActiveRunner().uiContext},get hasUI(){return requireActiveRunner().hasUI()},get cwd(){return requireActiveRunner().cwd},get sessionManager(){return requireActiveRunner().sessionManager},get modelRegistry(){return requireActiveRunner().modelRegistry},get model(){requireActiveRunner();return e()},isIdle:()=>requireActiveRunner().isIdleFn(),get signal(){return requireActiveRunner().getSignalFn()},abort:()=>requireActiveRunner().abortFn(),hasPendingMessages:()=>requireActiveRunner().hasPendingMessagesFn(),shutdown:()=>requireActiveRunner().shutdownHandler(),getContextUsage:()=>requireActiveRunner().getContextUsageFn(),compact:e=>requireActiveRunner().compactFn(e),getSystemPrompt:()=>requireActiveRunner().getSystemPromptFn()}}createCommandContext(){return Object.assign(this.createContext(),{waitForIdle:()=>this.requireActive().waitForIdleFn(),newSession:e=>this.requireActive().newSessionHandler(e),fork:(e,t)=>this.requireActive().forkHandler(e,t),navigateTree:(e,t)=>this.requireActive().navigateTreeHandler(e,t),switchSession:(e,t)=>this.requireActive().switchSessionHandler(e,t),reload:()=>this.requireActive().reloadHandler()})}async dispatchHandlers(e,t,n){let r=n;for(const n of this.extensions)for(const i of n.handlers.get(e)??[]){r??=this.createContext();try{const e=await t(i,r,n.path);if(e!==void 0)return e}catch(t){if(e===`tool_call`)throw t;rethrowIncognitoSessionError(t);if(t instanceof SessionMetadataCommittedError)throw t;this.emitError({extensionPath:n.path,event:e,error:coerceErrorMessage(t),stack:t instanceof Error?t.stack:void 0})}}}async emit(e){let t;return await this.dispatchHandlers(e.type,async(n,r)=>{const i=await n(e,r);if((e.type===`session_before_switch`||e.type===`session_before_fork`||e.type===`session_before_compact`||e.type===`session_before_tree`)&&i){t=i;if(t.cancel)return t}})??t}async emitMessageEnd(e){let t=e.message;let n=false;await this.dispatchHandlers(`message_end`,async(r,i,a)=>{const o=await r({...e,message:t},i);if(o?.message){if(o.message.role!==t.role)this.emitError({extensionPath:a,event:`message_end`,error:`message_end handlers must return a message with the same role`});else{t=o.message;n=true}}});return n?t:void 0}async emitToolResult(e){const t={...e};let n=false;await this.dispatchHandlers(`tool_result`,async(e,r)=>{const i=await e(t,r);if(i?.content!==void 0){t.content=i.content;n=true}if(i?.details!==void 0){t.details=i.details;n=true}if(i?.isError!==void 0||isToolResultError(i)){t.isError=i?.isError??true;n=true}if(i?.terminate!==void 0){t.terminate=i.terminate;n=true}});if(!n)return;return{content:t.content,details:t.details,isError:t.isError,terminate:t.terminate}}async emitToolCall(e){let t;await this.dispatchHandlers(`tool_call`,async(n,r)=>{const i=await n(e,r);if(i){t=i;if(t.block)return t}});return t}async emitUserBash(e){return await this.dispatchHandlers(`user_bash`,async(t,n)=>{const r=await t(e,n);return r?r:void 0})}async emitContext(e){if(!this.hasHandlers(`context`))return e;let t=cloneTranscriptView(e,{shareImmutablePayloads:false});await this.dispatchHandlers(`context`,async(e,n)=>{t=(await e({type:`context`,messages:t},n))?.messages||t});return t}async emitBeforeProviderRequest(e){let t=e;await this.dispatchHandlers(`before_provider_request`,async(e,n)=>{const r=await e({type:`before_provider_request`,payload:t},n);if(r!==void 0)t=r});return t}async emitBeforeAgentStart(e,t,n,r){let i=n;const a=this.createContext();a.getSystemPrompt=()=>{this.requireActive();return i};const o=[];let s=false;await this.dispatchHandlers(`before_agent_start`,async(n,a)=>{const c=await n({type:`before_agent_start`,prompt:e,images:t,systemPrompt:i,systemPromptOptions:r},a);if(c?.message)o.push(c.message);if(c?.systemPrompt!==void 0){i=c.systemPrompt;s=true}},a);if(o.length>0||s)return{messages:o.length>0?o:void 0,systemPrompt:s?i:void 0}}async emitResourcesDiscover(e,t){const n={skillPaths:[],promptPaths:[],themePaths:[]};await this.dispatchHandlers(`resources_discover`,async(r,i,a)=>{const o=await r({type:`resources_discover`,cwd:e,reason:t},i);for(const e of[`skillPaths`,`promptPaths`,`themePaths`]){const t=o?.[e];if(t?.length)n[e].push(...t.map(e=>({path:e,extensionPath:a})))}});return n}async emitInput(e,t,n){let r=e;let i=t;const a=await this.dispatchHandlers(`input`,async(e,t)=>{const a=await e({type:`input`,text:r,images:i,source:n},t);if(a?.action===`handled`)return a;if(a?.action===`transform`){r=a.text;i=a.images??i}});if(a)return a;return r!==e||i!==t?{action:`transform`,text:r,images:i}:{action:`continue`}}};
//!src/agents/sessions/queued-user-message-retirement.ts
const queuedUserMessageRetirements=/* @__PURE__ */ new WeakMap;function registerQueuedUserMessageRetirement(e,t){queuedUserMessageRetirements.set(e,t)}function retireQueuedUserMessage(e){const t=queuedUserMessageRetirements.get(e);if(!t)return false;queuedUserMessageRetirements.delete(e);return t()}
//!src/agents/sessions/session-tool-result-preparation.ts
const preparers=createSessionManagerRuntimeRegistry();const unchangedToolResult=()=>false;function setSessionToolResultPreparer(e,t){preparers.set(e,t)}function createSessionToolResultPreparer(e,t){if(t.type!==`message_end`||t.message.role!==`toolResult`)return unchangedToolResult;return()=>{if(t.message.role!==`toolResult`)return false;const n=t.message;const r=preparers.get(e)?.cap(n)??n;if(r===n)return false;if(Object.isFrozen(n))t.message=copyInternalToolResultState(n,freezeJsonSnapshot(r));else n.content=r.content;return true}}
//!src/agents/sessions/steering-message-identity.ts
const STEERING_MESSAGE_IDENTITY=Symbol.for(`openclaw.steeringMessageIdentity`);const steeringMessagePersistenceFailureListeners=/* @__PURE__ */ new Map;function setSteeringMessageIdentity(e,t){if(t)Object.defineProperty(e,STEERING_MESSAGE_IDENTITY,{configurable:true,value:t})}function getSteeringMessageIdentity(e){return e&&typeof e===`object`?e[STEERING_MESSAGE_IDENTITY]:void 0}function subscribeSteeringMessagePersistenceFailure(e,t){const n=steeringMessagePersistenceFailureListeners.get(e)??/* @__PURE__ */ new Set;n.add(t);steeringMessagePersistenceFailureListeners.set(e,n);return()=>{n.delete(t);if(n.size===0&&steeringMessagePersistenceFailureListeners.get(e)===n)steeringMessagePersistenceFailureListeners.delete(e)}}function reportSteeringMessagePersistenceFailure(e,t){const n=getSteeringMessageIdentity(e);if(n)steeringMessagePersistenceFailureListeners.get(n)?.forEach(e=>e(t))}
//!src/agents/sessions/agent-session-base.ts
const log=createSubsystemLogger(`agents/session`);var AgentSessionBase=class{constructor(e){this.eventListeners=[];this.steeringMessages=[];this.followUpMessages=[];this.pendingNextTurnMessages=[];this.compactionAbortController=void 0;this.autoCompactionAbortController=void 0;this.overflowRecoveryAttempts=0;this.extensionModifiedToolResultIds=/* @__PURE__ */ new Set;this.retryAbortController=void 0;this.retryCount=0;this.turnIndex=0;this.toolRegistry=/* @__PURE__ */ new Map;this.toolDefinitions=/* @__PURE__ */ new Map;this.lastAssistantMessage=void 0;this.lastRunEndedForTurnHandoff=false;this.handleAgentEvent=(e,t)=>{const n=createSessionToolResultPreparer(this.sessionManager,e);if(e.type===`agent_end`){const e=t?.reason;this.lastRunEndedForTurnHandoff=t?.aborted===true&&typeof e===`object`&&e!==null&&e.turnHandoff===true}if(e.type===`message_end`||this.currentExtensionRunner.hasHandlers(e.type))return this.runWithSessionWriteSettlement(()=>this.handleAgentEventUnlocked(e,n)).then(()=>{n()});return this.handleAgentEventUnlocked(e,n,e.type===`message_update`?false:void 0)};this.agent=e.agent;this.baseSystemPrompt=e.systemPrompt;this.sessionManager=e.sessionManager;this.settingsManager=e.settingsManager;this.sessionResourceLoader=e.resourceLoader;this.customTools=e.customTools??[];this.cwd=e.cwd;this.sessionModelRegistry=e.modelRegistry;this.extensionRunnerRef=e.extensionRunnerRef;this.allowedToolNames=new Set(e.allowedToolNames);this.withExternalSessionWriteSettlement=e.withSessionWriteSettlement;this.contextOverflowRecoveryOwner=e.contextOverflowRecoveryOwner??`session`;this.resolveCompactionThinkingLevel=e.resolveCompactionThinkingLevel;this.cleanupProviderSessionResourcesOnDispose=e.cleanupProviderSessionResourcesOnDispose??true}get modelRegistry(){return this.sessionModelRegistry}async getRequiredRequestAuth(e){const t=await this.sessionModelRegistry.getApiKeyAndHeaders(e);if(!t.ok){if(t.error.startsWith(`No API key found`))throw new Error(formatNoApiKeyFoundMessage(e.provider));throw new Error(t.error)}if(t.apiKey)return{apiKey:t.apiKey,headers:t.headers};if(this.sessionModelRegistry.isUsingOAuth(e))throw new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`);throw new Error(formatNoApiKeyFoundMessage(e.provider))}async getCompactionRequestAuth(e){if(getStreamLlmRuntime(this.agent.streamFn)===getModelRegistryRuntime(this.sessionModelRegistry).llmRuntime)return this.getRequiredRequestAuth(e);const t=await this.sessionModelRegistry.getApiKeyAndHeaders(e);return t.ok?{apiKey:t.apiKey,headers:t.headers}:{}}async runWithSessionWriteSettlement(e){return this.withExternalSessionWriteSettlement?await this.withExternalSessionWriteSettlement(e):await e()}installAgentToolHooks(){this.agent.beforeToolCall=async({toolCall:e,args:t})=>{const n=this.currentExtensionRunner;return await this.runWithSessionWriteSettlement(async()=>{if(!n.hasHandlers(`tool_call`))return;try{return await n.emitToolCall({type:`tool_call`,toolName:e.name,toolCallId:e.id,input:t})}catch(e){if(e instanceof Error)throw e;throw new Error(`Extension failed, blocking execution: ${String(e)}`,{cause:e})}})};this.agent.afterToolCall=async({toolCall:e,args:t,result:n,isError:r})=>{const i=r||isToolResultError(n);const a=this.currentExtensionRunner;if(!a.hasHandlers(`tool_result`))return{isError:i};const o=await this.runWithSessionWriteSettlement(async()=>await a.emitToolResult({type:`tool_result`,toolName:e.name,toolCallId:e.id,input:t,content:n.content,details:n.details,isError:i,...n.terminate!==void 0?{terminate:n.terminate}:{}}));if(o)this.extensionModifiedToolResultIds.add(e.id);return{...o,isError:o?.isError??i}};this.agent.afterToolOutcome=async({executionStarted:e,result:t,isError:n})=>e?void 0:{isError:n||isToolResultError(t)}}emit(e){for(const t of this.eventListeners)t(e)}async emitTerminal(e){const t=this.eventListeners;for(const n of t)try{await n(e)}catch(e){log.warn(`agent_end listener failed: ${String(e)}`)}}emitQueueUpdate(){this.emit({type:`queue_update`})}trackQueuedUserMessage(e,t,n){const r=t===`steering`?this.steeringMessages:this.followUpMessages;const i={text:n};r.push(i);registerQueuedUserMessageRetirement(e,()=>{if(r!==this.steeringMessages&&r!==this.followUpMessages)return false;const e=r.indexOf(i);if(e===-1)return false;r.splice(e,1);this.emitQueueUpdate();return true})}async handleAgentEventUnlocked(e,t,n){if(e.type===`agent_start`){this.lastAssistantEntryId=void 0;this.turnIndex=0}if(e.type===`message_start`&&e.message.role===`user`){this.overflowRecoveryAttempts=0;retireQueuedUserMessage(e.message)}let r=false;if(n??this.currentExtensionRunner.hasHandlers(e.type))r=await this.emitExtensionEvent(e);if(e.type===`turn_end`)this.turnIndex++;r=t()||r;const i=e.type===`message_end`&&e.message.role===`user`;if(e.type===`agent_end`)await this.emitTerminal({...e,willRetry:this.willRetryAfterAgentEnd(e),...this.lastAssistantEntryId?{assistantEntryId:this.lastAssistantEntryId}:{}});else if(!i)this.emit(e);r=t()||r;if(e.type===`message_end`){if(e.message.role===`custom`){const t=e.message;const n=getModelPromptProjectionAppend(t);if(n)await this.sessionManager[sessionManagerAppendPromptContext](t,n);else await this.sessionManager.appendCustomMessageEntryAsync(t.customType,t.content,t.display,t.details,t.timestamp)}else if(e.message.role===`user`||e.message.role===`assistant`||e.message.role===`toolResult`){const t=e.message.role===`toolResult`&&this.extensionModifiedToolResultIds.delete(e.message.toolCallId);try{const n=e.message.role===`user`&&shouldRetainSteeringRuntimeContext(this)?getSteeringRuntimeContext(e.message):void 0;if(n)await this.sessionManager.appendCustomMessageEntryAsync(n.customType,n.content,n.display,n.details,n.timestamp);const i=await persistAgentSessionMessage(this.sessionManager,e.message,{invalidateSerializedPrefixCache:r||t});if(e.message.role===`assistant`)this.lastAssistantEntryId=i}catch(t){if(e.message.role===`user`)reportSteeringMessagePersistenceFailure(e.message,t);throw t}if(e.message.role===`user`)this.emit(e)}if(e.message.role===`assistant`)this.lastAssistantMessage=e.message}if(e.type===`turn_end`&&e.message.role===`assistant`){const t=e.message;if(t.stopReason!==`error`&&t.stopReason!==`length`)this.overflowRecoveryAttempts=0;if(t.stopReason!==`error`&&this.retryCount>0){this.emit({type:`auto_retry_end`});this.retryCount=0}}}willRetryAfterAgentEnd(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled||this.retryCount>=t.maxRetries)return false;const n=e.messages.findLast(e=>e.role===`assistant`);return n!==void 0&&this.isRetryableError(n)}findLastAssistantMessage(){return this.agent.state.messages.findLast(e=>e.role===`assistant`)}async emitExtensionEvent(e){if(e.type===`turn_start`)await this.currentExtensionRunner.emit({type:`turn_start`,turnIndex:this.turnIndex,timestamp:Date.now()});else if(e.type===`turn_end`)await this.currentExtensionRunner.emit({type:`turn_end`,turnIndex:this.turnIndex,message:e.message,toolResults:e.toolResults});else if(e.type===`message_end`){const t=await this.currentExtensionRunner.emitMessageEnd({type:`message_end`,message:e.message});if(t){replaceAgentMessageInPlace(e.message,t);return true}}else if(e.type===`tool_execution_start`)await this.currentExtensionRunner.emit({type:`tool_execution_start`,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args});else if(e.type===`tool_execution_update`)await this.currentExtensionRunner.emit({type:`tool_execution_update`,toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult});else if(e.type===`tool_execution_end`)await this.currentExtensionRunner.emit({type:`tool_execution_end`,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError});else await this.currentExtensionRunner.emit({...e});return false}subscribe(e){this.eventListeners=[...this.eventListeners,e];return()=>{const t=this.eventListeners.indexOf(e);if(t!==-1)this.eventListeners=this.eventListeners.toSpliced(t,1)}}disconnectFromAgent(){if(this.unsubscribeAgent){this.unsubscribeAgent();this.unsubscribeAgent=void 0}}reconnectToAgent(){if(this.unsubscribeAgent)return;this.unsubscribeAgent=this.agent.subscribe(this.handleAgentEvent)}dispose(){this.disposeBackgroundResultPlacement();setInternalBeforeRequest(this.agent,void 0);notifyListeners([()=>this.abortRetry(),()=>this.abortCompaction(),()=>this.agent.abort()],void 0);this.currentExtensionRunner.invalidate();this.disconnectFromAgent();this.eventListeners=[];if(this.cleanupProviderSessionResourcesOnDispose)cleanupSessionResources(this.sessionId)}get state(){return this.agent.state}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get isStreaming(){return this.agent.state.isStreaming}get systemPrompt(){return this.agent.state.systemPrompt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}getAllTools(){return Array.from(this.toolDefinitions.values()).map(({definition:e,sourceInfo:t})=>({name:e.name,description:e.description,parameters:e.parameters,sourceInfo:t}))}getToolDefinition(e){return this.toolDefinitions.get(e)?.definition}setActiveToolsByName(e,t){const n=[];const r=[];const i=t?new Set(t):void 0;for(const t of e){const e=this.toolRegistry.get(t);if(e){n.push(!i||i.has(t)?e:gateAgentToolExecution(e,`${t} is not available in this turn. Do not retry ${t}.`));r.push(t)}}this.agent.state.tools=n;this.refreshSystemPromptMetadata(r);this.agent.state.systemPrompt=this.systemPromptOverride??this.baseSystemPrompt}setBaseSystemPrompt(e){this.baseSystemPrompt=e;this.refreshSystemPromptMetadata(this.getActiveToolNames());this.agent.state.systemPrompt=e}get isCompacting(){return this.autoCompactionAbortController!==void 0||this.compactionAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionTarget(){return this.sessionManager.getSessionTarget()}get sessionKey(){return this.sessionTarget?.sessionKey}get sessionFile(){return this.sessionKey}get sessionId(){return this.sessionManager.getSessionId()}get sessionName(){return this.sessionManager.getSessionName()}get promptTemplates(){return this.sessionResourceLoader.getPrompts().prompts}refreshSystemPromptMetadata(e){const t=e.filter(e=>this.toolRegistry.has(e));const n={};const r=[];for(const e of t){const t=this.toolDefinitions.get(e)?.definition;const i=t?.promptSnippet?.replace(/\s+/g,` `).trim();if(i)n[e]=i;r.push(...new Set(t?.promptGuidelines?.map(e=>e.trim()).filter(Boolean)))}this.baseSystemPromptOptions={cwd:this.cwd,customPrompt:this.baseSystemPrompt,selectedTools:t,toolSnippets:n,promptGuidelines:r}}};
//!src/shared/tilde-path.ts
function expandTildePath(e){const t=e.trim();if(t===`~`)return homedir();if(t.startsWith(`~/`))return join(homedir(),t.slice(2));if(t.startsWith(`~`))return join(homedir(),t.slice(1));return t}
//!src/agents/sessions/prompt-templates.ts
function loadTemplateFromFile(e,t){try{const n=readFileSync(e,`utf-8`);const{frontmatter:r,body:i}=parsePromptFrontmatter(n);const a=basename(e).replace(/\.md$/,``);let o=r.description||``;if(!o){const e=i.split(`
`).find(e=>e.trim());if(e)o=truncateUtf16Safe(e,60)+(e.length>60?`...`:``)}return{name:a,description:o,...r[`argument-hint`]&&{argumentHint:r[`argument-hint`]},content:i,sourceInfo:t,filePath:e}}catch{return null}}function resolvePromptPath(e,t){const n=expandTildePath(e);return isAbsolute(n)?n:resolve(t,n)}function loadPromptTemplates({cwd:e,agentDir:t,promptPaths:n}){const r=[];const i=t?join(t,`prompts`):t;const a=resolve(e,CONFIG_DIR_NAME,`prompts`);const getSourceInfo=e=>{for(const[t,n]of[[i,`user`],[a,`project`]])if(isPathInside(t,e))return createSyntheticSourceInfo(e,{source:`local`,scope:n,baseDir:t});return createSyntheticSourceInfo(e,{source:`local`,baseDir:dirname(e)})};for(const t of n){const n=resolvePromptPath(t,e);try{const e=statSync(n);let t=[];if(e.isDirectory()){const{entries:e}=walkDirectorySync(n,{maxDepth:1,symlinks:`follow`,include:e=>e.kind===`file`&&e.name.endsWith(`.md`)});t=e.map(e=>join(n,e.name))}else if(e.isFile()&&n.endsWith(`.md`))t=[n];for(const e of t){const t=loadTemplateFromFile(e,getSourceInfo(e));if(t)r.push(t)}}catch{}}return r}function expandPromptTemplate(e,t){const n=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return e;const r=n[1];const i=n[2]??``;const a=t.find(e=>e.name===r);if(a){const e=parseCommandArgs(i);return substituteArgs(a.content,e)}return e}
//!src/agents/sessions/agent-session-prompting.ts
function createCustomMessage(e){return{role:`custom`,customType:e.customType,content:e.content,display:e.display,details:e.details,timestamp:Date.now()}}const agentSessionSetPromptPreparation=Symbol.for(`openclaw.agent-session.set-prompt-preparation`);const agentSessionQueuePromptContext=Symbol.for(`openclaw.agent-session.queue-prompt-context`);var AgentSessionPrompting=class extends AgentSessionBase{constructor(...e){super(...e);this.logicalPromptActive=false}[agentSessionQueuePromptContext](e,t){if(t?.delivery===`current-request`)return this.persistCustomMessage(e);if(this.logicalPromptActive&&isOpenClawSystemUpdateMessage(e)){this.agent.steer(e);return()=>{this.agent.cancelSteeringMessage(t=>t===e)}}if(isOpenClawSystemUpdateMessage(e))this.pendingNextTurnMessages.push(e);else this.pendingNextTurnMessages.unshift(e);return()=>{this.pendingNextTurnMessages=this.pendingNextTurnMessages.filter(t=>t!==e)}}[agentSessionSetPromptPreparation](e){this.promptPreparation=e}dispose(){this.promptPreparation=void 0;super.dispose()}async runAgentPrompt(e){if(this.logicalPromptActive)throw new Error(`Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.`);this.logicalPromptActive=true;let t=false;try{await this.runPreparedAgentLoop(()=>this.agent.prompt(e));while(true){const e=await this.handlePostAgentRun();if(e!==`continue`){t=e===`handoff`;break}await this.runPreparedAgentLoop(()=>this.agent.continue())}}finally{this.systemPromptOverride=void 0;this.logicalPromptActive=false;t||=this.lastRunEndedForTurnHandoff;this.lastRunEndedForTurnHandoff=false;if(t)this.emit({type:`agent_handoff`});else{this.emit({type:`agent_settled`});await this.currentExtensionRunner.emit({type:`agent_settled`})}}}async runPreparedAgentLoop(e){const t=this.promptPreparation;if(!t)return e();const n=await t();const assertCurrent=()=>{if(t!==this.promptPreparation)throw new Error(`Session prompt preparation is stale after replacement or disposal.`)};assertCurrent();let r;const start=t=>{assertCurrent();t?.();assertCurrent();r=e().then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))};try{if(n)await n(start);else start()}catch(e){await r;throw e}if(!r)throw new Error(`Session prompt admission did not start the agent loop.`);const i=await r;if(i.status===`rejected`)throw i.reason}async handlePostAgentRun(){const e=this.lastAssistantMessage;this.lastAssistantMessage=void 0;const t=this.lastRunEndedForTurnHandoff;this.lastRunEndedForTurnHandoff=false;if(t)return`handoff`;if(!e||e.stopReason===`aborted`)return`settled`;if(this.isRetryableError(e)&&await this.prepareRetry(e))return`continue`;if(e.stopReason===`error`&&this.retryCount>0){this.emit({type:`auto_retry_end`});this.retryCount=0}if(await this.checkCompaction(e))return`continue`;return e.stopReason!==`error`&&this.agent.hasQueuedMessages()?`continue`:`settled`}createUserMessage(e,t,n){const r=readRuntimePromptImageFactIndexes(t);const i={role:`user`,content:[{type:`text`,text:e},...t??[]],timestamp:Date.now(),...r?{__openclaw:{mediaImageBlockFactIndexes:r}}:{}};return Object.assign(i,mergePreparedUserTurnMessageForRuntime({runtimeMessage:i,preparedMessage:n}),{content:i.content})}async prompt(e,t){const n=takePromptCompactionRequestBudget(t);const r=t?.expandPromptTemplates??true;const i=t?.preflightResult;let a=false;let o=false;let s;try{if(r&&e.startsWith(`/`)){if(await this.tryExecuteExtensionCommand(e)){i?.(true);return}}let c=e;let l=t?.images;if(this.currentExtensionRunner.hasHandlers(`input`)){const e=await this.currentExtensionRunner.emitInput(c,l,t?.source??`interactive`);if(e.action===`handled`){i?.(true);return}if(e.action===`transform`){c=e.text;l=e.images??l}}const u=r?this.expandPrompt(c):c;if(this.isStreaming||this.logicalPromptActive){if(!t?.streamingBehavior)throw new Error(`Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.`);if(t.streamingBehavior===`followUp`)this.queueFollowUp(u,l);else{const e=this.queueSteer(this.createSteeringMessage(u,l),u);a=true;e()}o=a;i?.(true);return}if(!this.model)throw new Error(formatNoModelSelectedMessage());if(!this.sessionModelRegistry.hasConfiguredAuth(this.model)){if(this.sessionModelRegistry.isUsingOAuth(this.model))throw new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`);throw new Error(formatNoApiKeyFoundMessage(this.model.provider))}const d=t?.persistedUserIdempotencyKey;const f=this.model.contextWindow;const p=this.findLastAssistantMessage();if(p){const e=resolvePendingRuntimeContextReplay({messages:this.agent.state.messages,pendingContextMessages:this.pendingNextTurnMessages,persistedUserIdempotencyKey:d}).pendingContextMessages;await this.checkCompaction(p,false,n?withCompactionQueuedContext(n,e):typeof f===`number`&&Number.isFinite(f)&&f>0?createCompactionRequestBudget({contextWindow:f,reserveTokens:this.settingsManager.getCompactionSettings().reserveTokens,systemPrompt:this.agent.state.systemPrompt,tools:this.agent.state.tools,pendingPrompt:u,pendingImageCount:l?.length,pendingQueuedContextMessages:e,pendingUserIdempotencyKey:d}):void 0)}const{persistedUserIndex:m,replayPersistedCarrier:h,pendingContextMessages:g}=resolvePendingRuntimeContextReplay({messages:this.agent.state.messages,pendingContextMessages:this.pendingNextTurnMessages,persistedUserIdempotencyKey:d});const _=m>=0;const v=this.agent.state.messages[m];if(!h&&v?.role===`user`&&readModelPromptProjection(v)===void 0){const e=this.createUserMessage(u,l,v);this.agent.state.messages=this.agent.state.messages.with(m,e)}s=[];if(!_)s.push({...this.createUserMessage(u,l),...d?{idempotencyKey:d}:{}});s.push(...g);this.pendingNextTurnMessages=[];const y=await this.currentExtensionRunner.emitBeforeAgentStart(u,l,this.baseSystemPrompt,this.baseSystemPromptOptions);if(y?.messages)for(const e of y.messages)s.push(createCustomMessage(e));this.systemPromptOverride=y?.systemPrompt;this.agent.state.systemPrompt=this.systemPromptOverride!==void 0?this.systemPromptOverride:this.baseSystemPrompt}catch(e){if(a){let t=e;if(!o)try{i?.(true)}catch(n){t=new AggregateError([e,n],`Steering feedback failed`)}throw new MessageInjectionAcceptedUnconfirmedError({cause:t})}i?.(false);throw e}i?.(true);await this.runAgentPrompt(orderSystemUpdateMessages(s))}async tryExecuteExtensionCommand(e){const t=e.indexOf(` `);const n=t===-1?e.slice(1):e.slice(1,t);const r=t===-1?``:e.slice(t+1);const i=this.currentExtensionRunner.getCommand(n);if(!i)return false;const a=this.currentExtensionRunner.createCommandContext();try{await i.handler(r,a)}catch(e){this.currentExtensionRunner.emitError({extensionPath:`command:${n}`,event:`command`,error:e instanceof Error?e.message:String(e)})}return true}expandSkillCommand(e){if(!e.startsWith(`/skill:`))return e;const t=e.indexOf(` `);const n=t===-1?e.slice(7):e.slice(7,t);const r=t===-1?``:e.slice(t+1).trim();const i=this.sessionResourceLoader.getSkills().skills.find(e=>e.name===n);if(!i)return e;try{const e=readFileSync(i.filePath,`utf-8`);const t=stripFrontmatter(e).trim();const n=`<skill name="${i.name}" location="${i.filePath}">\nReferences are relative to ${i.baseDir}.\n\n${t}\n</skill>`;return r?`${n}\n\n${r}`:n}catch(t){this.currentExtensionRunner.emitError({extensionPath:i.filePath,event:`skill_expansion`,error:t instanceof Error?t.message:String(t)});return e}}expandPrompt(e){return expandPromptTemplate(this.expandSkillCommand(e),[...this.promptTemplates])}async steer(e,t,n,r,i,a,o,s,c,l){if(e.startsWith(`/`))this.throwIfExtensionCommand(e);const u=this.expandPrompt(e);return enqueueMessageInjection(this,async()=>{const e=await n?.resolveMessage();const d=this.createSteeringMessage(u,t,e&&n?{message:e,recorder:n}:void 0,r,i,a,s);let f;let p;try{await withMessageInjectionAdmission(c,()=>{if(o&&!o())throw new MessageInjectionClosedError;f=this.queueSteer(d,u);l?.()})}catch(e){p={error:e}}try{f?.()}catch(e){throw new MessageInjectionAcceptedUnconfirmedError({cause:p?new AggregateError([p.error,e],`Steering admission and notification failed`):e})}if(p)throw p.error})}async followUp(e,t){if(e.startsWith(`/`))this.throwIfExtensionCommand(e);this.queueFollowUp(this.expandPrompt(e),t)}createSteeringMessage(e,t,n,r,i,a,o){const s=this.createUserMessage(annotateInterSessionPromptText(e,n?.message.provenance),t,n?.message);const c=r?.length?attachRuntimePromptMediaFacts(s,r,i):s;attachSteeringRuntimeContext(c,o);setSteeringMessageIdentity(c,a);return n?attachRuntimeUserTurnTranscriptContext(c,n):c}queueSteer(e,t){this.trackQueuedUserMessage(e,`steering`,t);const n=this.agent.admitSteeringMessage(e);return()=>{const e=[];notifyListeners([()=>this.emitQueueUpdate(),()=>n()],void 0,t=>e.push(t));throwCollectedErrors(e,`Steering notifications failed`)}}queueFollowUp(e,t){const n=this.createUserMessage(e,t);this.trackQueuedUserMessage(n,`followUp`,e);this.emitQueueUpdate();this.agent.followUp(n)}throwIfExtensionCommand(e){const t=e.indexOf(` `);const n=t===-1?e.slice(1):e.slice(1,t);if(this.currentExtensionRunner.getCommand(n))throw new Error(`Extension command "/${n}" cannot be queued. Use prompt() or execute the command when not streaming.`)}async sendCustomMessage(e,t){const n=createCustomMessage(e);if(t?.deliverAs===`nextTurn`)this.pendingNextTurnMessages.push(n);else if(this.isStreaming){if(t?.deliverAs===`followUp`)this.agent.followUp(n);else this.agent.steer(n)}else if(t?.triggerTurn)await this.runAgentPrompt(n);else await this.persistCustomMessage(n)}async persistCustomMessage(e){await withSessionManagerAppend(this.sessionManager,async()=>{await this.sessionManager.appendCustomMessageEntryAsync(e.customType,e.content,e.display,e.details,e.timestamp);this.agent.state.messages.push(e)});this.emit({type:`message_start`,message:e});this.emit({type:`message_end`,message:e})}async sendUserMessage(e,t){let n;let r;if(typeof e===`string`)n=e;else{const t=[];r=[];for(const n of e)if(n.type===`text`)t.push(n.text);else r.push(n);n=t.join(`
`);if(r.length===0)r=void 0}await this.prompt(n,{expandPromptTemplates:false,streamingBehavior:t?.deliverAs,images:r,source:`extension`})}clearQueue(){const e=this.steeringMessages.map(e=>e.text);const t=this.followUpMessages.map(e=>e.text);this.steeringMessages=[];this.followUpMessages=[];this.agent.clearAllQueues();this.emitQueueUpdate();return{steering:e,followUp:t}}get pendingMessageCount(){return this.steeringMessages.length+this.followUpMessages.length}getSteeringMessages(){return this.steeringMessages.map(e=>e.text)}getFollowUpMessages(){return this.followUpMessages.map(e=>e.text)}get resourceLoader(){return this.sessionResourceLoader}async abort(e){this.abortRetry();this.agent.abort(e);await this.agent.waitForIdle()}};export{expandTildePath as a,setSessionToolResultPreparer as c,emitSessionShutdownEvent as d,createExtensionRuntime as f,stripStaleAssistantUsageBeforeLatestCompaction as g,sanitizeCompactionReplayMessages as h,loadPromptTemplates as i,retireQueuedUserMessage as l,formatNoModelSelectedMessage as m,agentSessionQueuePromptContext as n,getSteeringMessageIdentity as o,loadExtensionFromFactory as p,agentSessionSetPromptPreparation as r,subscribeSteeringMessagePersistenceFailure as s,AgentSessionPrompting as t,ExtensionRunner as u};