dal-code 1.0.34 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/agent-session.d.ts +2 -0
  3. package/dist/core/agent-session.js +5 -5
  4. package/dist/core/background-processes.d.ts +14 -1
  5. package/dist/core/background-processes.js +7 -6
  6. package/dist/core/git-state.js +1 -0
  7. package/dist/core/model-config.d.ts +30 -0
  8. package/dist/core/model-config.js +2 -2
  9. package/dist/core/sandbox/denial.d.ts +1 -0
  10. package/dist/core/sandbox/denial.js +4 -3
  11. package/dist/core/sandbox/shell-sandbox.js +5 -5
  12. package/dist/core/system-prompt.d.ts +1 -0
  13. package/dist/core/system-prompt.js +12 -12
  14. package/dist/core/tools/bash.d.ts +7 -0
  15. package/dist/core/tools/bash.js +14 -20
  16. package/dist/core/tools/output-accumulator.js +3 -3
  17. package/dist/core/tools/output-condense.js +1 -1
  18. package/dist/core/tools/process.d.ts +3 -4
  19. package/dist/core/tools/process.js +15 -15
  20. package/dist/core/tools/truncate.d.ts +12 -0
  21. package/dist/core/tools/truncate.js +12 -5
  22. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  23. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  24. package/dist/node_modules/@dalcode/dal-gateway/src/index.js +1 -1
  25. package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
  26. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  27. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  28. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  29. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  30. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  31. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  32. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
  33. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  34. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
  35. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  36. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
  37. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  38. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  39. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  40. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  41. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  42. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  43. package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +2 -2
  44. package/dist/node_modules/@dalcode/dal-skills/src/index.js +10 -10
  45. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  46. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +14 -16
  47. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  48. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  49. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  50. package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
  51. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -5
  52. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  53. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  54. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  55. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  56. package/dist/node_modules/@dalcode/deepailab/src/model-defaults.js +1 -1
  57. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  58. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  59. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts +2 -1
  60. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
  61. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  62. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  63. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -0
  64. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  65. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  66. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  67. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  68. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  69. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  70. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  71. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  72. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  73. package/dist/utils/output-files.js +1 -1
  74. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  75. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  76. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  77. package/examples/extensions/gondolin/package-lock.json +2 -2
  78. package/examples/extensions/gondolin/package.json +1 -1
  79. package/examples/extensions/sandbox/package-lock.json +2 -2
  80. package/examples/extensions/sandbox/package.json +1 -1
  81. package/examples/extensions/with-deps/package-lock.json +2 -2
  82. package/examples/extensions/with-deps/package.json +1 -1
  83. package/npm-shrinkwrap.json +2 -2
  84. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -8,6 +8,16 @@ DAL Code 的发布说明。这里只写用户看得见的变化。
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [1.0.35] - 2026-10-15
12
+
13
+ - 每次请求带给模型的固定内容大幅减少:装了大型连接器(如浏览器工具)时,它的工具在用到时才加载,新对话首次请求从约 1.3 万 token 降到约 5 千,更快也更省。
14
+ - 长命令输出只保留开头和结尾,完整内容另存为文件,需要时再查看;技能清单只列最相关的项目,其余可搜索。
15
+ - 运行超过 30 秒的命令会自动转到后台,助手可以继续工作并随时查看进度。
16
+ - 修复:选用 auto(自动选模型)时显示的费用偏低约 7 倍;现在按实际回答的模型计价。`--list-models` 里也能看到 auto。
17
+ - 不在 git 仓库里工作时,助手不再先跑一遍 git 命令碰壁。
18
+ - 助手读小项目更快、验证更有针对性,并会在报告完成前把新加的分支(兼容旧参数、出错处理等)实际跑一遍。
19
+ - 沙箱拦下写 /tmp 时,会直接告诉助手可以写的临时目录,不再建议申请越权。
20
+
11
21
  ## [1.0.34] - 2026-10-15
12
22
 
13
23
  - 新增目标模式:输入 /goal 加上目标,助手会持续推进直到完成,并自己核对结果;默认最多自动续跑 8 次、有 token 预算,没有进展时会自动暂停,随时可以 /goal pause 或 /goal clear。
@@ -231,6 +231,7 @@ export declare class AgentSession {
231
231
  private _readGuard;
232
232
  private _shellSandbox;
233
233
  private _sandboxScratch;
234
+ private _releaseOutputFileDirectory;
234
235
  private _backgroundProcesses;
235
236
  private _sessionStartEvent;
236
237
  private _extensionUIContext?;
@@ -424,6 +425,7 @@ export declare class AgentSession {
424
425
  private _refreshToolRegistry;
425
426
  private _isDeclarable;
426
427
  private _isActivatedOnRegistration;
428
+ private getScratchDir;
427
429
  private _buildRuntime;
428
430
  reload(options?: {
429
431
  beforeSessionStart?: () => void | Promise<void>;
@@ -1,7 +1,7 @@
1
- var re=Object.defineProperty;var c=(T,e)=>re(T,"name",{value:e,configurable:!0});import{readFileSync as ae,rmSync as le}from"node:fs";import{basename as de,dirname as ce}from"node:path";import{runToolCall as he}from"@earendil-works/pi-agent-core";import{contentText as P,getCurrentSystemMessage as N,retryDelayMs as ue}from"@earendil-works/pi-ai";import{clampThinkingLevel as z,cleanupSessionResources as me,getSupportedThinkingLevels as ge,isContextOverflow as B,isRecoverableLength as pe,isRetryableAssistantError as fe,modelsAreEqual as k,resetApiProviders as _e,streamSimple as ye}from"@earendil-works/pi-ai/compat";import{configureShellEnvironment as xe}from"../dal/child-env.js";import{fill as q,t as I}from"../dal/i18n.js";import{getThemeByName as Me,theme as we}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as be}from"../utils/frontmatter.js";import{processImage as Te}from"../utils/image-process.js";import{sleep as Re}from"../utils/sleep.js";import{normalizeToolResultImages as Ae}from"../utils/tool-result-images.js";import{formatNoApiKeyFoundMessage as O,formatNoModelSelectedMessage as H}from"./auth-guidance.js";import{BackgroundProcessManager as Ce}from"./background-processes.js";import{executeBashWithOperations as ve}from"./bash-executor.js";import{generateBugReportSummary as Se}from"./bug-report.js";import{calculateContextTokens as $,collectEntriesForBranchSummary as Ee,compact as Pe,compactionThreshold as G,estimateContextTokens as ke,estimateProjectedContextTokens as S,estimateTokens as Ie,generateBranchSummary as Le,PRUNE_TARGET_RATIO as Ne,planToolOutputPruning as Be,prepareCompaction as Q,shouldCompact as V}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as Oe,THINKING_LEVEL_OPTIONS as Fe}from"./defaults.js";import{markBlankAssistantAsError as De}from"./empty-assistant.js";import{exportSessionToHtml as Ue}from"./export-html/index.js";import{createToolHtmlRenderer as We}from"./export-html/tool-renderer.js";import{ExtensionRunner as je,wrapRegisteredTools as K}from"./extensions/index.js";import{emitSessionShutdownEvent as ze}from"./extensions/runner.js";import{createToolNameMatcher as J,isMcpToolName as X}from"./mcp-servers.js";import{convertToLlm as F}from"./messages.js";import{ModelRegistry as qe}from"./model-registry.js";import{isPlaceholderModel as He,pickHouseModel as $e}from"./model-resolver.js";import{NestedToolCallRunner as Ge}from"./nested-tool-calls.js";import{buildRuleSet as Qe,EMPTY_RULE_SET as Ve}from"./permissions/rules.js";import{buildReadGuard as Ke,evaluateToolPolicy as Je,permissionAskHandlers as Xe,setProcessReadGuard as Ye}from"./permissions/tool-policy.js";import{expandPromptTemplate as Y}from"./prompt-templates.js";import{filesystemRules as Ze,resolveSandboxPolicy as et,SANDBOX_ENV as tt,sandboxEnvironmentValue as st}from"./sandbox/policy.js";import{createScratchDir as nt,ShellSandbox as ot,setProcessShellSandbox as it}from"./sandbox/shell-sandbox.js";import{exportSessionToJsonl as rt}from"./session-export.js";import{getLatestCompactionEntry as Z,SessionManager as at}from"./session-manager.js";import{applyToolModifiers as lt,DEFAULT_TOOL_NAMES as dt}from"./settings-manager.js";import{BUILTIN_PATH_PREFIX as ee,createSyntheticSourceInfo as D,isSyntheticPath as te}from"./source-info.js";import{buildSystemPrompt as ct,buildSystemPromptSections as ht,diffSystemPromptSections as ut,normalizeBuildSystemPromptOptions as se}from"./system-prompt.js";import{createLocalBashOperations as mt}from"./tools/bash.js";import{createAllToolDefinitions as gt}from"./tools/index.js";import{createProcessToolDefinition as pt}from"./tools/process.js";import{createToolDefinitionFromAgentTool as ft}from"./tools/tool-definition-wrapper.js";import{addUsageToTotals as L,combineUsage as _t,createUsageTotals as yt}from"./usage-totals.js";import{findLatestResponse as xt,getBranchSelection as Mt,getVirtualModelState as wt,isVirtualModel as C,VIRTUAL_MODEL_STATE_ENTRY as bt}from"./virtual-models.js";function gs(T){const e=T.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}c(gs,"parseSkillBlock");function ne(T){return T?Object.fromEntries(Object.entries(T).filter(e=>e[1]!==null)):void 0}c(ne,"withoutDeletedHeaders");function oe(T){let e=0;for(const t of T)e+=Ie(t);return e}c(oe,"estimateMessagesTokens");class ps{static{c(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_promptAbortGeneration=0;_agentRunAbortRequested=!1;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_branchSummaryAbortController=void 0;_retryAbortController=void 0;_retryAttempt=0;_failedResponse;_bashAbortControllers=new Set;_pendingBashMessages=[];_extensionRunner;_turnIndex=0;_entryIdsByMessage=new WeakMap;_boundaryDispatchedMessages=new WeakSet;_lastAssistantMessage;_lastAssistantToolResults=[];_lastActivityOutcome="completed";_isBeforeSettle=!1;_abortDuringBeforeSettle=!1;_isEmittingAgentSettled=!1;_deferredSettledActions=[];_resourceLoader;_customTools;_baseToolDefinitions=new Map;_cwd;_extensionRunnerRef;_initialActiveToolNames;_pendingToolNames=new Set;_usesDefaultTools;_defaultToolModifiers;_allowedTools;_allowedToolEntries;_excludedToolEntries;_allowlistFiltersMcp=!1;_excludedTools;_baseToolsOverride;_sandboxOptions;_permissionRules=Ve;_readGuard;_shellSandbox;_sandboxScratch;_backgroundProcesses;_sessionStartEvent;_extensionUIContext;_extensionMode="print";_extensionCommandContextActions;_extensionAbortHandler;_extensionShutdownHandler;_extensionErrorListener;_extensionErrorUnsubscriber;_modelRuntime;_desiredModel;_cacheWarmer;_toolRegistry=new Map;_nestedToolCalls;_hiddenDeclarations=new Set;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPromptOptions;_runSystemPromptOptions;constructor(e){this.agent=e.agent,this.sessionManager=e.sessionManager,this.settingsManager=e.settingsManager,this._scopedModels=e.scopedModels??[],this._resourceLoader=e.resourceLoader,this._customTools=e.customTools??[],this._cwd=e.cwd,this._modelRuntime=e.modelRuntime,this._desiredModel=e.desiredModel,this._cacheWarmer=e.cacheWarmer,this._cacheWarmer&&(this._cacheWarmer.onWarmed=t=>this._emit({type:"entry_appended",entry:t})),this._extensionRunnerRef=e.extensionRunnerRef,this._initialActiveToolNames=e.initialActiveToolNames,this._usesDefaultTools=e.usesDefaultTools??!1,this._defaultToolModifiers=e.defaultToolModifiers??[],e.allowedToolNames&&(this._allowedTools=J(e.allowedToolNames),this._allowlistFiltersMcp=e.allowedToolNames.length===0||e.allowedToolNames.some(t=>t.startsWith("mcp__"))),this._excludedTools=e.excludedToolNames?J(e.excludedToolNames):void 0,this._allowedToolEntries=e.allowedToolNames?[...e.allowedToolNames]:void 0,this._excludedToolEntries=e.excludedToolNames?[...e.excludedToolNames]:void 0,this._baseToolsOverride=e.baseToolsOverride,this._sandboxOptions=e.sandbox??{},this._backgroundProcesses=new Ce({sandbox:c(()=>this._shellSandbox,"sandbox"),shellPath:c(()=>this.settingsManager.getShellPath(),"shellPath"),onEvent:c(t=>this._emit(t),"onEvent")}),this._sessionStartEvent=e.sessionStartEvent??{type:"session_start",reason:"startup"},this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._installAgentToolHooks(),this._installAgentNextTurnRefresh(),this._installAgentRequestProjection(),this._installAgentBoundaryHooks(),this._installHiddenDeclarationsProjection(),this._installAgentForcedPromptProjection(),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0}),this._initialActiveToolNames===void 0&&this._restoreToolsFromTranscript()}get modelRuntime(){return this._modelRuntime}async _askPermission(e){const t=this._extensionRunner.createContext();for(const i of Xe()){const r=await i(e,t);if(r)return r}if(!t.hasUI)return{approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"};const s=typeof e.input.command=="string"?e.input.command:JSON.stringify(e.input),n=I("\u4EC5\u672C\u6B21\u5141\u8BB8");return await t.ui.select([q(I("\u89C4\u5219 {rule} \u8981\u6C42\u5148\u786E\u8BA4\u518D\u8FD0\u884C\u3002"),{rule:e.rule}),q(I("\u5DE5\u5177\uFF1A{tool}"),{tool:e.toolName}),s].join(`
2
- `),[n,I("\u62D2\u7EDD")])===n?{approved:!0}:{approved:!1,message:"the user declined"}}getSandboxStatus(){return this._shellSandbox?.status()}get backgroundProcesses(){return this._backgroundProcesses}async _getRequiredRequestAuth(e,t){let s;try{s=await this._modelRuntime.getAuth(e,{signal:t})}catch(o){const i=o instanceof Error?o.cause:void 0;throw i instanceof Error&&i.message==="authHeader requires a resolved API key"?new Error(O(e.provider)):o}if(s&&(s.auth.apiKey||s.auth.headers))return{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:ne(s.auth.headers),env:s.env};throw this._modelRuntime.isUsingOAuth(e.provider)?new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`):new Error(O(e.provider))}async _getSummarizationRequestAuth(e,t){const{model:s,thinkingLevel:n}=C(e)?await this._modelRuntime.resolveModel(e,F(this.messages),{reason:"direct",thinkingLevel:this.thinkingLevel,signal:t}):{model:e,thinkingLevel:this.thinkingLevel};if(this.agent.streamFunction===ye)return{...await this._getRequiredRequestAuth(s,t),thinkingLevel:n};try{const o=await this._modelRuntime.getAuth(s,{signal:t});return o?{model:o.auth.baseUrl?{...s,baseUrl:o.auth.baseUrl}:s,apiKey:o.auth.apiKey,headers:ne(o.auth.headers),env:o.env,thinkingLevel:n}:{model:s,thinkingLevel:n}}catch(o){if(t?.aborted)throw o;return{model:s,thinkingLevel:n}}}_modelForMessage(e){const t=this.model;return t&&C(t)?this._modelRuntime.getPhysicalModel(e.provider,e.model):t?.provider===e.provider&&t.id===e.model?t:void 0}_recordSelection(){const e=this.model;if(!e)return;const t=c((o,i)=>this._modelRuntime.getModel(o,i),"getModel"),s=Mt(this.sessionManager.getBranch(),t);if(!s||s.provider===e.provider&&s.modelId===e.id)return;const n=t(s.provider,s.modelId);!C(e)&&!(n&&C(n))||this.sessionManager.appendModelChange(e.provider,e.id)}_limitsModel(){return this.routedModel?.model??this.model}_installAgentToolHooks(){this.agent.beforeToolCall=e=>this._beforeToolCall(e),this.agent.afterToolCall=e=>this._afterToolCall(e)}async _beforeToolCall({toolCall:e,args:t},s){const n=t??{},o=Je({toolName:e.name,input:n,cwd:this._cwd},{rules:this._permissionRules,readGuard:this._readGuard});if(o?.behavior==="deny")return{block:!0,reason:o.reason};const i=this._extensionRunner;let r;if(i.hasHandlers("tool_call"))try{r=await i.emitToolCall({type:"tool_call",toolName:e.name,toolCallId:e.id,...s?{parentToolCallId:s}:{},input:n})}catch(a){throw a instanceof Error?a:new Error(`Extension failed, blocking execution: ${String(a)}`)}if(r?.block)return r;if(o?.behavior==="ask"){const a=await this._askPermission({toolCallId:e.id,toolName:e.name,input:n,cwd:this._cwd,rule:o.rule,source:o.source});if(!a.approved)return{block:!0,reason:`Not approved (permission rule ${o.rule} asks first)${a.message?`: ${a.message}`:"."}`}}return r}async _afterToolCall({toolCall:e,args:t,result:s,isError:n},o){const i=this._extensionRunner,r=i.hasHandlers("tool_result")?await i.emitToolResult({type:"tool_result",toolName:e.name,toolCallId:e.id,...o?{parentToolCallId:o}:{},input:t,content:s.content,details:s.details,...s.structuredContent===void 0?{}:{structuredContent:s.structuredContent},isError:n,usage:s.usage}):void 0,a=r?.content??s.content??[],l=this._limitsModel()?.inputLimits?.images?.resize,h=await Ae(a,{autoResizeImages:this.settingsManager.getImageAutoResize(),...l?{resizeOptions:l}:{}});if(!(!r&&h===a))return{content:h,details:r?.details,structuredContent:r?r.structuredContent:s.structuredContent,isError:r?.isError??n,usage:r?.usage}}async _executeNestedToolCall(e,t,s,n){return this._nestedToolCalls??=new Ge({getTools:c(()=>this._getCallableTools(),"getTools"),isSequential:c(()=>this.agent.toolExecution==="sequential","isSequential"),runToolCall:c((o,i,r,a)=>{const l=this._findLastAssistantMessage();return l?he(o,{tools:this._getCallableTools(),assistantMessage:l,context:{messages:this.agent.state.messages,tools:this.agent.state.tools},beforeToolCall:c(h=>this._beforeToolCall(h,i),"beforeToolCall"),afterToolCall:c(h=>this._afterToolCall(h,i),"afterToolCall"),signal:r,onUpdate:a}):Promise.resolve({toolCall:o,result:{content:[{type:"text",text:"No assistant message issued this call"}],details:{}},isError:!0})},"runToolCall"),emit:c(async o=>{await this._extensionRunner.emit(o),this._emit(o)},"emit")}),this._nestedToolCalls.execute(e,t,s,n)}_compactionBaseTokens(){let e=this.agent.state.systemPrompt.length;for(const t of this.agent.state.tools)e+=t.name.length+(t.description?.length??0)+JSON.stringify(t.parameters??{}).length;return Math.ceil(e/4)}_exceedsCompactionThreshold(e,t){return e.contextWindow<=0?!1:V(S(t,this.sessionManager.getBranch()).tokens,e.contextWindow,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_compactionThresholdFor(e){return G(e,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_pruneToolOutputsInsteadOfCompacting(e){const t=this.settingsManager.getCompactionSettings(this.model);if(!t.pruneToolOutputs||!Number.isFinite(e)||e<=0)return!1;const s=this.sessionManager.buildSessionProjection(),n=S(s,this.sessionManager.getBranch()).tokens,o=Be(s,t.keepRecentTokens);if(o.edits.length===0||n-o.tokensSaved>e*Ne)return!1;for(const i of o.edits){const r=this.sessionManager.getEntry(this.sessionManager.appendContextEdit(i.targetId,{content:i.content}));r&&this._emit({type:"entry_appended",entry:r})}return this._refreshFinalizedContext(),!0}async _compactBeforeNextAssistantResponse(e){const t=this.sessionManager.buildSessionProjection(),s=this.model;return!s||C(s)||!this._exceedsCompactionThreshold(s,t)?{...e,messages:t.messages}:(await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(s.contextWindow)),{...e,messages:this.sessionManager.buildSessionProjection().messages})}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n=this._failedResponse;this._failedResponse=void 0;const o=c(async()=>{const _=this.sessionManager.buildSessionProjection(),f={...t.context,messages:_.messages,tools:this.agent.state.tools.slice()},w=await e?.({...t,context:f,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{previous:w,context:w?.context??f,projection:_}},"prepare");let{previous:i,context:r,projection:a}=await o();const l=i?.model??this.agent.state.model,h=i?.thinkingLevel??this.agent.state.thinkingLevel;if(!C(l))return{...i,context:r,model:l,thinkingLevel:h};const u=r.messages.findLastIndex(_=>_.role==="assistant"),m=r.messages.slice(u+1).some(_=>_.role==="user"),d=wt(this.sessionManager.getBranch(),l.provider,l.id),g=await this._modelRuntime.resolveModel(l,F(r.messages),{reason:n?"retry":m?"user":"continuation",thinkingLevel:h,signal:s,failed:n,state:d});if(g.state!==void 0&&g.state!==d){const _={provider:l.provider,modelId:l.id,state:g.state},f=this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(bt,_));f&&this._emit({type:"entry_appended",entry:f})}return this._exceedsCompactionThreshold(g.model,a)&&(await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(g.model.contextWindow)),{previous:i,context:r}=await o()),{...i,context:r,model:g.model,thinkingLevel:g.thinkingLevel}}}async _dispatchTurnEndBoundary(e,t){this._lastActivityOutcome=e.stopReason==="aborted"?"aborted":e.stopReason==="error"?"error":"completed";const s=this._findPersistedMessageEntryId(e);if(!this._extensionRunner.hasHandlers("turn_end"))return!1;if(!s)return this._extensionRunner.emitError({extensionPath:"<boundary>",event:"turn_end",error:"turn_end could not resolve the persisted assistant entry ID"}),!1;const n=t.flatMap(i=>{const r=this._findPersistedMessageEntryId(i);return r?[r]:[]}),o=await this._extensionRunner.emitBoundary({type:"turn_end",turnIndex:this._turnIndex,message:e,toolResults:t,messageEntryId:s,toolResultEntryIds:n,outcome:this._lastActivityOutcome},i=>this._buildBoundaryContext(i,"turn_end"));return this._commitBoundaryDrafts(o.entries),o.continue&&!this._buildBoundaryContext([],"turn_end").canContinue?(this._reportInvalidBoundaryContinuation("turn_end"),!1):o.continue}_installAgentBoundaryHooks(){const e=this.agent.finishTurn;this.agent.finishTurn=async(t,s)=>{this._boundaryDispatchedMessages.add(t.message);const n=await this._dispatchTurnEndBoundary(t.message,t.toolResults),o=await e?.(t,s);if(o?.action==="end")return o;if(n||o?.action==="continue")return{action:"continue"}}}_installAgentNextTurnRefresh(){const e=this.agent.prepareNextTurnWithContext??(this.agent.prepareNextTurn?async(t,s)=>await this.agent.prepareNextTurn?.(s):void 0);this.agent.prepareNextTurnWithContext=async(t,s)=>{const n=await this._compactBeforeNextAssistantResponse(t.context),o=await e?.({...t,context:n},s),i=o?.context??n,r=this._runSystemPromptOptions??this._baseSystemPromptOptions,a=se({...r,selectedTools:this.getActiveToolNames(),toolSnippets:{...this._baseSystemPromptOptions.toolSnippets,...r.toolSnippets},toolGuidelines:{...this._baseSystemPromptOptions.toolGuidelines,...r.toolGuidelines}}),l=this._preparePromptAndToolLoadout(a,i.messages);return this._runSystemPromptOptions=a,{...o,context:{...i,tools:this.agent.state.tools.slice()},messages:l?[...o?.messages??[],l]:o?.messages,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel}}}_refreshFinalizedContext(){const e=this.sessionManager.buildSessionProjection();for(const t of e.entries)for(const s of t.messages)this._entryIdsByMessage.set(s,t.sourceEntry.id);this.agent.state.messages=e.messages}_applyBoundaryDrafts(e,t){const s=[];for(const n of t){let o;switch(n.type){case"custom":o=e.appendCustomEntry(n.customType,n.data);break;case"custom_message":o=e.appendCustomMessageEntry(n.customType,n.content,n.display,n.details);break;case"context_edit":o=e.appendContextEdit(n.targetId,n.replacement);break;case"compaction":{const r=S(e.buildSessionProjection(),e.getBranch()).tokens;o=e.appendCompaction(n.summary,n.firstKeptEntryId,r,n.details,!0,n.usage);break}}const i=e.getEntry(o);i&&s.push(i)}return s}_createBoundaryPreviewManager(e){const t=this.sessionManager.getHeader();if(!t)throw new Error("Session header is missing");const s=at.inMemory(this._cwd,void 0,[t,...this.sessionManager.getBranch()]);return this._applyBoundaryDrafts(s,e),s}_getPendingBoundaryMessages(){return[...this.agent.peekQueuedMessages(),...this._pendingCustomMessages]}_buildBoundaryContext(e,t){const s=this._createBoundaryPreviewManager(e).buildSessionProjection(),n=this._getPendingBoundaryMessages(),o=F(s.messages),i=o[o.length-1]?.role,a=o.some(h=>h.role!=="system")&&i!=="assistant",l=this._pendingCustomMessages.length>0;return{contextEntries:s.entries,contextMessages:s.messages,llmMessages:o,pendingMessages:n,canContinue:a||l||(t==="turn_end"?this.agent.hasQueuedMessages():i==="assistant"&&this.agent.hasQueuedMessages())}}_commitBoundaryDrafts(e){const t=this._applyBoundaryDrafts(this.sessionManager,e);this._refreshFinalizedContext();for(const s of t)this._emit({type:"entry_appended",entry:s})}_reportInvalidBoundaryContinuation(e){this._extensionRunner.emitError({extensionPath:"<boundary>",event:e,error:`${e} requested continuation without runnable model context`})}_emit(e){for(const t of this._eventListeners)t(e)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}async _emitSessionCompactFailed(e){this._extensionRunner.hasHandlers("session_compact_failed")&&await this._extensionRunner.emit({type:"session_compact_failed",...e})}_getIdleWaitPromise(){return this._idleWaitPromise||(this._idleWaitPromise=new Promise(e=>{this._resolveIdleWait=e})),this._idleWaitPromise}_resolveIdleWaitIfIdle(){if(!this.isIdle||!this._resolveIdleWait)return;const e=this._resolveIdleWait;this._idleWaitPromise=void 0,this._resolveIdleWait=void 0,e()}async _emitAgentSettled(){this._cacheWarmer?.onAgentSettled(),this._isAgentRunActive=!1,this._isEmittingAgentSettled=!0;try{const t=this._agentRunAbortRequested;await this._extensionRunner.emit({type:"agent_settled",aborted:t}),this._emit({type:"agent_settled",aborted:t})}finally{this._isEmittingAgentSettled=!1}const e=this._deferredSettledActions.splice(0);if(e.length>0){try{for(const t of e)await t()}finally{this._resolveIdleWaitIfIdle()}return}this._resolveIdleWaitIfIdle()}_handleAgentEvent=c(async e=>{if(this._nestedToolCalls)if(e.type==="message_start"&&e.message.role==="toolResult"){const t=e.message,s=this._nestedToolCalls.takeRecord(t.toolCallId);s?.calls&&(t.nestedCalls=s.calls),s?.usage&&(t.usage=t.usage?_t(t.usage,s.usage):s.usage)}else e.type==="agent_end"&&this._nestedToolCalls.clear();if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=P(e.message.content,"");if(t){const s=this._steeringMessages.indexOf(t);if(s!==-1)this._steeringMessages.splice(s,1),this._emitQueueUpdate();else{const n=this._followUpMessages.indexOf(t);n!==-1&&(this._followUpMessages.splice(n,1),this._emitQueueUpdate())}}}if(e.type==="message_end"&&e.message.role==="assistant"){const t=e.message,s=De(t);if(s!==t){e.message=s;const n=this.agent.state.messages;for(let o=n.length-1;o>=0;o--)if(n[o]===t){n[o]=s;break}}}if(await this._emitExtensionEvent(e),this._emit(e.type==="agent_end"?{...e,willRetry:this._willRetryAfterAgentEnd(e)}:e),e.type==="message_end"){let t;if(e.message.role==="custom"?t=this.sessionManager.appendCustomMessageEntry(e.message.customType,e.message.content,e.message.display,e.message.details):(e.message.role==="system"||e.message.role==="user"||e.message.role==="assistant"||e.message.role==="toolResult")&&(t=this.sessionManager.appendMessage(e.message)),t&&this._entryIdsByMessage.set(e.message,t),e.message.role==="assistant"){const s=e.message;this._lastAssistantMessage=s,s.stopReason!=="error"&&s.stopReason!=="length"&&(this._overflowRecoveryAttempted=!1),s.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}}e.type==="turn_end"&&(this._lastAssistantToolResults=e.toolResults,this._flushPendingCustomMessages())},"_handleAgentEvent");_willRetryAfterAgentEnd(e){if(this._agentRunAbortRequested)return!1;const t=this.settingsManager.getRetrySettings();if(!t.enabled||this._retryAttempt>=t.maxRetries)return!1;for(let s=e.messages.length-1;s>=0;s--){const n=e.messages[s];if(n.role==="assistant")return this._isRetryableError(n)}return!1}_findPersistedMessageEntryId(e){const t=this._entryIdsByMessage.get(e);if(t)return t;for(const i of[...this.sessionManager.getBranch()].reverse())if(i.type==="message"&&i.message===e)return i.id;const s=this.agent.state.messages.indexOf(e);if(s<0)return;const n=this.sessionManager.buildSessionProjection();let o=0;for(const i of n.entries)for(let r=0;r<i.messages.length;r++){if(o===s)return this._entryIdsByMessage.set(e,i.sourceEntry.id),i.sourceEntry.id;o++}}_omitRecoveryAttempt(e,t=[]){const s=[e,...t],n=s.map(i=>this._findPersistedMessageEntryId(i));if(s.some((i,r)=>n[r]===void 0&&this.agent.state.messages.includes(i)))throw new Error("Cannot persist recovery omission because a projected message has no source entry");for(const i of n){if(!i)continue;const r=this.sessionManager.appendContextEdit(i,null),a=this.sessionManager.getEntry(r);a&&this._emit({type:"entry_appended",entry:a})}this._refreshFinalizedContext()}_findLastAssistantMessage(){const e=this.agent.state.messages;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s.role==="assistant")return s}}_replaceMessageInPlace(e,t){if(e===t)return;const s=e;for(const n of Object.keys(s))delete s[n];Object.assign(s,t)}async _emitExtensionEvent(e){if(e.type==="agent_start")this._turnIndex=0,await this._extensionRunner.emit({type:"agent_start"});else if(e.type==="agent_end")await this._extensionRunner.emit({type:"agent_end",messages:e.messages});else if(e.type==="turn_start"){const t={type:"turn_start",turnIndex:this._turnIndex,timestamp:Date.now()};await this._extensionRunner.emit(t)}else if(e.type==="turn_end")e.message.role==="assistant"&&!this._boundaryDispatchedMessages.delete(e.message)&&await this._dispatchTurnEndBoundary(e.message,e.toolResults),this._turnIndex++;else if(e.type==="message_start"){const t={type:"message_start",message:e.message};await this._extensionRunner.emit(t)}else if(e.type==="message_update"){const t={type:"message_update",message:e.message,assistantMessageEvent:e.assistantMessageEvent};await this._extensionRunner.emit(t)}else if(e.type==="message_end"){const t={type:"message_end",message:e.message},s=await this._extensionRunner.emitMessageEnd(t);if(s){const n=(s.role==="user"||s.role==="assistant"||s.role==="toolResult"||s.role==="custom")&&s.content==null?{...s,content:[]}:s;this._replaceMessageInPlace(e.message,n)}}else if(e.type==="tool_execution_start"){const t={type:"tool_execution_start",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_update"){const t={type:"tool_execution_update",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_end"){const t={type:"tool_execution_end",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi 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()."),this._disconnectFromAgent(),this._eventListeners=[];const e=this._shellSandbox,t=this._sandboxScratch;this._sandboxScratch=void 0,this._backgroundProcesses.stopAll().finally(()=>(t&&le(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),me(this.sessionId)}refreshContext(){this._refreshFinalizedContext()}get state(){return this.agent.state}get cacheWarmingStatus(){return this._cacheWarmer?.status}setCacheWarmingMode(e){this.settingsManager.setCacheWarmingMode(e),this._cacheWarmer?.onModeChanged()}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get routedModel(){if(!this.model||!C(this.model))return;const e=xt(this.agent.state.messages),t=e&&this._modelRuntime.getPhysicalModel(e.provider,e.model);return t&&{model:t,thinkingLevel:e?.thinkingLevel}}get isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return ct(this._runSystemPromptOptions??this._baseSystemPromptOptions)}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}getCallableToolNames(){return this._getCallableTools().map(e=>e.name)}isToolAllowed(e){return this._isAllowedTool(e)}getToolDenylist(){return this._excludedToolEntries&&this._excludedToolEntries.length>0?[...this._excludedToolEntries]:void 0}getToolAllowlist(){if(this._allowedToolEntries)return this._allowedToolEntries.filter(e=>!this._excludedTools?.(e))}getAllTools(){return Array.from(this._toolDefinitions.values()).map(({definition:e,sourceInfo:t})=>({name:e.name,description:e.description,parameters:e.parameters,promptGuidelines:e.promptGuidelines,exposure:this._getToolExposure(e.name),...e.namespace?{namespace:e.namespace}:{},...e.annotations?{annotations:{...e.annotations}}:{},sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=this.getActiveToolNames();this._setActiveTools(e);const s=new Set(this.getActiveToolNames());t.some(n=>!s.has(n))&&this._pendingToolNames.clear()}_setActiveTools(e){const t=this._applyToolLoadout(e);for(const s of t)this._pendingToolNames.delete(s.name);this._rebuildSystemPrompt(t.map(s=>s.name))}_isAllowedTool(e){return this._excludedTools?.(e)?!1:!this._allowedTools||this._allowedTools(e)?!0:!this._allowlistFiltersMcp&&X(e)}_isActivatable(e){return!this._allowedTools||this._allowedTools(e)||!X(e)?!0:this._getToolExposure(e)!=="direct"&&this._toolRegistry.has("tool_search")}_getToolExposure(e){return this._toolDefinitions.get(e)?.definition.exposure??"direct"}_getCallableTools(e=new Set(this.getActiveToolNames())){return[...this._toolRegistry.values()].filter(t=>{const s=this._getToolExposure(t.name);return s==="codemode"||s==="deferred"||s==="direct"&&e.has(t.name)})}_applyToolLoadout(e){const t=[...new Set(e)].flatMap(i=>{const r=this._toolRegistry.get(i);return r&&this._getToolExposure(i)!=="hidden"&&this._isActivatable(i)?[r]:[]}),s=t.flatMap(i=>{const r=this._toolDefinitions.get(i.name);return r?.definition.prepareLoadout?[r]:[]}),n=new Set;let o=t;if(s.length>0){const i={declared:t,callable:this._getCallableTools(new Set(t.map(a=>a.name))),registered:[...this._toolRegistry.values()],getExposure:c(a=>this._getToolExposure(a),"getExposure"),getNamespace:c(a=>this._toolDefinitions.get(a)?.definition.namespace,"getNamespace"),getPromptGuidelines:c(a=>this._toolPromptGuidelines.get(a)??[],"getPromptGuidelines")},r=new Map;for(const{definition:a,sourceInfo:l}of s)try{const h=a.prepareLoadout?.(i);for(const[u,m]of Object.entries(h?.descriptions??{}))r.set(u,m);for(const u of h?.hiddenDeclarations??[])n.add(u)}catch(h){this._extensionRunner.emitError({extensionPath:l.path,event:"prepare_loadout",error:h instanceof Error?h.message:String(h),stack:h instanceof Error?h.stack:void 0})}o=t.map(a=>{const l=r.get(a.name);return l===void 0?a:{...a,description:l}})}return this._hiddenDeclarations=n,this.agent.state.tools=o,o}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get sessionName(){return this.sessionManager.getSessionName()}get scopedModels(){return this._scopedModels}setScopedModels(e){this._scopedModels=e}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(e){if(!e)return;const t=e.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();return t.length>0?t:void 0}_normalizePromptGuidelines(e){if(!e||e.length===0)return[];const t=new Set;for(const s of e){const n=s.trim();n.length>0&&t.add(n)}return Array.from(t)}_rebuildSystemPrompt(e){const t=e.filter(l=>this._toolRegistry.has(l)),s={};for(const l of this._toolRegistry.keys()){const h=this._toolPromptSnippets.get(l);h&&(s[l]=h)}const n=this._resourceLoader.getSystemPrompt(),o=this._resourceLoader.getAppendSystemPrompt(),i=o.length>0?o.join(`
1
+ var re=Object.defineProperty;var c=(T,e)=>re(T,"name",{value:e,configurable:!0});import{readFileSync as ae,rmSync as le}from"node:fs";import{basename as de,dirname as ce}from"node:path";import{runToolCall as he}from"@earendil-works/pi-agent-core";import{contentText as P,getCurrentSystemMessage as N,retryDelayMs as ue}from"@earendil-works/pi-ai";import{clampThinkingLevel as z,cleanupSessionResources as me,getSupportedThinkingLevels as ge,isContextOverflow as B,isRecoverableLength as pe,isRetryableAssistantError as fe,modelsAreEqual as k,resetApiProviders as _e,streamSimple as ye}from"@earendil-works/pi-ai/compat";import{configureShellEnvironment as xe}from"../dal/child-env.js";import{fill as q,t as I}from"../dal/i18n.js";import{getThemeByName as Me,theme as we}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as be}from"../utils/frontmatter.js";import{processImage as Te}from"../utils/image-process.js";import{setOutputFileDirectory as Re}from"../utils/output-files.js";import{sleep as Ae}from"../utils/sleep.js";import{normalizeToolResultImages as Ce}from"../utils/tool-result-images.js";import{formatNoApiKeyFoundMessage as O,formatNoModelSelectedMessage as H}from"./auth-guidance.js";import{BackgroundProcessManager as ve}from"./background-processes.js";import{executeBashWithOperations as Se}from"./bash-executor.js";import{generateBugReportSummary as Ee}from"./bug-report.js";import{calculateContextTokens as $,collectEntriesForBranchSummary as Pe,compact as ke,compactionThreshold as G,estimateContextTokens as Ie,estimateProjectedContextTokens as S,estimateTokens as Le,generateBranchSummary as Ne,PRUNE_TARGET_RATIO as Be,planToolOutputPruning as Oe,prepareCompaction as Q,shouldCompact as V}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as De,THINKING_LEVEL_OPTIONS as Fe}from"./defaults.js";import{markBlankAssistantAsError as Ue}from"./empty-assistant.js";import{exportSessionToHtml as We}from"./export-html/index.js";import{createToolHtmlRenderer as je}from"./export-html/tool-renderer.js";import{ExtensionRunner as ze,wrapRegisteredTools as K}from"./extensions/index.js";import{emitSessionShutdownEvent as qe}from"./extensions/runner.js";import{createToolNameMatcher as J,isMcpToolName as X}from"./mcp-servers.js";import{convertToLlm as D}from"./messages.js";import{ModelRegistry as He}from"./model-registry.js";import{isPlaceholderModel as $e,pickHouseModel as Ge}from"./model-resolver.js";import{NestedToolCallRunner as Qe}from"./nested-tool-calls.js";import{buildRuleSet as Ve,EMPTY_RULE_SET as Ke}from"./permissions/rules.js";import{buildReadGuard as Je,evaluateToolPolicy as Xe,permissionAskHandlers as Ye,setProcessReadGuard as Ze}from"./permissions/tool-policy.js";import{expandPromptTemplate as Y}from"./prompt-templates.js";import{filesystemRules as et,resolveSandboxPolicy as tt,SANDBOX_ENV as st,sandboxEnvironmentValue as nt}from"./sandbox/policy.js";import{createScratchDir as ot,ShellSandbox as it,setProcessShellSandbox as rt}from"./sandbox/shell-sandbox.js";import{exportSessionToJsonl as at}from"./session-export.js";import{getLatestCompactionEntry as Z,SessionManager as lt}from"./session-manager.js";import{applyToolModifiers as dt,DEFAULT_TOOL_NAMES as ct}from"./settings-manager.js";import{BUILTIN_PATH_PREFIX as ee,createSyntheticSourceInfo as F,isSyntheticPath as te}from"./source-info.js";import{buildSystemPrompt as ht,buildSystemPromptSections as ut,diffSystemPromptSections as mt,normalizeBuildSystemPromptOptions as se}from"./system-prompt.js";import{createLocalBashOperations as gt}from"./tools/bash.js";import{createAllToolDefinitions as pt}from"./tools/index.js";import{createProcessToolDefinition as ft}from"./tools/process.js";import{createToolDefinitionFromAgentTool as _t}from"./tools/tool-definition-wrapper.js";import{addUsageToTotals as L,combineUsage as yt,createUsageTotals as xt}from"./usage-totals.js";import{findLatestResponse as Mt,getBranchSelection as wt,getVirtualModelState as bt,isVirtualModel as C,VIRTUAL_MODEL_STATE_ENTRY as Tt}from"./virtual-models.js";function fs(T){const e=T.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}c(fs,"parseSkillBlock");function ne(T){return T?Object.fromEntries(Object.entries(T).filter(e=>e[1]!==null)):void 0}c(ne,"withoutDeletedHeaders");function oe(T){let e=0;for(const t of T)e+=Le(t);return e}c(oe,"estimateMessagesTokens");class _s{static{c(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_promptAbortGeneration=0;_agentRunAbortRequested=!1;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_branchSummaryAbortController=void 0;_retryAbortController=void 0;_retryAttempt=0;_failedResponse;_bashAbortControllers=new Set;_pendingBashMessages=[];_extensionRunner;_turnIndex=0;_entryIdsByMessage=new WeakMap;_boundaryDispatchedMessages=new WeakSet;_lastAssistantMessage;_lastAssistantToolResults=[];_lastActivityOutcome="completed";_isBeforeSettle=!1;_abortDuringBeforeSettle=!1;_isEmittingAgentSettled=!1;_deferredSettledActions=[];_resourceLoader;_customTools;_baseToolDefinitions=new Map;_cwd;_extensionRunnerRef;_initialActiveToolNames;_pendingToolNames=new Set;_usesDefaultTools;_defaultToolModifiers;_allowedTools;_allowedToolEntries;_excludedToolEntries;_allowlistFiltersMcp=!1;_excludedTools;_baseToolsOverride;_sandboxOptions;_permissionRules=Ke;_readGuard;_shellSandbox;_sandboxScratch;_releaseOutputFileDirectory;_backgroundProcesses;_sessionStartEvent;_extensionUIContext;_extensionMode="print";_extensionCommandContextActions;_extensionAbortHandler;_extensionShutdownHandler;_extensionErrorListener;_extensionErrorUnsubscriber;_modelRuntime;_desiredModel;_cacheWarmer;_toolRegistry=new Map;_nestedToolCalls;_hiddenDeclarations=new Set;_toolDefinitions=new Map;_toolPromptSnippets=new Map;_toolPromptGuidelines=new Map;_baseSystemPromptOptions;_runSystemPromptOptions;constructor(e){this.agent=e.agent,this.sessionManager=e.sessionManager,this.settingsManager=e.settingsManager,this._scopedModels=e.scopedModels??[],this._resourceLoader=e.resourceLoader,this._customTools=e.customTools??[],this._cwd=e.cwd,this._modelRuntime=e.modelRuntime,this._desiredModel=e.desiredModel,this._cacheWarmer=e.cacheWarmer,this._cacheWarmer&&(this._cacheWarmer.onWarmed=t=>this._emit({type:"entry_appended",entry:t})),this._extensionRunnerRef=e.extensionRunnerRef,this._initialActiveToolNames=e.initialActiveToolNames,this._usesDefaultTools=e.usesDefaultTools??!1,this._defaultToolModifiers=e.defaultToolModifiers??[],e.allowedToolNames&&(this._allowedTools=J(e.allowedToolNames),this._allowlistFiltersMcp=e.allowedToolNames.length===0||e.allowedToolNames.some(t=>t.startsWith("mcp__"))),this._excludedTools=e.excludedToolNames?J(e.excludedToolNames):void 0,this._allowedToolEntries=e.allowedToolNames?[...e.allowedToolNames]:void 0,this._excludedToolEntries=e.excludedToolNames?[...e.excludedToolNames]:void 0,this._baseToolsOverride=e.baseToolsOverride,this._sandboxOptions=e.sandbox??{},this._backgroundProcesses=new ve({sandbox:c(()=>this._shellSandbox,"sandbox"),shellPath:c(()=>this.settingsManager.getShellPath(),"shellPath"),onEvent:c(t=>this._emit(t),"onEvent")}),this._sessionStartEvent=e.sessionStartEvent??{type:"session_start",reason:"startup"},this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._installAgentToolHooks(),this._installAgentNextTurnRefresh(),this._installAgentRequestProjection(),this._installAgentBoundaryHooks(),this._installHiddenDeclarationsProjection(),this._installAgentForcedPromptProjection(),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0}),this._initialActiveToolNames===void 0&&this._restoreToolsFromTranscript()}get modelRuntime(){return this._modelRuntime}async _askPermission(e){const t=this._extensionRunner.createContext();for(const i of Ye()){const r=await i(e,t);if(r)return r}if(!t.hasUI)return{approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"};const s=typeof e.input.command=="string"?e.input.command:JSON.stringify(e.input),n=I("\u4EC5\u672C\u6B21\u5141\u8BB8");return await t.ui.select([q(I("\u89C4\u5219 {rule} \u8981\u6C42\u5148\u786E\u8BA4\u518D\u8FD0\u884C\u3002"),{rule:e.rule}),q(I("\u5DE5\u5177\uFF1A{tool}"),{tool:e.toolName}),s].join(`
2
+ `),[n,I("\u62D2\u7EDD")])===n?{approved:!0}:{approved:!1,message:"the user declined"}}getSandboxStatus(){return this._shellSandbox?.status()}get backgroundProcesses(){return this._backgroundProcesses}async _getRequiredRequestAuth(e,t){let s;try{s=await this._modelRuntime.getAuth(e,{signal:t})}catch(o){const i=o instanceof Error?o.cause:void 0;throw i instanceof Error&&i.message==="authHeader requires a resolved API key"?new Error(O(e.provider)):o}if(s&&(s.auth.apiKey||s.auth.headers))return{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:ne(s.auth.headers),env:s.env};throw this._modelRuntime.isUsingOAuth(e.provider)?new Error(`Authentication failed for "${e.provider}". Credentials may have expired or network is unavailable. Run '/login ${e.provider}' to re-authenticate.`):new Error(O(e.provider))}async _getSummarizationRequestAuth(e,t){const{model:s,thinkingLevel:n}=C(e)?await this._modelRuntime.resolveModel(e,D(this.messages),{reason:"direct",thinkingLevel:this.thinkingLevel,signal:t}):{model:e,thinkingLevel:this.thinkingLevel};if(this.agent.streamFunction===ye)return{...await this._getRequiredRequestAuth(s,t),thinkingLevel:n};try{const o=await this._modelRuntime.getAuth(s,{signal:t});return o?{model:o.auth.baseUrl?{...s,baseUrl:o.auth.baseUrl}:s,apiKey:o.auth.apiKey,headers:ne(o.auth.headers),env:o.env,thinkingLevel:n}:{model:s,thinkingLevel:n}}catch(o){if(t?.aborted)throw o;return{model:s,thinkingLevel:n}}}_modelForMessage(e){const t=this.model;return t&&C(t)?this._modelRuntime.getPhysicalModel(e.provider,e.model):t?.provider===e.provider&&t.id===e.model?t:void 0}_recordSelection(){const e=this.model;if(!e)return;const t=c((o,i)=>this._modelRuntime.getModel(o,i),"getModel"),s=wt(this.sessionManager.getBranch(),t);if(!s||s.provider===e.provider&&s.modelId===e.id)return;const n=t(s.provider,s.modelId);!C(e)&&!(n&&C(n))||this.sessionManager.appendModelChange(e.provider,e.id)}_limitsModel(){return this.routedModel?.model??this.model}_installAgentToolHooks(){this.agent.beforeToolCall=e=>this._beforeToolCall(e),this.agent.afterToolCall=e=>this._afterToolCall(e)}async _beforeToolCall({toolCall:e,args:t},s){const n=t??{},o=Xe({toolName:e.name,input:n,cwd:this._cwd},{rules:this._permissionRules,readGuard:this._readGuard});if(o?.behavior==="deny")return{block:!0,reason:o.reason};const i=this._extensionRunner;let r;if(i.hasHandlers("tool_call"))try{r=await i.emitToolCall({type:"tool_call",toolName:e.name,toolCallId:e.id,...s?{parentToolCallId:s}:{},input:n})}catch(a){throw a instanceof Error?a:new Error(`Extension failed, blocking execution: ${String(a)}`)}if(r?.block)return r;if(o?.behavior==="ask"){const a=await this._askPermission({toolCallId:e.id,toolName:e.name,input:n,cwd:this._cwd,rule:o.rule,source:o.source});if(!a.approved)return{block:!0,reason:`Not approved (permission rule ${o.rule} asks first)${a.message?`: ${a.message}`:"."}`}}return r}async _afterToolCall({toolCall:e,args:t,result:s,isError:n},o){const i=this._extensionRunner,r=i.hasHandlers("tool_result")?await i.emitToolResult({type:"tool_result",toolName:e.name,toolCallId:e.id,...o?{parentToolCallId:o}:{},input:t,content:s.content,details:s.details,...s.structuredContent===void 0?{}:{structuredContent:s.structuredContent},isError:n,usage:s.usage}):void 0,a=r?.content??s.content??[],l=this._limitsModel()?.inputLimits?.images?.resize,h=await Ce(a,{autoResizeImages:this.settingsManager.getImageAutoResize(),...l?{resizeOptions:l}:{}});if(!(!r&&h===a))return{content:h,details:r?.details,structuredContent:r?r.structuredContent:s.structuredContent,isError:r?.isError??n,usage:r?.usage}}async _executeNestedToolCall(e,t,s,n){return this._nestedToolCalls??=new Qe({getTools:c(()=>this._getCallableTools(),"getTools"),isSequential:c(()=>this.agent.toolExecution==="sequential","isSequential"),runToolCall:c((o,i,r,a)=>{const l=this._findLastAssistantMessage();return l?he(o,{tools:this._getCallableTools(),assistantMessage:l,context:{messages:this.agent.state.messages,tools:this.agent.state.tools},beforeToolCall:c(h=>this._beforeToolCall(h,i),"beforeToolCall"),afterToolCall:c(h=>this._afterToolCall(h,i),"afterToolCall"),signal:r,onUpdate:a}):Promise.resolve({toolCall:o,result:{content:[{type:"text",text:"No assistant message issued this call"}],details:{}},isError:!0})},"runToolCall"),emit:c(async o=>{await this._extensionRunner.emit(o),this._emit(o)},"emit")}),this._nestedToolCalls.execute(e,t,s,n)}_compactionBaseTokens(){let e=this.agent.state.systemPrompt.length;for(const t of this.agent.state.tools)e+=t.name.length+(t.description?.length??0)+JSON.stringify(t.parameters??{}).length;return Math.ceil(e/4)}_exceedsCompactionThreshold(e,t){return e.contextWindow<=0?!1:V(S(t,this.sessionManager.getBranch()).tokens,e.contextWindow,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_compactionThresholdFor(e){return G(e,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_pruneToolOutputsInsteadOfCompacting(e){const t=this.settingsManager.getCompactionSettings(this.model);if(!t.pruneToolOutputs||!Number.isFinite(e)||e<=0)return!1;const s=this.sessionManager.buildSessionProjection(),n=S(s,this.sessionManager.getBranch()).tokens,o=Oe(s,t.keepRecentTokens);if(o.edits.length===0||n-o.tokensSaved>e*Be)return!1;for(const i of o.edits){const r=this.sessionManager.getEntry(this.sessionManager.appendContextEdit(i.targetId,{content:i.content}));r&&this._emit({type:"entry_appended",entry:r})}return this._refreshFinalizedContext(),!0}async _compactBeforeNextAssistantResponse(e){const t=this.sessionManager.buildSessionProjection(),s=this.model;return!s||C(s)||!this._exceedsCompactionThreshold(s,t)?{...e,messages:t.messages}:(await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(s.contextWindow)),{...e,messages:this.sessionManager.buildSessionProjection().messages})}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n=this._failedResponse;this._failedResponse=void 0;const o=c(async()=>{const _=this.sessionManager.buildSessionProjection(),f={...t.context,messages:_.messages,tools:this.agent.state.tools.slice()},w=await e?.({...t,context:f,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{previous:w,context:w?.context??f,projection:_}},"prepare");let{previous:i,context:r,projection:a}=await o();const l=i?.model??this.agent.state.model,h=i?.thinkingLevel??this.agent.state.thinkingLevel;if(!C(l))return{...i,context:r,model:l,thinkingLevel:h};const u=r.messages.findLastIndex(_=>_.role==="assistant"),m=r.messages.slice(u+1).some(_=>_.role==="user"),d=bt(this.sessionManager.getBranch(),l.provider,l.id),g=await this._modelRuntime.resolveModel(l,D(r.messages),{reason:n?"retry":m?"user":"continuation",thinkingLevel:h,signal:s,failed:n,state:d});if(g.state!==void 0&&g.state!==d){const _={provider:l.provider,modelId:l.id,state:g.state},f=this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(Tt,_));f&&this._emit({type:"entry_appended",entry:f})}return this._exceedsCompactionThreshold(g.model,a)&&(await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(g.model.contextWindow)),{previous:i,context:r}=await o()),{...i,context:r,model:g.model,thinkingLevel:g.thinkingLevel}}}async _dispatchTurnEndBoundary(e,t){this._lastActivityOutcome=e.stopReason==="aborted"?"aborted":e.stopReason==="error"?"error":"completed";const s=this._findPersistedMessageEntryId(e);if(!this._extensionRunner.hasHandlers("turn_end"))return!1;if(!s)return this._extensionRunner.emitError({extensionPath:"<boundary>",event:"turn_end",error:"turn_end could not resolve the persisted assistant entry ID"}),!1;const n=t.flatMap(i=>{const r=this._findPersistedMessageEntryId(i);return r?[r]:[]}),o=await this._extensionRunner.emitBoundary({type:"turn_end",turnIndex:this._turnIndex,message:e,toolResults:t,messageEntryId:s,toolResultEntryIds:n,outcome:this._lastActivityOutcome},i=>this._buildBoundaryContext(i,"turn_end"));return this._commitBoundaryDrafts(o.entries),o.continue&&!this._buildBoundaryContext([],"turn_end").canContinue?(this._reportInvalidBoundaryContinuation("turn_end"),!1):o.continue}_installAgentBoundaryHooks(){const e=this.agent.finishTurn;this.agent.finishTurn=async(t,s)=>{this._boundaryDispatchedMessages.add(t.message);const n=await this._dispatchTurnEndBoundary(t.message,t.toolResults),o=await e?.(t,s);if(o?.action==="end")return o;if(n||o?.action==="continue")return{action:"continue"}}}_installAgentNextTurnRefresh(){const e=this.agent.prepareNextTurnWithContext??(this.agent.prepareNextTurn?async(t,s)=>await this.agent.prepareNextTurn?.(s):void 0);this.agent.prepareNextTurnWithContext=async(t,s)=>{const n=await this._compactBeforeNextAssistantResponse(t.context),o=await e?.({...t,context:n},s),i=o?.context??n,r=this._runSystemPromptOptions??this._baseSystemPromptOptions,a=se({...r,selectedTools:this.getActiveToolNames(),toolSnippets:{...this._baseSystemPromptOptions.toolSnippets,...r.toolSnippets},toolGuidelines:{...this._baseSystemPromptOptions.toolGuidelines,...r.toolGuidelines}}),l=this._preparePromptAndToolLoadout(a,i.messages);return this._runSystemPromptOptions=a,{...o,context:{...i,tools:this.agent.state.tools.slice()},messages:l?[...o?.messages??[],l]:o?.messages,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel}}}_refreshFinalizedContext(){const e=this.sessionManager.buildSessionProjection();for(const t of e.entries)for(const s of t.messages)this._entryIdsByMessage.set(s,t.sourceEntry.id);this.agent.state.messages=e.messages}_applyBoundaryDrafts(e,t){const s=[];for(const n of t){let o;switch(n.type){case"custom":o=e.appendCustomEntry(n.customType,n.data);break;case"custom_message":o=e.appendCustomMessageEntry(n.customType,n.content,n.display,n.details);break;case"context_edit":o=e.appendContextEdit(n.targetId,n.replacement);break;case"compaction":{const r=S(e.buildSessionProjection(),e.getBranch()).tokens;o=e.appendCompaction(n.summary,n.firstKeptEntryId,r,n.details,!0,n.usage);break}}const i=e.getEntry(o);i&&s.push(i)}return s}_createBoundaryPreviewManager(e){const t=this.sessionManager.getHeader();if(!t)throw new Error("Session header is missing");const s=lt.inMemory(this._cwd,void 0,[t,...this.sessionManager.getBranch()]);return this._applyBoundaryDrafts(s,e),s}_getPendingBoundaryMessages(){return[...this.agent.peekQueuedMessages(),...this._pendingCustomMessages]}_buildBoundaryContext(e,t){const s=this._createBoundaryPreviewManager(e).buildSessionProjection(),n=this._getPendingBoundaryMessages(),o=D(s.messages),i=o[o.length-1]?.role,a=o.some(h=>h.role!=="system")&&i!=="assistant",l=this._pendingCustomMessages.length>0;return{contextEntries:s.entries,contextMessages:s.messages,llmMessages:o,pendingMessages:n,canContinue:a||l||(t==="turn_end"?this.agent.hasQueuedMessages():i==="assistant"&&this.agent.hasQueuedMessages())}}_commitBoundaryDrafts(e){const t=this._applyBoundaryDrafts(this.sessionManager,e);this._refreshFinalizedContext();for(const s of t)this._emit({type:"entry_appended",entry:s})}_reportInvalidBoundaryContinuation(e){this._extensionRunner.emitError({extensionPath:"<boundary>",event:e,error:`${e} requested continuation without runnable model context`})}_emit(e){for(const t of this._eventListeners)t(e)}_emitQueueUpdate(){this._emit({type:"queue_update",steering:[...this._steeringMessages],followUp:[...this._followUpMessages]})}async _emitSessionCompactFailed(e){this._extensionRunner.hasHandlers("session_compact_failed")&&await this._extensionRunner.emit({type:"session_compact_failed",...e})}_getIdleWaitPromise(){return this._idleWaitPromise||(this._idleWaitPromise=new Promise(e=>{this._resolveIdleWait=e})),this._idleWaitPromise}_resolveIdleWaitIfIdle(){if(!this.isIdle||!this._resolveIdleWait)return;const e=this._resolveIdleWait;this._idleWaitPromise=void 0,this._resolveIdleWait=void 0,e()}async _emitAgentSettled(){this._cacheWarmer?.onAgentSettled(),this._isAgentRunActive=!1,this._isEmittingAgentSettled=!0;try{const t=this._agentRunAbortRequested;await this._extensionRunner.emit({type:"agent_settled",aborted:t}),this._emit({type:"agent_settled",aborted:t})}finally{this._isEmittingAgentSettled=!1}const e=this._deferredSettledActions.splice(0);if(e.length>0){try{for(const t of e)await t()}finally{this._resolveIdleWaitIfIdle()}return}this._resolveIdleWaitIfIdle()}_handleAgentEvent=c(async e=>{if(this._nestedToolCalls)if(e.type==="message_start"&&e.message.role==="toolResult"){const t=e.message,s=this._nestedToolCalls.takeRecord(t.toolCallId);s?.calls&&(t.nestedCalls=s.calls),s?.usage&&(t.usage=t.usage?yt(t.usage,s.usage):s.usage)}else e.type==="agent_end"&&this._nestedToolCalls.clear();if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=P(e.message.content,"");if(t){const s=this._steeringMessages.indexOf(t);if(s!==-1)this._steeringMessages.splice(s,1),this._emitQueueUpdate();else{const n=this._followUpMessages.indexOf(t);n!==-1&&(this._followUpMessages.splice(n,1),this._emitQueueUpdate())}}}if(e.type==="message_end"&&e.message.role==="assistant"){const t=e.message,s=Ue(t);if(s!==t){e.message=s;const n=this.agent.state.messages;for(let o=n.length-1;o>=0;o--)if(n[o]===t){n[o]=s;break}}}if(await this._emitExtensionEvent(e),this._emit(e.type==="agent_end"?{...e,willRetry:this._willRetryAfterAgentEnd(e)}:e),e.type==="message_end"){let t;if(e.message.role==="custom"?t=this.sessionManager.appendCustomMessageEntry(e.message.customType,e.message.content,e.message.display,e.message.details):(e.message.role==="system"||e.message.role==="user"||e.message.role==="assistant"||e.message.role==="toolResult")&&(t=this.sessionManager.appendMessage(e.message)),t&&this._entryIdsByMessage.set(e.message,t),e.message.role==="assistant"){const s=e.message;this._lastAssistantMessage=s,s.stopReason!=="error"&&s.stopReason!=="length"&&(this._overflowRecoveryAttempted=!1),s.stopReason!=="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!0,attempt:this._retryAttempt}),this._retryAttempt=0)}}e.type==="turn_end"&&(this._lastAssistantToolResults=e.toolResults,this._flushPendingCustomMessages())},"_handleAgentEvent");_willRetryAfterAgentEnd(e){if(this._agentRunAbortRequested)return!1;const t=this.settingsManager.getRetrySettings();if(!t.enabled||this._retryAttempt>=t.maxRetries)return!1;for(let s=e.messages.length-1;s>=0;s--){const n=e.messages[s];if(n.role==="assistant")return this._isRetryableError(n)}return!1}_findPersistedMessageEntryId(e){const t=this._entryIdsByMessage.get(e);if(t)return t;for(const i of[...this.sessionManager.getBranch()].reverse())if(i.type==="message"&&i.message===e)return i.id;const s=this.agent.state.messages.indexOf(e);if(s<0)return;const n=this.sessionManager.buildSessionProjection();let o=0;for(const i of n.entries)for(let r=0;r<i.messages.length;r++){if(o===s)return this._entryIdsByMessage.set(e,i.sourceEntry.id),i.sourceEntry.id;o++}}_omitRecoveryAttempt(e,t=[]){const s=[e,...t],n=s.map(i=>this._findPersistedMessageEntryId(i));if(s.some((i,r)=>n[r]===void 0&&this.agent.state.messages.includes(i)))throw new Error("Cannot persist recovery omission because a projected message has no source entry");for(const i of n){if(!i)continue;const r=this.sessionManager.appendContextEdit(i,null),a=this.sessionManager.getEntry(r);a&&this._emit({type:"entry_appended",entry:a})}this._refreshFinalizedContext()}_findLastAssistantMessage(){const e=this.agent.state.messages;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s.role==="assistant")return s}}_replaceMessageInPlace(e,t){if(e===t)return;const s=e;for(const n of Object.keys(s))delete s[n];Object.assign(s,t)}async _emitExtensionEvent(e){if(e.type==="agent_start")this._turnIndex=0,await this._extensionRunner.emit({type:"agent_start"});else if(e.type==="agent_end")await this._extensionRunner.emit({type:"agent_end",messages:e.messages});else if(e.type==="turn_start"){const t={type:"turn_start",turnIndex:this._turnIndex,timestamp:Date.now()};await this._extensionRunner.emit(t)}else if(e.type==="turn_end")e.message.role==="assistant"&&!this._boundaryDispatchedMessages.delete(e.message)&&await this._dispatchTurnEndBoundary(e.message,e.toolResults),this._turnIndex++;else if(e.type==="message_start"){const t={type:"message_start",message:e.message};await this._extensionRunner.emit(t)}else if(e.type==="message_update"){const t={type:"message_update",message:e.message,assistantMessageEvent:e.assistantMessageEvent};await this._extensionRunner.emit(t)}else if(e.type==="message_end"){const t={type:"message_end",message:e.message},s=await this._extensionRunner.emitMessageEnd(t);if(s){const n=(s.role==="user"||s.role==="assistant"||s.role==="toolResult"||s.role==="custom")&&s.content==null?{...s,content:[]}:s;this._replaceMessageInPlace(e.message,n)}}else if(e.type==="tool_execution_start"){const t={type:"tool_execution_start",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_update"){const t={type:"tool_execution_update",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_end"){const t={type:"tool_execution_end",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi 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()."),this._disconnectFromAgent(),this._eventListeners=[];const e=this._shellSandbox,t=this._sandboxScratch;this._sandboxScratch=void 0,this._releaseOutputFileDirectory?.(),this._releaseOutputFileDirectory=void 0,this._backgroundProcesses.stopAll().finally(()=>(t&&le(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),me(this.sessionId)}refreshContext(){this._refreshFinalizedContext()}get state(){return this.agent.state}get cacheWarmingStatus(){return this._cacheWarmer?.status}setCacheWarmingMode(e){this.settingsManager.setCacheWarmingMode(e),this._cacheWarmer?.onModeChanged()}get model(){return this.agent.state.model}get thinkingLevel(){return this.agent.state.thinkingLevel}get routedModel(){if(!this.model||!C(this.model))return;const e=Mt(this.agent.state.messages),t=e&&this._modelRuntime.getPhysicalModel(e.provider,e.model);return t&&{model:t,thinkingLevel:e?.thinkingLevel}}get isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return ht(this._runSystemPromptOptions??this._baseSystemPromptOptions)}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}getCallableToolNames(){return this._getCallableTools().map(e=>e.name)}isToolAllowed(e){return this._isAllowedTool(e)}getToolDenylist(){return this._excludedToolEntries&&this._excludedToolEntries.length>0?[...this._excludedToolEntries]:void 0}getToolAllowlist(){if(this._allowedToolEntries)return this._allowedToolEntries.filter(e=>!this._excludedTools?.(e))}getAllTools(){return Array.from(this._toolDefinitions.values()).map(({definition:e,sourceInfo:t})=>({name:e.name,description:e.description,parameters:e.parameters,promptGuidelines:e.promptGuidelines,exposure:this._getToolExposure(e.name),...e.namespace?{namespace:e.namespace}:{},...e.annotations?{annotations:{...e.annotations}}:{},sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=this.getActiveToolNames();this._setActiveTools(e);const s=new Set(this.getActiveToolNames());t.some(n=>!s.has(n))&&this._pendingToolNames.clear()}_setActiveTools(e){const t=this._applyToolLoadout(e);for(const s of t)this._pendingToolNames.delete(s.name);this._rebuildSystemPrompt(t.map(s=>s.name))}_isAllowedTool(e){return this._excludedTools?.(e)?!1:!this._allowedTools||this._allowedTools(e)?!0:!this._allowlistFiltersMcp&&X(e)}_isActivatable(e){return!this._allowedTools||this._allowedTools(e)||!X(e)?!0:this._getToolExposure(e)!=="direct"&&this._toolRegistry.has("tool_search")}_getToolExposure(e){return this._toolDefinitions.get(e)?.definition.exposure??"direct"}_getCallableTools(e=new Set(this.getActiveToolNames())){return[...this._toolRegistry.values()].filter(t=>{const s=this._getToolExposure(t.name);return s==="codemode"||s==="deferred"||s==="direct"&&e.has(t.name)})}_applyToolLoadout(e){const t=[...new Set(e)].flatMap(i=>{const r=this._toolRegistry.get(i);return r&&this._getToolExposure(i)!=="hidden"&&this._isActivatable(i)?[r]:[]}),s=t.flatMap(i=>{const r=this._toolDefinitions.get(i.name);return r?.definition.prepareLoadout?[r]:[]}),n=new Set;let o=t;if(s.length>0){const i={declared:t,callable:this._getCallableTools(new Set(t.map(a=>a.name))),registered:[...this._toolRegistry.values()],getExposure:c(a=>this._getToolExposure(a),"getExposure"),getNamespace:c(a=>this._toolDefinitions.get(a)?.definition.namespace,"getNamespace"),getPromptGuidelines:c(a=>this._toolPromptGuidelines.get(a)??[],"getPromptGuidelines")},r=new Map;for(const{definition:a,sourceInfo:l}of s)try{const h=a.prepareLoadout?.(i);for(const[u,m]of Object.entries(h?.descriptions??{}))r.set(u,m);for(const u of h?.hiddenDeclarations??[])n.add(u)}catch(h){this._extensionRunner.emitError({extensionPath:l.path,event:"prepare_loadout",error:h instanceof Error?h.message:String(h),stack:h instanceof Error?h.stack:void 0})}o=t.map(a=>{const l=r.get(a.name);return l===void 0?a:{...a,description:l}})}return this._hiddenDeclarations=n,this.agent.state.tools=o,o}get isCompacting(){return this._autoCompactionAbortController!==void 0||this._compactionAbortController!==void 0||this._branchSummaryAbortController!==void 0}get messages(){return this.agent.state.messages}get steeringMode(){return this.agent.steeringMode}get followUpMode(){return this.agent.followUpMode}get sessionFile(){return this.sessionManager.getSessionFile()}get sessionId(){return this.sessionManager.getSessionId()}get sessionName(){return this.sessionManager.getSessionName()}get scopedModels(){return this._scopedModels}setScopedModels(e){this._scopedModels=e}get promptTemplates(){return this._resourceLoader.getPrompts().prompts}_normalizePromptSnippet(e){if(!e)return;const t=e.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();return t.length>0?t:void 0}_normalizePromptGuidelines(e){if(!e||e.length===0)return[];const t=new Set;for(const s of e){const n=s.trim();n.length>0&&t.add(n)}return Array.from(t)}_rebuildSystemPrompt(e){const t=e.filter(l=>this._toolRegistry.has(l)),s={};for(const l of this._toolRegistry.keys()){const h=this._toolPromptSnippets.get(l);h&&(s[l]=h)}const n=this._resourceLoader.getSystemPrompt(),o=this._resourceLoader.getAppendSystemPrompt(),i=o.length>0?o.join(`
3
3
 
4
- `):"",r=this._resourceLoader.getSkills().skills,a=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=se({cwd:this._cwd,skills:r,contextFiles:a,customPrompt:n,appendSystemPrompt:i,selectedTools:t,hiddenTools:[...this._hiddenDeclarations],toolSnippets:s,toolGuidelines:Object.fromEntries(this._toolPromptGuidelines)})}_preparePromptAndToolLoadout(e,t=this.agent.state.messages){e.selectedTools=this._applyToolLoadout(e.selectedTools).map(n=>n.name),e.hiddenTools=[...this._hiddenDeclarations];const s=ut(N(t)?.sections??{},ht(e));return s?{role:"system",content:"",sections:s,timestamp:Date.now()}:void 0}_installHiddenDeclarationsProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._hiddenDeclarations;return o.size===0?n:n.map(i=>{if(i.role!=="system"||!i.toolsAdded&&!i.toolsRemoved)return i;const{toolsAdded:r,toolsRemoved:a,...l}=i,h=r?.filter(m=>!o.has(m.name))??[],u=a?.filter(m=>!o.has(m.name))??[];return{...l,...h.length>0?{toolsAdded:h}:{},...u.length>0?{toolsRemoved:u}:{}}})}}_installAgentForcedPromptProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._runSystemPromptOptions?.forceSystemPrompt;if(o===void 0)return n;const i=N(n);return[{role:"system",content:o,...i?.toolsAdded?{toolsAdded:i.toolsAdded}:{},timestamp:i?.timestamp??Date.now()},...n.filter(a=>a.role!=="system")]}}_restoreToolsFromTranscript(){this._pendingToolNames.clear();const e=N(this.sessionManager.buildSessionContext().messages);if(!e)return;const t=(e.toolsAdded??[]).map(s=>s.name);this._pendingToolNames=new Set(t.filter(s=>this._isAllowedTool(s))),this._setActiveTools(t)}async _runAgentPrompt(e){this._agentRunAbortRequested=!1,this._failedResponse=void 0,this._recordSelection(),this._pendingToolNames.clear(),this._isAgentRunActive=!0;try{for(await this.agent.prompt(e);!this._agentRunAbortRequested;){if(await this._handlePostAgentRun()){if(this._agentRunAbortRequested)break;await this.agent.continue();continue}if(this._agentRunAbortRequested||!await this._runBeforeSettleBoundary()||this._agentRunAbortRequested)break;await this.agent.continue()}}finally{this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=void 0,this._runSystemPromptOptions=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),await this._emitAgentSettled()}}async _handlePostAgentRun(){const e=this._lastAssistantMessage,t=this._lastAssistantToolResults;return this._lastAssistantMessage=void 0,this._lastAssistantToolResults=[],this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):e?this._isRetryableError(e)&&await this._prepareRetry(e)?(this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=e,!this._agentRunAbortRequested):this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):(e.stopReason==="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!1,attempt:this._retryAttempt,finalError:e.errorMessage}),this._retryAttempt=0),await this._checkCompaction(e,!0,t)?!this._agentRunAbortRequested:!this._agentRunAbortRequested&&this.agent.hasQueuedMessages()):this.agent.hasQueuedMessages()}async _runBeforeSettleBoundary(){if(!this._extensionRunner.hasHandlers("agent_before_settle"))return this.agent.hasQueuedMessages();this._isBeforeSettle=!0,this._abortDuringBeforeSettle=!1;try{const e=await this._extensionRunner.emitBoundary({type:"agent_before_settle",outcome:this._lastActivityOutcome},n=>this._buildBoundaryContext(n,"agent_before_settle"));this._commitBoundaryDrafts(e.entries),this._flushPendingCustomMessages();const t=this._buildBoundaryContext([],"agent_before_settle");if(this._abortDuringBeforeSettle)return!1;const s=e.continue||this.agent.hasQueuedMessages();return s&&!t.canContinue?(e.continue&&this._reportInvalidBoundaryContinuation("agent_before_settle"),!1):s}finally{this._isBeforeSettle=!1}}async _runInputHandlers(e,t,s,n){if(!this._extensionRunner.hasHandlers("input"))return{text:e,images:t};const o=await this._extensionRunner.emitInput(e,t,s,n);if(o.action!=="handled")return o.action==="transform"?{text:o.text,images:o.images??t}:{text:e,images:t}}async _normalizePromptImages(e){if(!e)return{images:[],hints:[]};const t=[],s=[];for(const n of e){const o=await Te(Buffer.from(n.data,"base64"),n.mimeType,{autoResizeImages:this.settingsManager.getImageAutoResize(),resizeOptions:this._limitsModel()?.inputLimits?.images?.resize});if(!o.ok){s.push(o.message);continue}t.push({type:"image",data:o.data,mimeType:o.mimeType}),s.push(...o.hints)}return{images:t,hints:s}}async prompt(e,t){await this._prompt(e,t,this._promptAbortGeneration)}async _prompt(e,t,s){if(this._isEmittingAgentSettled){this._deferredSettledActions.push(async()=>await this._prompt(e,t,s));return}const n=t?.expandPromptTemplates??!0,o=t?.preflightResult,i=c(()=>this._promptAbortGeneration===s?!1:(o?.("cancelled"),!0),"abortedBeforeRun");if(n&&e.startsWith("/")&&await this._tryExecuteExtensionCommand(e,()=>o?.("handled")))return;if(this._compactionAbortController!==void 0)throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");const r=await this._runInputHandlers(e,t?.images,t?.source??"interactive",this.isStreaming?t?.streamingBehavior:void 0);if(i())return;if(!r){o?.("handled");return}const{text:a,images:l}=r;let h=a;if(n&&(h=this._expandSkillCommand(h),h=Y(h,[...this.promptTemplates])),this.isStreaming){if(!t?.streamingBehavior)throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");t.streamingBehavior==="followUp"?await this._queueFollowUp(h,l):await this._queueSteer(h,l),o?.("queued");return}if(this._flushPendingBashMessages(),this._flushPendingCustomMessages(),!this.model)throw new Error(H());const u=this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0;if(i())return;if(!u)throw this._modelRuntime.isUsingOAuth(this.model.provider)?new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`):new Error(O(this.model.provider));const m=this._findLastAssistantMessage();if(m&&(await this._checkCompaction(m,!1),i()))return;const d=this._baseSystemPromptOptions.selectedTools,g=await this._extensionRunner.emitBeforeAgentStart(h,l,this._baseSystemPromptOptions);if(i())return;g.systemPromptOptions.selectedTools.length!==d.length||g.systemPromptOptions.selectedTools.some((y,b)=>y!==d[b])||(g.systemPromptOptions.selectedTools=this.getActiveToolNames());const f=await this._normalizePromptImages(l);if(i())return;const w=f.hints.length>0?`${h}
4
+ `):"",r=this._resourceLoader.getSkills().skills,a=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=se({cwd:this._cwd,gitState:!0,skills:r,contextFiles:a,customPrompt:n,appendSystemPrompt:i,selectedTools:t,hiddenTools:[...this._hiddenDeclarations],toolSnippets:s,toolGuidelines:Object.fromEntries(this._toolPromptGuidelines)})}_preparePromptAndToolLoadout(e,t=this.agent.state.messages){e.selectedTools=this._applyToolLoadout(e.selectedTools).map(n=>n.name),e.hiddenTools=[...this._hiddenDeclarations];const s=mt(N(t)?.sections??{},ut(e));return s?{role:"system",content:"",sections:s,timestamp:Date.now()}:void 0}_installHiddenDeclarationsProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._hiddenDeclarations;return o.size===0?n:n.map(i=>{if(i.role!=="system"||!i.toolsAdded&&!i.toolsRemoved)return i;const{toolsAdded:r,toolsRemoved:a,...l}=i,h=r?.filter(m=>!o.has(m.name))??[],u=a?.filter(m=>!o.has(m.name))??[];return{...l,...h.length>0?{toolsAdded:h}:{},...u.length>0?{toolsRemoved:u}:{}}})}}_installAgentForcedPromptProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,o=this._runSystemPromptOptions?.forceSystemPrompt;if(o===void 0)return n;const i=N(n);return[{role:"system",content:o,...i?.toolsAdded?{toolsAdded:i.toolsAdded}:{},timestamp:i?.timestamp??Date.now()},...n.filter(a=>a.role!=="system")]}}_restoreToolsFromTranscript(){this._pendingToolNames.clear();const e=N(this.sessionManager.buildSessionContext().messages);if(!e)return;const t=(e.toolsAdded??[]).map(s=>s.name);this._pendingToolNames=new Set(t.filter(s=>this._isAllowedTool(s))),this._setActiveTools(t)}async _runAgentPrompt(e){this._agentRunAbortRequested=!1,this._failedResponse=void 0,this._recordSelection(),this._pendingToolNames.clear(),this._isAgentRunActive=!0;try{for(await this.agent.prompt(e);!this._agentRunAbortRequested;){if(await this._handlePostAgentRun()){if(this._agentRunAbortRequested)break;await this.agent.continue();continue}if(this._agentRunAbortRequested||!await this._runBeforeSettleBoundary()||this._agentRunAbortRequested)break;await this.agent.continue()}}finally{this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=void 0,this._runSystemPromptOptions=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),await this._emitAgentSettled()}}async _handlePostAgentRun(){const e=this._lastAssistantMessage,t=this._lastAssistantToolResults;return this._lastAssistantMessage=void 0,this._lastAssistantToolResults=[],this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):e?this._isRetryableError(e)&&await this._prepareRetry(e)?(this._agentRunAbortRequested&&this._finishCancelledRetry(),this._failedResponse=e,!this._agentRunAbortRequested):this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):(e.stopReason==="error"&&this._retryAttempt>0&&(this._emit({type:"auto_retry_end",success:!1,attempt:this._retryAttempt,finalError:e.errorMessage}),this._retryAttempt=0),await this._checkCompaction(e,!0,t)?!this._agentRunAbortRequested:!this._agentRunAbortRequested&&this.agent.hasQueuedMessages()):this.agent.hasQueuedMessages()}async _runBeforeSettleBoundary(){if(!this._extensionRunner.hasHandlers("agent_before_settle"))return this.agent.hasQueuedMessages();this._isBeforeSettle=!0,this._abortDuringBeforeSettle=!1;try{const e=await this._extensionRunner.emitBoundary({type:"agent_before_settle",outcome:this._lastActivityOutcome},n=>this._buildBoundaryContext(n,"agent_before_settle"));this._commitBoundaryDrafts(e.entries),this._flushPendingCustomMessages();const t=this._buildBoundaryContext([],"agent_before_settle");if(this._abortDuringBeforeSettle)return!1;const s=e.continue||this.agent.hasQueuedMessages();return s&&!t.canContinue?(e.continue&&this._reportInvalidBoundaryContinuation("agent_before_settle"),!1):s}finally{this._isBeforeSettle=!1}}async _runInputHandlers(e,t,s,n){if(!this._extensionRunner.hasHandlers("input"))return{text:e,images:t};const o=await this._extensionRunner.emitInput(e,t,s,n);if(o.action!=="handled")return o.action==="transform"?{text:o.text,images:o.images??t}:{text:e,images:t}}async _normalizePromptImages(e){if(!e)return{images:[],hints:[]};const t=[],s=[];for(const n of e){const o=await Te(Buffer.from(n.data,"base64"),n.mimeType,{autoResizeImages:this.settingsManager.getImageAutoResize(),resizeOptions:this._limitsModel()?.inputLimits?.images?.resize});if(!o.ok){s.push(o.message);continue}t.push({type:"image",data:o.data,mimeType:o.mimeType}),s.push(...o.hints)}return{images:t,hints:s}}async prompt(e,t){await this._prompt(e,t,this._promptAbortGeneration)}async _prompt(e,t,s){if(this._isEmittingAgentSettled){this._deferredSettledActions.push(async()=>await this._prompt(e,t,s));return}const n=t?.expandPromptTemplates??!0,o=t?.preflightResult,i=c(()=>this._promptAbortGeneration===s?!1:(o?.("cancelled"),!0),"abortedBeforeRun");if(n&&e.startsWith("/")&&await this._tryExecuteExtensionCommand(e,()=>o?.("handled")))return;if(this._compactionAbortController!==void 0)throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");const r=await this._runInputHandlers(e,t?.images,t?.source??"interactive",this.isStreaming?t?.streamingBehavior:void 0);if(i())return;if(!r){o?.("handled");return}const{text:a,images:l}=r;let h=a;if(n&&(h=this._expandSkillCommand(h),h=Y(h,[...this.promptTemplates])),this.isStreaming){if(!t?.streamingBehavior)throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");t.streamingBehavior==="followUp"?await this._queueFollowUp(h,l):await this._queueSteer(h,l),o?.("queued");return}if(this._flushPendingBashMessages(),this._flushPendingCustomMessages(),!this.model)throw new Error(H());const u=this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0;if(i())return;if(!u)throw this._modelRuntime.isUsingOAuth(this.model.provider)?new Error(`Authentication failed for "${this.model.provider}". Credentials may have expired or network is unavailable. Run '/login ${this.model.provider}' to re-authenticate.`):new Error(O(this.model.provider));const m=this._findLastAssistantMessage();if(m&&(await this._checkCompaction(m,!1),i()))return;const d=this._baseSystemPromptOptions.selectedTools,g=await this._extensionRunner.emitBeforeAgentStart(h,l,this._baseSystemPromptOptions);if(i())return;g.systemPromptOptions.selectedTools.length!==d.length||g.systemPromptOptions.selectedTools.some((y,b)=>y!==d[b])||(g.systemPromptOptions.selectedTools=this.getActiveToolNames());const f=await this._normalizePromptImages(l);if(i())return;const w=f.hints.length>0?`${h}
5
5
 
6
6
  ${f.hints.join(`
7
7
  `)}`:h,p=[],x=[{type:"text",text:w}];x.push(...f.images),p.push({role:"user",content:x,timestamp:Date.now()});for(const y of this._pendingNextTurnMessages)p.push(y);this._pendingNextTurnMessages=[];for(const y of g.messages)p.push({role:"custom",customType:y.customType,content:y.content??[],display:y.display,details:y.details,timestamp:Date.now()});const R=this._preparePromptAndToolLoadout(g.systemPromptOptions);this._runSystemPromptOptions=g.systemPromptOptions,R&&p.unshift(R),o?.("started"),await this._runAgentPrompt(p)}async _tryExecuteExtensionCommand(e,t){const s=e.indexOf(" "),n=s===-1?e.slice(1):e.slice(1,s),o=s===-1?"":e.slice(s+1),i=this._extensionRunner.getCommand(n);if(!i)return!1;const r=this._extensionRunner.createCommandContext();t?.(),this._emit({type:"extension_command_start",command:n});try{return await i.handler(o,r),this._emit({type:"extension_command_end",command:n}),!0}catch(a){const l=a instanceof Error?a.message:String(a);return this._extensionRunner.emitError({extensionPath:`command:${n}`,event:"command",error:l}),this._emit({type:"extension_command_end",command:n,error:l}),!0}}_expandSkillCommand(e){if(!e.startsWith("/skill:"))return e;const t=e.indexOf(" "),s=t===-1?e.slice(7):e.slice(7,t),n=t===-1?"":e.slice(t+1).trim(),o=this.resourceLoader.getSkills().skills.find(i=>i.name===s);if(!o)return e;try{const i=ae(o.filePath,"utf-8"),r=be(i).trim(),a=`<skill name="${o.name}" location="${o.filePath}">
@@ -11,5 +11,5 @@ ${r}
11
11
  </skill>`;return n?`${a}
12
12
 
13
13
  ${n}`:a}catch(i){return this._extensionRunner.emitError({extensionPath:o.filePath,event:"skill_expansion",error:i instanceof Error?i.message:String(i)}),e}}async _queueUserInput(e,t,s,n){e.startsWith("/")&&this._throwIfExtensionCommand(e);const o=await this._runInputHandlers(e,t,n,this.isStreaming?s:void 0);if(!o)return"handled";let i=this._expandSkillCommand(o.text);return i=Y(i,[...this.promptTemplates]),s==="steer"?await this._queueSteer(i,o.images):await this._queueFollowUp(i,o.images),"queued"}async steer(e,t,s){return this._queueUserInput(e,t,"steer",s?.source??"interactive")}async followUp(e,t,s){return this._queueUserInput(e,t,"followUp",s?.source??"interactive")}async _queueSteer(e,t){this._steeringMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.steer({role:"user",content:s,timestamp:Date.now()})}async _queueFollowUp(e,t){this._followUpMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.followUp({role:"user",content:s,timestamp:Date.now()})}_throwIfExtensionCommand(e){const t=e.indexOf(" "),s=t===-1?e.slice(1):e.slice(1,t);if(this._extensionRunner.getCommand(s))throw new Error(`Extension command "/${s}" cannot be queued. Use prompt() or execute the command when not streaming.`)}async sendCustomMessage(e,t){const s={role:"custom",customType:e.customType,content:e.content??[],display:e.display,details:e.details,timestamp:Date.now()};if(t?.deliverAs==="nextTurn")this._pendingNextTurnMessages.push(s);else if(this.isStreaming&&t?.triggerTurn!==!1)t?.deliverAs==="followUp"?this.agent.followUp(s):this.agent.steer(s);else if(t?.triggerTurn){if(this._isEmittingAgentSettled){this._deferredSettledActions.push(async()=>await this._runAgentPrompt(s));return}await this._runAgentPrompt(s)}else this.isStreaming?this._pendingCustomMessages.push(s):this._appendCustomMessage(s)}_appendCustomMessage(e){this.sessionManager.appendCustomMessageEntry(e.customType,e.content,e.display,e.details),this._refreshFinalizedContext(),this._emit({type:"message_start",message:e}),this._emit({type:"message_end",message:e})}_flushPendingCustomMessages(){if(this._pendingCustomMessages.length===0)return;const e=this._pendingCustomMessages;this._pendingCustomMessages=[];for(const t of e)this._appendCustomMessage(t)}async sendUserMessage(e,t){let s,n;if(typeof e=="string")s=e;else{const o=[];n=[];for(const i of e)i.type==="text"?o.push(i.text):n.push(i);s=o.join(`
14
- `),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:t?.expandPromptTemplates??!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this._promptAbortGeneration++,this._isAgentRunActive&&(this._agentRunAbortRequested=!0),this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this._isBeforeSettle&&(this._abortDuringBeforeSettle=!0),this.agent.abort(),await this.waitForIdle()}async waitForIdle(){this.isIdle||await this._getIdleWaitPromise()}async emitProviderAuthenticated(e,t){await this._extensionRunner.emit({type:"provider_authenticated",providerId:e,authType:t})}async _emitModelSelect(e,t,s){k(t,e)||await this._extensionRunner.emit({type:"model_select",model:e,previousModel:t,source:s})}async _reconcileDesiredModel(){const e=this._desiredModel;if(this._desiredModel=void 0,e){const s=this.model;if(s&&s.provider===e.provider&&s.id===e.modelId)return;const n=this._modelRuntime.getModel(e.provider,e.modelId);if(n&&this._modelRuntime.hasConfiguredAuth(n.provider)){await this.setModel(n);return}}if(!He(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=$e([...this._modelRuntime.getAvailableSnapshot()]);if(t)try{await this.setModel(t)}catch{}}async setModel(e,t={}){if(!await this._modelRuntime.checkAuth(e.provider))throw new Error(`No API key for ${e.provider}/${e.id}`);const s=this.model,n=this._getThinkingLevelForModelSwitch(e);this.agent.state.model=e,this.sessionManager.appendModelChange(e.provider,e.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(e.provider,e.id),this._addPersistedDefaultToNonEmptyScope(e)),this.setThinkingLevel(n),await this._emitModelSelect(e,s,"set")}_addPersistedDefaultToNonEmptyScope(e){if(this._scopedModels.length===0||this._scopedModels.some(n=>k(n.model,e)))return;this._scopedModels=[...this._scopedModels,{model:e}];const t=this.settingsManager.getEnabledModels();if(!t?.length)return;const s=`${e.provider}/${e.id}`;t.some(n=>n.toLowerCase()===s.toLowerCase())||this.settingsManager.setEnabledModels([...t,s])}async cycleModel(e="forward",t={}){return this._scopedModels.length>0?this._cycleScopedModel(e,t):this._cycleAvailableModel(e,t)}async _cycleScopedModel(e,t){const s=new Set(this._modelRuntime.getAvailableSnapshot().map(u=>`${u.provider}\0${u.id}`)),n=this._scopedModels.filter(u=>s.has(`${u.model.provider}\0${u.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(u=>k(u.model,o));i===-1&&(i=0);const r=n.length,a=e==="forward"?(i+1)%r:(i-1+r)%r,l=n[a],h=this._getThinkingLevelForModelSwitch(l.model,l.thinkingLevel);return this.agent.state.model=l.model,this.sessionManager.appendModelChange(l.model.provider,l.model.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(l.model.provider,l.model.id),this._addPersistedDefaultToNonEmptyScope(l.model)),this.setThinkingLevel(h),await this._emitModelSelect(l.model,o,"cycle"),{model:l.model,thinkingLevel:this.thinkingLevel,isScoped:!0}}async _cycleAvailableModel(e,t){const s=this._modelRuntime.getAvailableSnapshot();if(s.length<=1)return;const n=this.model;let o=s.findIndex(h=>k(h,n));o===-1&&(o=0);const i=s.length,r=e==="forward"?(o+1)%i:(o-1+i)%i,a=s[r],l=this._getThinkingLevelForModelSwitch(a);return this.agent.state.model=a,this.sessionManager.appendModelChange(a.provider,a.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(a.provider,a.id),this._addPersistedDefaultToNonEmptyScope(a)),this.setThinkingLevel(l),await this._emitModelSelect(a,n,"cycle"),{model:a,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e,t={}){const s=this.getAvailableThinkingLevels(),n=s.includes(e)?e:this._clampThinkingLevel(e,s),o=this.agent.state.thinkingLevel,i=n!==o;this.agent.state.thinkingLevel=n,t.persist&&this.settingsManager.setDefaultThinkingLevel(e),i&&(this.sessionManager.appendThinkingLevelChange(n),this._emit({type:"thinking_level_changed",level:n}),this._extensionRunner.emit({type:"thinking_level_select",level:n,previousLevel:o}))}cycleThinkingLevel(e={}){if(!this.supportsThinking())return;const t=this.getAvailableThinkingLevels(),n=(t.indexOf(this.thinkingLevel)+1)%t.length,o=t[n];return this.setThinkingLevel(o,e),o}getAvailableThinkingLevels(){return this.model?ge(this.model):[...Fe]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return z(e,this._getThinkingLevelForModelSwitch(e))}_getThinkingLevelForModelSwitch(e,t){if(t!==void 0)return t;if(e){const s=this.settingsManager.getModelThinkingLevel(e.provider,e.id);if(s!==void 0)return s}return this.settingsManager.getDefaultThinkingLevel()??this.thinkingLevel??Oe}_clampThinkingLevel(e,t){return this.model?z(this.model,e):"off"}syncQueueModesFromSettings(){this.agent.steeringMode=this.settingsManager.getSteeringMode(),this.agent.followUpMode=this.settingsManager.getFollowUpMode()}setSteeringMode(e){this.agent.steeringMode=e,this.settingsManager.setSteeringMode(e)}setFollowUpMode(e){this.agent.followUpMode=e,this.settingsManager.setFollowUpMode(e)}async _runDefaultCompaction(e,t,s,n,o){const i=this.settingsManager.getCompactionSummaryModel();let r=t;if(i){const l=this._modelRuntime.getModel(i.provider,i.modelId);if(!l)throw new Error(`compaction.summaryModel "${i.provider}/${i.modelId}" is not an available model`);r=l}const a=await this._getSummarizationRequestAuth(r,n);return Pe(e,a.model,a.apiKey,a.headers,s,n,a.thinkingLevel,this.agent.streamFunction,a.env,this.settingsManager.getRetrySettings(),this._summarizationRetryCallbacks({source:"compaction",reason:o}),void 0)}_clearManualCompactionState(){this._compactionAbortController=void 0,this._resolveIdleWaitIfIdle()}async compact(e){await this.abort(),this._compactionAbortController=new AbortController,this._emit({type:"compaction_start",reason:"manual"});let t=!1,s=!1;try{const n=this.model;if(!n)throw new Error(H());const o=this.settingsManager.getCompactionSettings(n),i=this.sessionManager.getBranch(),r=Q(i,o);if(!r)throw i[i.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let a;if(this._extensionRunner.hasHandlers("session_before_compact")){const p=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(p?.cancel)throw s=!0,new Error("Compaction cancelled");p?.compaction&&(a=p.compaction,t=!0)}let l,h,u,m,d;if(a)l=a.summary,h=a.firstKeptEntryId,u=a.tokensBefore,m=a.usage,d=a.details;else{const p=await this._runDefaultCompaction(r,n,e,this._compactionAbortController.signal,"manual");l=p.summary,h=p.firstKeptEntryId,u=p.tokensBefore,m=p.usage,d=p.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,h,u,d,t,m);const g=this.sessionManager.getEntries();this._refreshFinalizedContext();const _=oe(this.sessionManager.buildSessionProjection().messages),f=g.find(p=>p.type==="compaction"&&p.summary===l);this._extensionRunner&&f&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:f,fromExtension:t,reason:"manual",willRetry:!1});const w={summary:l,firstKeptEntryId:h,tokensBefore:u,estimatedTokensAfter:_,usage:m,details:d};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:w,aborted:!1,willRetry:!1}),w}catch(n){const o=n instanceof Error?n.message:String(n),i=this._compactionAbortController.signal.aborted||s,r=i?void 0:`Compaction failed: ${o}`;throw this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:i,willRetry:!1,errorMessage:r}),await this._emitSessionCompactFailed({reason:"manual",errorMessage:r,aborted:i,willRetry:!1,fromExtension:t}),n}finally{this._clearManualCompactionState()}}abortCompaction(){this._compactionAbortController?.abort(),this._autoCompactionAbortController?.abort()}abortBranchSummary(){this._branchSummaryAbortController?.abort()}async _checkCompaction(e,t=!0,s=[]){const n=this.settingsManager.getCompactionSettings(this.model);if(!n.enabled||t&&e.stopReason==="aborted")return!1;const o=this._modelForMessage(e),i=o!==void 0,r=(o??this.model)?.contextWindow??0,a=Z(this.sessionManager.getBranch());if(a!==null&&e.timestamp<=new Date(a.timestamp).getTime())return!1;const h=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),m=u===void 0||h.entries.some(M=>M.sourceEntry.id===u&&M.messages.some(A=>A.role==="assistant")),d=this.sessionManager.getBranch(),g=u?d.findIndex(M=>M.id===u):-1,_=g>=0?d.slice(g+1):[],f=_.some(M=>M.type==="context_edit"),w=_.filter(M=>M.type==="context_edit"&&M.targetId===u).at(-1),p=u===void 0||!_.some(M=>M.type==="compaction")&&w?.replacement!==null,x=m&&!f,R=e.stopReason==="error"&&B(e),y=i&&(R&&p||x&&B(e,r)),b=i&&m&&pe(e,this.settingsManager.getOutputTokenLimit(o.maxTokens));if(y||b){const M=e.stopReason!=="stop";if(!M)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const v=y?"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.":"Truncated response recovery failed after one compact-and-retry attempt.";return this._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:v}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:v,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const A=await this._runAutoCompaction("overflow",M);return A&&(this._failedResponse=e),A}let E;const U=h,ie=U.entries.some(M=>M.sourceEntry.type==="context_edit"),W=e.usage?$(e.usage):0;if(ie)E=S(U,d).tokens;else if(e.stopReason==="error"||W===0){const M=this.agent.state.messages,A=ke(M);if(A.lastUsageIndex!==null){const v=M[A.lastUsageIndex];if(a&&v.role==="assistant"&&v.timestamp<=new Date(a.timestamp).getTime())return!1}E=A.tokens}else E=W;const j=this._compactionBaseTokens();return V(E,r,n,j)?await this._runAutoCompaction("threshold",!1,G(r,n,j)):!1}async _runAutoCompaction(e,t,s){const n=this.model,o=this.settingsManager.getCompactionSettings(n);if(e==="threshold"&&s!==void 0&&this._pruneToolOutputsInsteadOfCompacting(s))return!1;let i,r=!1,a=!1,l=!1;try{if(!n)return!1;const h=this.sessionManager.getBranch(),u=Q(h,o);if(!u)return!1;i=new AbortController,this._autoCompactionAbortController=i,r=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let m;if(this._extensionRunner.hasHandlers("session_before_compact")){const b=await this._extensionRunner.emit({type:"session_before_compact",preparation:u,branchEntries:h,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(b?.cancel)throw l=!0,new Error("Compaction cancelled");b?.compaction&&(m=b.compaction,a=!0)}i.signal.throwIfAborted();let d,g,_,f,w;if(m)d=m.summary,g=m.firstKeptEntryId,_=m.tokensBefore,f=m.usage,w=m.details;else{const b=await this._runDefaultCompaction(u,n,void 0,i.signal,e);d=b.summary,g=b.firstKeptEntryId,_=b.tokensBefore,f=b.usage,w=b.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,g,_,w,a,f);const p=this.sessionManager.getEntries();this._refreshFinalizedContext();const x=oe(this.sessionManager.buildSessionProjection().messages),R=p.find(b=>b.type==="compaction"&&b.summary===d);this._extensionRunner&&R&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:R,fromExtension:a,reason:e,willRetry:t});const y={summary:d,firstKeptEntryId:g,tokensBefore:_,estimatedTokensAfter:x,usage:f,details:w};return this._emit({type:"compaction_end",reason:e,result:y,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(h){const u=h instanceof Error?h.message:"compaction failed",m=i?.signal.aborted===!0||l;if(r){const d=m?void 0:e==="overflow"?`Context overflow recovery failed: ${u}`:`Auto-compaction failed: ${u}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:m,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:m,willRetry:!1,fromExtension:a})}return!1}finally{this._autoCompactionAbortController===i&&(this._autoCompactionAbortController=void 0),this._resolveIdleWaitIfIdle()}}setAutoCompactionEnabled(e){this.settingsManager.setCompactionEnabled(e)}get autoCompactionEnabled(){return this.settingsManager.getCompactionEnabled()}async bindExtensions(e){e.uiContext!==void 0&&(this._extensionUIContext=e.uiContext),e.mode!==void 0&&(this._extensionMode=e.mode),e.commandContextActions!==void 0&&(this._extensionCommandContextActions=e.commandContextActions),e.abortHandler!==void 0&&(this._extensionAbortHandler=e.abortHandler),e.shutdownHandler!==void 0&&(this._extensionShutdownHandler=e.shutdownHandler),e.onError!==void 0&&(this._extensionErrorListener=e.onError),this._applyExtensionBindings(this._extensionRunner),await this._extensionRunner.emit(this._sessionStartEvent),await this._reconcileDesiredModel(),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions(this._sessionStartEvent.reason==="reload"?"reload":"startup")}async extendResourcesFromExtensions(e){if(!this._extensionRunner.hasHandlers("resources_discover"))return;const{skillPaths:t,promptPaths:s,themePaths:n}=await this._extensionRunner.emitResourcesDiscover(this._cwd,e);if(t.length===0&&s.length===0&&n.length===0)return;const o={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(o),this._rebuildSystemPrompt(this.getActiveToolNames())}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=te(t.extensionPath)?void 0:ce(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return te(e)?`extension:${e.replace(/[<>]/g,"")}`:`extension:${de(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRuntime.getModel(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=c(()=>{const s=e.getRegisteredCommands().map(i=>({name:i.invocationName,description:i.description,source:"extension",sourceInfo:i.sourceInfo})),n=this.promptTemplates.map(i=>({name:i.name,description:i.description,source:"prompt",sourceInfo:i.sourceInfo})),o=this._resourceLoader.getSkills().skills.map(i=>({name:`skill:${i.name}`,description:i.description,source:"skill",sourceInfo:i.sourceInfo}));return[...s,...n,...o]},"getCommands");e.bindCore({sendMessage:c((s,n)=>{this.sendCustomMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:o instanceof Error?o.message:String(o)})})},"sendMessage"),sendUserMessage:c((s,n)=>{this.sendUserMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:o instanceof Error?o.message:String(o)})})},"sendUserMessage"),appendEntry:c((s,n)=>{const o=this.sessionManager.appendCustomEntry(s,n),i=this.sessionManager.getEntry(o);i&&this._emit({type:"entry_appended",entry:i})},"appendEntry"),emitHostEvent:c((s,n)=>{this._emit({type:"extension_event",name:s,data:n??null})},"emitHostEvent"),setSessionName:c(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:c(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:c((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:c(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:c(()=>this.getAllTools(),"getAllTools"),getSettings:c(()=>this.settingsManager.getSettings(),"getSettings"),setActiveTools:c(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:c(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:c(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:c(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:c(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:c(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:c(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:c(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:c(()=>this.model,"getModel"),getScopedModels:c(()=>this._scopedModels,"getScopedModels"),isIdle:c(()=>this.isIdle,"isIdle"),isProjectTrusted:c(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:c(()=>this.agent.signal,"getSignal"),abort:c(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:c(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:c(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:c(()=>this.getContextUsage(),"getContextUsage"),compact:c(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const o=n instanceof Error?n:new Error(String(n));s?.onError?.(o)}})()},"compact"),getSystemPrompt:c(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:c(()=>this._baseSystemPromptOptions,"getSystemPromptOptions"),executeTool:c((s,n,o,i)=>this._executeNestedToolCall(s,n,o,i),"executeTool"),getCallableTools:c(()=>this._getCallableTools(),"getCallableTools")},{registerProvider:c((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:c(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:c(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider"),registerVirtualModel:c(s=>{this._modelRuntime.registerVirtualModel(s),this._refreshCurrentModelFromRegistry()},"registerVirtualModel"),unregisterVirtualModel:c((s,n)=>{this._modelRuntime.unregisterVirtualModel(s,n),this._refreshCurrentModelFromRegistry()},"unregisterVirtualModel")})}_refreshToolRegistry(e){const t=new Set([...this._toolRegistry.keys()].filter(d=>this._isActivatedOnRegistration(d))),s=this.getActiveToolNames(),n=this._allowedTools,i=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:D(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>this._isAllowedTool(d.definition.name)),r=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>this._isAllowedTool(d)).map(([d,g])=>[d,{definition:g,sourceInfo:D(`${ee}${d}`,{source:"builtin"})}]));for(const d of i)r.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=r,this._toolPromptSnippets=new Map(Array.from(r.values()).map(({definition:d})=>{const g=this._normalizePromptSnippet(d.promptSnippet);return g?[d.name,g]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(r.values()).map(({definition:d})=>{const g=this._normalizePromptGuidelines(d.promptGuidelines);return g.length>0?[d.name,g]:void 0}).filter(d=>d!==void 0));const a=this._extensionRunner,l=K(i,a),h=K(Array.from(this._baseToolDefinitions.values()).filter(d=>this._isAllowedTool(d.name)).map(d=>({definition:d,sourceInfo:D(`${ee}${d.name}`,{source:"builtin"})})),a),u=new Map(h.map(d=>[d.name,d]));for(const d of l)u.set(d.name,d);this._toolRegistry=u;const m=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&m.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&m.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&m.push(d);m.push(...this._pendingToolNames),this._setActiveTools([...new Set(m)])}_isDeclarable(e){const t=this._getToolExposure(e);return t==="direct"||t==="model-only"}_isActivatedOnRegistration(e){return this._isDeclarable(e)&&this._toolDefinitions.get(e)?.definition.defaultActive!==!1}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();xe(this.settingsManager.getShellEnvironmentPolicy());const o=et({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"}),i=new ot({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:c(m=>this._emit(m),"onEvent"),scratchDir:c(()=>(this._sandboxScratch??=nt(),this._sandboxScratch),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=i,r?.dispose(),it(i),process.env[tt]=st(o),this._permissionRules=Qe(this.settingsManager.getPermissionRuleSources()),this._readGuard=Ke({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:Ze(o,this._cwd).denyRead}:{}}),Ye(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([m,d])=>[m,ft(d)])):gt(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i}});this._baseToolDefinitions=new Map(Object.entries(a).map(([m,d])=>[m,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",pt(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[m,d]of e.flagValues)l.runtime.flagValues.set(m,d);this._extensionRunner=new je(l.extensions,l.runtime,this._cwd,this.sessionManager,new qe(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const h=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],u=e.activeToolNames??h;this._refreshToolRegistry({activeToolNames:u,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await ze(t,{type:"session_shutdown",reason:"reload"}),t.invalidate();const n=c(()=>this._usesDefaultTools?lt(this.settingsManager.getDefaultTools()??dt,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),_e(),await this._resourceLoader.reload();const i=n().filter(a=>!o.has(a));for(const a of this.getActiveToolNames())this._pendingToolNames.add(a);this._buildRuntime({activeToolNames:[...this.getActiveToolNames(),...i],flagValues:s,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await e?.beforeSessionStart?.(),await this._extensionRunner.emit({type:"session_start",reason:"reload"}),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions("reload"))}_isRetryableError(e){return B(e,(this._modelForMessage(e)??this.model)?.contextWindow??0)?!1:fe(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:c((t,s,n,o)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:o})},"onRetryScheduled"),onRetryAttemptStart:c(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:c(()=>{this._emit({type:"summarization_retry_finished"})},"onRetryFinished")}}_finishCancelledRetry(){if(this._retryAttempt===0)return;const e=this._retryAttempt;this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:e,finalError:"Retry cancelled"})}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=ue(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await Re(s,this._retryAbortController.signal)}catch{return this._finishCancelledRetry(),!1}finally{this._retryAbortController=void 0}return!0}abortRetry(){this._retryAbortController?.abort()}get isRetrying(){return this._retryAbortController!==void 0}get autoRetryEnabled(){return this.settingsManager.getRetryEnabled()}setAutoRetryEnabled(e){this.settingsManager.setRetryEnabled(e)}async executeBash(e,t,s){const n=new AbortController;this._bashAbortControllers.add(n);const o=this.settingsManager.getShellCommandPrefix(),i=this.settingsManager.getShellPath(),r=o?`${o}
15
- ${e}`:e;try{const a=await ve(r,this.sessionManager.getCwd(),s?.operations??mt({shellPath:i}),{onChunk:c(l=>{t?.(l),this._emit({type:"bash_execution_update",id:s?.id,delta:l})},"onChunk"),signal:n.signal});return this.recordBashResult(e,a,s),a}finally{this._bashAbortControllers.delete(n)}}recordBashResult(e,t,s){const n={role:"bashExecution",command:e,output:t.output,exitCode:t.exitCode,cancelled:t.cancelled,truncated:t.truncated,fullOutputPath:t.fullOutputPath,timestamp:Date.now(),excludeFromContext:s?.excludeFromContext};this.isStreaming?this._pendingBashMessages.push(n):(this.sessionManager.appendMessage(n),this._refreshFinalizedContext())}abortBash(){for(const e of[...this._bashAbortControllers])e.abort()}get isBashRunning(){return this._bashAbortControllers.size>0}get hasPendingBashMessages(){return this._pendingBashMessages.length>0}_flushPendingBashMessages(){if(this._pendingBashMessages.length!==0){for(const e of this._pendingBashMessages)this.sessionManager.appendMessage(e);this._pendingBashMessages=[],this._refreshFinalizedContext()}}setSessionName(e){this.sessionManager.appendSessionInfo(e);const t={type:"session_info_changed",name:this.sessionManager.getSessionName()};this._emit(t),this._extensionRunner.emit(t)}async navigateTree(e,t={}){if(this.isStreaming)throw new Error("Wait for the current response to finish before navigating the session tree.");if(this.isCompacting)throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");const s=this.sessionManager.getLeafId();if(e===s)return{cancelled:!1};if(t.summarize&&!this.model)throw new Error("No model available for summarization");const n=this.sessionManager.getEntry(e);if(!n)throw new Error(`Entry ${e} not found`);const{entries:o,commonAncestorId:i}=Ee(this.sessionManager,s,e);let r=t.customInstructions,a=t.replaceInstructions,l=t.label;const h={targetId:e,oldLeafId:s,commonAncestorId:i,entriesToSummarize:o,userWantsSummary:t.summarize??!1,customInstructions:r,replaceInstructions:a,label:l};this._branchSummaryAbortController=new AbortController;try{let u,m=!1;if(this._extensionRunner.hasHandlers("session_before_tree")){const x=await this._extensionRunner.emit({type:"session_before_tree",preparation:h,signal:this._branchSummaryAbortController.signal});if(x?.cancel)return{cancelled:!0};x?.summary&&t.summarize&&(u=x.summary,m=!0),x?.customInstructions!==void 0&&(r=x.customInstructions),x?.replaceInstructions!==void 0&&(a=x.replaceInstructions),x?.label!==void 0&&(l=x.label)}let d,g,_;if(t.summarize&&o.length>0&&!u){const x=this._branchSummaryAbortController.signal,R=this.settingsManager.getBranchSummarySettings(),y=await Le(o,{...await this._getSummarizationRequestAuth(this.model,x),signal:x,customInstructions:r,replaceInstructions:a,reserveTokens:R.reserveTokens,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),callbacks:this._summarizationRetryCallbacks({source:"branchSummary"})});if(y.aborted)return{cancelled:!0,aborted:!0};if(y.error)throw new Error(y.error);d=y.summary,_=y.usage,g={readFiles:y.readFiles||[],modifiedFiles:y.modifiedFiles||[]}}else u&&(d=u.summary,g=u.details,_=u.usage);let f,w;n.type==="message"&&n.message.role==="user"?(f=n.parentId,w=P(n.message.content,"")):n.type==="custom_message"?(f=n.parentId,w=P(n.content,"")):f=e;let p;if(d){const x=this.sessionManager.branchWithSummary(f,d,g,m,_);p=this.sessionManager.getEntry(x),l&&this.sessionManager.appendLabelChange(x,l)}else f===null?this.sessionManager.resetLeaf():this.sessionManager.branch(f);return l&&!d&&this.sessionManager.appendLabelChange(e,l),this._refreshFinalizedContext(),this._restoreToolsFromTranscript(),await this._extensionRunner.emit({type:"session_tree",newLeafId:this.sessionManager.getLeafId(),oldLeafId:s,summaryEntry:p,fromExtension:d?m:void 0}),{editorText:w,cancelled:!1,summaryEntry:p}}finally{this._branchSummaryAbortController=void 0,this._resolveIdleWaitIfIdle()}}getUserMessagesForForking(){const e=this.sessionManager.getEntries(),t=[];for(const s of e){if(s.type!=="message"||s.message.role!=="user")continue;const n=P(s.message.content,"");n&&t.push({entryId:s.id,text:n})}return t}getSessionStats(){let e=0,t=0,s=0,n=0,o=0;const i=yt();for(const r of this.sessionManager.getEntries()){if(r.type==="usage"?L(i,r.usage):(r.type==="branch_summary"||r.type==="compaction")&&r.usage&&L(i,r.usage),r.type!=="message")continue;n++;const a=r.message;if(a.role==="user")e++;else if(a.role==="toolResult")s++,a.usage&&L(i,a.usage);else if(a.role==="assistant"){t++;const l=a;Array.isArray(l.content)&&(o+=l.content.filter(h=>h.type==="toolCall").length),L(i,l.usage)}}return{sessionFile:this.sessionFile,sessionId:this.sessionId,userMessages:e,assistantMessages:t,toolCalls:o,toolResults:s,totalMessages:n,tokens:{input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,total:i.input+i.output+i.cacheRead+i.cacheWrite},cost:i.cost,contextUsage:this.getContextUsage()}}getContextUsage(){const e=this._limitsModel();if(!e)return;const t=e.contextWindow??0;if(t<=0)return;const s=this.sessionManager.buildSessionProjection(),n=this.sessionManager.getBranch(),o=Z(n);if(o){const a=new Set(s.entries.flatMap(u=>u.messages.some(m=>m.role==="assistant"&&m.stopReason!=="aborted"&&m.stopReason!=="error"&&$(m.usage)>0)?[u.sourceEntry.id]:[])),l=n.findIndex(u=>u.id===o.id);if(!n.slice(l+1).some(u=>a.has(u.id)))return{tokens:null,contextWindow:t,percent:null}}const i=S(s,n),r=i.tokens/t*100;return{tokens:i.tokens,contextWindow:t,percent:r}}async exportToHtml(e,t={}){const s=[t.themeName,this.settingsManager.getTheme()].find(o=>o!==void 0&&Me(o)!==void 0),n=We({getToolRenderers:c(o=>this._extensionRunner.resolveToolRenderers(o,()=>this.getToolDefinition(o)),"getToolRenderers"),theme:we,cwd:this.sessionManager.getCwd()});return await Ue(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return rt(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");return Se({...await this._getSummarizationRequestAuth(t,e.signal),messages:this.messages,hint:e.hint,signal:e.signal,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),sessionId:this.sessionId})}getLastAssistantText(){const e=this.messages.slice().reverse().find(s=>{if(s.role!=="assistant")return!1;const n=s;return!(n.stopReason==="aborted"&&n.content.length===0)});if(!e)return;let t="";for(const s of e.content)s.type==="text"&&(t+=s.text);return t.trim()||void 0}createReplacedSessionContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));return e.sendMessage=(t,s)=>this.sendCustomMessage(t,s),e.sendUserMessage=(t,s)=>this.sendUserMessage(t,s),e}hasExtensionHandlers(e){return this._extensionRunner.hasHandlers(e)}get extensionRunner(){return this._extensionRunner}}export{ps as AgentSession,gs as parseSkillBlock};
14
+ `),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:t?.expandPromptTemplates??!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this._promptAbortGeneration++,this._isAgentRunActive&&(this._agentRunAbortRequested=!0),this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this._isBeforeSettle&&(this._abortDuringBeforeSettle=!0),this.agent.abort(),await this.waitForIdle()}async waitForIdle(){this.isIdle||await this._getIdleWaitPromise()}async emitProviderAuthenticated(e,t){await this._extensionRunner.emit({type:"provider_authenticated",providerId:e,authType:t})}async _emitModelSelect(e,t,s){k(t,e)||await this._extensionRunner.emit({type:"model_select",model:e,previousModel:t,source:s})}async _reconcileDesiredModel(){const e=this._desiredModel;if(this._desiredModel=void 0,e){const s=this.model;if(s&&s.provider===e.provider&&s.id===e.modelId)return;const n=this._modelRuntime.getModel(e.provider,e.modelId);if(n&&this._modelRuntime.hasConfiguredAuth(n.provider)){await this.setModel(n);return}}if(!$e(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Ge([...this._modelRuntime.getAvailableSnapshot()]);if(t)try{await this.setModel(t)}catch{}}async setModel(e,t={}){if(!await this._modelRuntime.checkAuth(e.provider))throw new Error(`No API key for ${e.provider}/${e.id}`);const s=this.model,n=this._getThinkingLevelForModelSwitch(e);this.agent.state.model=e,this.sessionManager.appendModelChange(e.provider,e.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(e.provider,e.id),this._addPersistedDefaultToNonEmptyScope(e)),this.setThinkingLevel(n),await this._emitModelSelect(e,s,"set")}_addPersistedDefaultToNonEmptyScope(e){if(this._scopedModels.length===0||this._scopedModels.some(n=>k(n.model,e)))return;this._scopedModels=[...this._scopedModels,{model:e}];const t=this.settingsManager.getEnabledModels();if(!t?.length)return;const s=`${e.provider}/${e.id}`;t.some(n=>n.toLowerCase()===s.toLowerCase())||this.settingsManager.setEnabledModels([...t,s])}async cycleModel(e="forward",t={}){return this._scopedModels.length>0?this._cycleScopedModel(e,t):this._cycleAvailableModel(e,t)}async _cycleScopedModel(e,t){const s=new Set(this._modelRuntime.getAvailableSnapshot().map(u=>`${u.provider}\0${u.id}`)),n=this._scopedModels.filter(u=>s.has(`${u.model.provider}\0${u.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(u=>k(u.model,o));i===-1&&(i=0);const r=n.length,a=e==="forward"?(i+1)%r:(i-1+r)%r,l=n[a],h=this._getThinkingLevelForModelSwitch(l.model,l.thinkingLevel);return this.agent.state.model=l.model,this.sessionManager.appendModelChange(l.model.provider,l.model.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(l.model.provider,l.model.id),this._addPersistedDefaultToNonEmptyScope(l.model)),this.setThinkingLevel(h),await this._emitModelSelect(l.model,o,"cycle"),{model:l.model,thinkingLevel:this.thinkingLevel,isScoped:!0}}async _cycleAvailableModel(e,t){const s=this._modelRuntime.getAvailableSnapshot();if(s.length<=1)return;const n=this.model;let o=s.findIndex(h=>k(h,n));o===-1&&(o=0);const i=s.length,r=e==="forward"?(o+1)%i:(o-1+i)%i,a=s[r],l=this._getThinkingLevelForModelSwitch(a);return this.agent.state.model=a,this.sessionManager.appendModelChange(a.provider,a.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(a.provider,a.id),this._addPersistedDefaultToNonEmptyScope(a)),this.setThinkingLevel(l),await this._emitModelSelect(a,n,"cycle"),{model:a,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e,t={}){const s=this.getAvailableThinkingLevels(),n=s.includes(e)?e:this._clampThinkingLevel(e,s),o=this.agent.state.thinkingLevel,i=n!==o;this.agent.state.thinkingLevel=n,t.persist&&this.settingsManager.setDefaultThinkingLevel(e),i&&(this.sessionManager.appendThinkingLevelChange(n),this._emit({type:"thinking_level_changed",level:n}),this._extensionRunner.emit({type:"thinking_level_select",level:n,previousLevel:o}))}cycleThinkingLevel(e={}){if(!this.supportsThinking())return;const t=this.getAvailableThinkingLevels(),n=(t.indexOf(this.thinkingLevel)+1)%t.length,o=t[n];return this.setThinkingLevel(o,e),o}getAvailableThinkingLevels(){return this.model?ge(this.model):[...Fe]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return z(e,this._getThinkingLevelForModelSwitch(e))}_getThinkingLevelForModelSwitch(e,t){if(t!==void 0)return t;if(e){const s=this.settingsManager.getModelThinkingLevel(e.provider,e.id);if(s!==void 0)return s}return this.settingsManager.getDefaultThinkingLevel()??this.thinkingLevel??De}_clampThinkingLevel(e,t){return this.model?z(this.model,e):"off"}syncQueueModesFromSettings(){this.agent.steeringMode=this.settingsManager.getSteeringMode(),this.agent.followUpMode=this.settingsManager.getFollowUpMode()}setSteeringMode(e){this.agent.steeringMode=e,this.settingsManager.setSteeringMode(e)}setFollowUpMode(e){this.agent.followUpMode=e,this.settingsManager.setFollowUpMode(e)}async _runDefaultCompaction(e,t,s,n,o){const i=this.settingsManager.getCompactionSummaryModel();let r=t;if(i){const l=this._modelRuntime.getModel(i.provider,i.modelId);if(!l)throw new Error(`compaction.summaryModel "${i.provider}/${i.modelId}" is not an available model`);r=l}const a=await this._getSummarizationRequestAuth(r,n);return ke(e,a.model,a.apiKey,a.headers,s,n,a.thinkingLevel,this.agent.streamFunction,a.env,this.settingsManager.getRetrySettings(),this._summarizationRetryCallbacks({source:"compaction",reason:o}),void 0)}_clearManualCompactionState(){this._compactionAbortController=void 0,this._resolveIdleWaitIfIdle()}async compact(e){await this.abort(),this._compactionAbortController=new AbortController,this._emit({type:"compaction_start",reason:"manual"});let t=!1,s=!1;try{const n=this.model;if(!n)throw new Error(H());const o=this.settingsManager.getCompactionSettings(n),i=this.sessionManager.getBranch(),r=Q(i,o);if(!r)throw i[i.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let a;if(this._extensionRunner.hasHandlers("session_before_compact")){const p=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(p?.cancel)throw s=!0,new Error("Compaction cancelled");p?.compaction&&(a=p.compaction,t=!0)}let l,h,u,m,d;if(a)l=a.summary,h=a.firstKeptEntryId,u=a.tokensBefore,m=a.usage,d=a.details;else{const p=await this._runDefaultCompaction(r,n,e,this._compactionAbortController.signal,"manual");l=p.summary,h=p.firstKeptEntryId,u=p.tokensBefore,m=p.usage,d=p.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,h,u,d,t,m);const g=this.sessionManager.getEntries();this._refreshFinalizedContext();const _=oe(this.sessionManager.buildSessionProjection().messages),f=g.find(p=>p.type==="compaction"&&p.summary===l);this._extensionRunner&&f&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:f,fromExtension:t,reason:"manual",willRetry:!1});const w={summary:l,firstKeptEntryId:h,tokensBefore:u,estimatedTokensAfter:_,usage:m,details:d};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:w,aborted:!1,willRetry:!1}),w}catch(n){const o=n instanceof Error?n.message:String(n),i=this._compactionAbortController.signal.aborted||s,r=i?void 0:`Compaction failed: ${o}`;throw this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:i,willRetry:!1,errorMessage:r}),await this._emitSessionCompactFailed({reason:"manual",errorMessage:r,aborted:i,willRetry:!1,fromExtension:t}),n}finally{this._clearManualCompactionState()}}abortCompaction(){this._compactionAbortController?.abort(),this._autoCompactionAbortController?.abort()}abortBranchSummary(){this._branchSummaryAbortController?.abort()}async _checkCompaction(e,t=!0,s=[]){const n=this.settingsManager.getCompactionSettings(this.model);if(!n.enabled||t&&e.stopReason==="aborted")return!1;const o=this._modelForMessage(e),i=o!==void 0,r=(o??this.model)?.contextWindow??0,a=Z(this.sessionManager.getBranch());if(a!==null&&e.timestamp<=new Date(a.timestamp).getTime())return!1;const h=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),m=u===void 0||h.entries.some(M=>M.sourceEntry.id===u&&M.messages.some(A=>A.role==="assistant")),d=this.sessionManager.getBranch(),g=u?d.findIndex(M=>M.id===u):-1,_=g>=0?d.slice(g+1):[],f=_.some(M=>M.type==="context_edit"),w=_.filter(M=>M.type==="context_edit"&&M.targetId===u).at(-1),p=u===void 0||!_.some(M=>M.type==="compaction")&&w?.replacement!==null,x=m&&!f,R=e.stopReason==="error"&&B(e),y=i&&(R&&p||x&&B(e,r)),b=i&&m&&pe(e,this.settingsManager.getOutputTokenLimit(o.maxTokens));if(y||b){const M=e.stopReason!=="stop";if(!M)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const v=y?"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.":"Truncated response recovery failed after one compact-and-retry attempt.";return this._emit({type:"compaction_end",reason:"overflow",result:void 0,aborted:!1,willRetry:!1,errorMessage:v}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:v,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const A=await this._runAutoCompaction("overflow",M);return A&&(this._failedResponse=e),A}let E;const U=h,ie=U.entries.some(M=>M.sourceEntry.type==="context_edit"),W=e.usage?$(e.usage):0;if(ie)E=S(U,d).tokens;else if(e.stopReason==="error"||W===0){const M=this.agent.state.messages,A=Ie(M);if(A.lastUsageIndex!==null){const v=M[A.lastUsageIndex];if(a&&v.role==="assistant"&&v.timestamp<=new Date(a.timestamp).getTime())return!1}E=A.tokens}else E=W;const j=this._compactionBaseTokens();return V(E,r,n,j)?await this._runAutoCompaction("threshold",!1,G(r,n,j)):!1}async _runAutoCompaction(e,t,s){const n=this.model,o=this.settingsManager.getCompactionSettings(n);if(e==="threshold"&&s!==void 0&&this._pruneToolOutputsInsteadOfCompacting(s))return!1;let i,r=!1,a=!1,l=!1;try{if(!n)return!1;const h=this.sessionManager.getBranch(),u=Q(h,o);if(!u)return!1;i=new AbortController,this._autoCompactionAbortController=i,r=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let m;if(this._extensionRunner.hasHandlers("session_before_compact")){const b=await this._extensionRunner.emit({type:"session_before_compact",preparation:u,branchEntries:h,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(b?.cancel)throw l=!0,new Error("Compaction cancelled");b?.compaction&&(m=b.compaction,a=!0)}i.signal.throwIfAborted();let d,g,_,f,w;if(m)d=m.summary,g=m.firstKeptEntryId,_=m.tokensBefore,f=m.usage,w=m.details;else{const b=await this._runDefaultCompaction(u,n,void 0,i.signal,e);d=b.summary,g=b.firstKeptEntryId,_=b.tokensBefore,f=b.usage,w=b.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,g,_,w,a,f);const p=this.sessionManager.getEntries();this._refreshFinalizedContext();const x=oe(this.sessionManager.buildSessionProjection().messages),R=p.find(b=>b.type==="compaction"&&b.summary===d);this._extensionRunner&&R&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:R,fromExtension:a,reason:e,willRetry:t});const y={summary:d,firstKeptEntryId:g,tokensBefore:_,estimatedTokensAfter:x,usage:f,details:w};return this._emit({type:"compaction_end",reason:e,result:y,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(h){const u=h instanceof Error?h.message:"compaction failed",m=i?.signal.aborted===!0||l;if(r){const d=m?void 0:e==="overflow"?`Context overflow recovery failed: ${u}`:`Auto-compaction failed: ${u}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:m,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:m,willRetry:!1,fromExtension:a})}return!1}finally{this._autoCompactionAbortController===i&&(this._autoCompactionAbortController=void 0),this._resolveIdleWaitIfIdle()}}setAutoCompactionEnabled(e){this.settingsManager.setCompactionEnabled(e)}get autoCompactionEnabled(){return this.settingsManager.getCompactionEnabled()}async bindExtensions(e){e.uiContext!==void 0&&(this._extensionUIContext=e.uiContext),e.mode!==void 0&&(this._extensionMode=e.mode),e.commandContextActions!==void 0&&(this._extensionCommandContextActions=e.commandContextActions),e.abortHandler!==void 0&&(this._extensionAbortHandler=e.abortHandler),e.shutdownHandler!==void 0&&(this._extensionShutdownHandler=e.shutdownHandler),e.onError!==void 0&&(this._extensionErrorListener=e.onError),this._applyExtensionBindings(this._extensionRunner),await this._extensionRunner.emit(this._sessionStartEvent),await this._reconcileDesiredModel(),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions(this._sessionStartEvent.reason==="reload"?"reload":"startup")}async extendResourcesFromExtensions(e){if(!this._extensionRunner.hasHandlers("resources_discover"))return;const{skillPaths:t,promptPaths:s,themePaths:n}=await this._extensionRunner.emitResourcesDiscover(this._cwd,e);if(t.length===0&&s.length===0&&n.length===0)return;const o={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(o),this._rebuildSystemPrompt(this.getActiveToolNames())}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=te(t.extensionPath)?void 0:ce(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return te(e)?`extension:${e.replace(/[<>]/g,"")}`:`extension:${de(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRuntime.getModel(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=c(()=>{const s=e.getRegisteredCommands().map(i=>({name:i.invocationName,description:i.description,source:"extension",sourceInfo:i.sourceInfo})),n=this.promptTemplates.map(i=>({name:i.name,description:i.description,source:"prompt",sourceInfo:i.sourceInfo})),o=this._resourceLoader.getSkills().skills.map(i=>({name:`skill:${i.name}`,description:i.description,source:"skill",sourceInfo:i.sourceInfo}));return[...s,...n,...o]},"getCommands");e.bindCore({sendMessage:c((s,n)=>{this.sendCustomMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:o instanceof Error?o.message:String(o)})})},"sendMessage"),sendUserMessage:c((s,n)=>{this.sendUserMessage(s,n).catch(o=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:o instanceof Error?o.message:String(o)})})},"sendUserMessage"),appendEntry:c((s,n)=>{const o=this.sessionManager.appendCustomEntry(s,n),i=this.sessionManager.getEntry(o);i&&this._emit({type:"entry_appended",entry:i})},"appendEntry"),emitHostEvent:c((s,n)=>{this._emit({type:"extension_event",name:s,data:n??null})},"emitHostEvent"),setSessionName:c(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:c(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:c((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:c(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:c(()=>this.getAllTools(),"getAllTools"),getSettings:c(()=>this.settingsManager.getSettings(),"getSettings"),setActiveTools:c(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:c(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:c(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:c(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:c(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:c(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:c(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:c(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:c(()=>this.model,"getModel"),getScopedModels:c(()=>this._scopedModels,"getScopedModels"),isIdle:c(()=>this.isIdle,"isIdle"),isProjectTrusted:c(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:c(()=>this.agent.signal,"getSignal"),abort:c(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:c(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:c(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:c(()=>this.getContextUsage(),"getContextUsage"),compact:c(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const o=n instanceof Error?n:new Error(String(n));s?.onError?.(o)}})()},"compact"),getSystemPrompt:c(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:c(()=>this._baseSystemPromptOptions,"getSystemPromptOptions"),executeTool:c((s,n,o,i)=>this._executeNestedToolCall(s,n,o,i),"executeTool"),getCallableTools:c(()=>this._getCallableTools(),"getCallableTools")},{registerProvider:c((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:c(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:c(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider"),registerVirtualModel:c(s=>{this._modelRuntime.registerVirtualModel(s),this._refreshCurrentModelFromRegistry()},"registerVirtualModel"),unregisterVirtualModel:c((s,n)=>{this._modelRuntime.unregisterVirtualModel(s,n),this._refreshCurrentModelFromRegistry()},"unregisterVirtualModel")})}_refreshToolRegistry(e){const t=new Set([...this._toolRegistry.keys()].filter(d=>this._isActivatedOnRegistration(d))),s=this.getActiveToolNames(),n=this._allowedTools,i=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:F(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>this._isAllowedTool(d.definition.name)),r=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>this._isAllowedTool(d)).map(([d,g])=>[d,{definition:g,sourceInfo:F(`${ee}${d}`,{source:"builtin"})}]));for(const d of i)r.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=r,this._toolPromptSnippets=new Map(Array.from(r.values()).map(({definition:d})=>{const g=this._normalizePromptSnippet(d.promptSnippet);return g?[d.name,g]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(r.values()).map(({definition:d})=>{const g=this._normalizePromptGuidelines(d.promptGuidelines);return g.length>0?[d.name,g]:void 0}).filter(d=>d!==void 0));const a=this._extensionRunner,l=K(i,a),h=K(Array.from(this._baseToolDefinitions.values()).filter(d=>this._isAllowedTool(d.name)).map(d=>({definition:d,sourceInfo:F(`${ee}${d.name}`,{source:"builtin"})})),a),u=new Map(h.map(d=>[d.name,d]));for(const d of l)u.set(d.name,d);this._toolRegistry=u;const m=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&m.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&m.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&m.push(d);m.push(...this._pendingToolNames),this._setActiveTools([...new Set(m)])}_isDeclarable(e){const t=this._getToolExposure(e);return t==="direct"||t==="model-only"}_isActivatedOnRegistration(e){return this._isDeclarable(e)&&this._toolDefinitions.get(e)?.definition.defaultActive!==!1}getScratchDir(){return this._sandboxScratch??=ot(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();xe(this.settingsManager.getShellEnvironmentPolicy());const o=tt({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=Re(()=>this.getScratchDir());const i=new it({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:c(m=>this._emit(m),"onEvent"),scratchDir:c(()=>this.getScratchDir(),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=i,r?.dispose(),rt(i),process.env[st]=nt(o),this._permissionRules=Ve(this.settingsManager.getPermissionRuleSources()),this._readGuard=Je({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:et(o,this._cwd).denyRead}:{}}),Ze(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([m,d])=>[m,_t(d)])):pt(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i,background:this._backgroundProcesses}});this._baseToolDefinitions=new Map(Object.entries(a).map(([m,d])=>[m,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",ft(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[m,d]of e.flagValues)l.runtime.flagValues.set(m,d);this._extensionRunner=new ze(l.extensions,l.runtime,this._cwd,this.sessionManager,new He(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const h=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],u=e.activeToolNames??h;this._refreshToolRegistry({activeToolNames:u,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await qe(t,{type:"session_shutdown",reason:"reload"}),t.invalidate();const n=c(()=>this._usesDefaultTools?dt(this.settingsManager.getDefaultTools()??ct,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),_e(),await this._resourceLoader.reload();const i=n().filter(a=>!o.has(a));for(const a of this.getActiveToolNames())this._pendingToolNames.add(a);this._buildRuntime({activeToolNames:[...this.getActiveToolNames(),...i],flagValues:s,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await e?.beforeSessionStart?.(),await this._extensionRunner.emit({type:"session_start",reason:"reload"}),this._extensionRunner.reportUnhandledMcpServers(),await this.extendResourcesFromExtensions("reload"))}_isRetryableError(e){return B(e,(this._modelForMessage(e)??this.model)?.contextWindow??0)?!1:fe(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:c((t,s,n,o)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:o})},"onRetryScheduled"),onRetryAttemptStart:c(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:c(()=>{this._emit({type:"summarization_retry_finished"})},"onRetryFinished")}}_finishCancelledRetry(){if(this._retryAttempt===0)return;const e=this._retryAttempt;this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:e,finalError:"Retry cancelled"})}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=ue(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await Ae(s,this._retryAbortController.signal)}catch{return this._finishCancelledRetry(),!1}finally{this._retryAbortController=void 0}return!0}abortRetry(){this._retryAbortController?.abort()}get isRetrying(){return this._retryAbortController!==void 0}get autoRetryEnabled(){return this.settingsManager.getRetryEnabled()}setAutoRetryEnabled(e){this.settingsManager.setRetryEnabled(e)}async executeBash(e,t,s){const n=new AbortController;this._bashAbortControllers.add(n);const o=this.settingsManager.getShellCommandPrefix(),i=this.settingsManager.getShellPath(),r=o?`${o}
15
+ ${e}`:e;try{const a=await Se(r,this.sessionManager.getCwd(),s?.operations??gt({shellPath:i}),{onChunk:c(l=>{t?.(l),this._emit({type:"bash_execution_update",id:s?.id,delta:l})},"onChunk"),signal:n.signal});return this.recordBashResult(e,a,s),a}finally{this._bashAbortControllers.delete(n)}}recordBashResult(e,t,s){const n={role:"bashExecution",command:e,output:t.output,exitCode:t.exitCode,cancelled:t.cancelled,truncated:t.truncated,fullOutputPath:t.fullOutputPath,timestamp:Date.now(),excludeFromContext:s?.excludeFromContext};this.isStreaming?this._pendingBashMessages.push(n):(this.sessionManager.appendMessage(n),this._refreshFinalizedContext())}abortBash(){for(const e of[...this._bashAbortControllers])e.abort()}get isBashRunning(){return this._bashAbortControllers.size>0}get hasPendingBashMessages(){return this._pendingBashMessages.length>0}_flushPendingBashMessages(){if(this._pendingBashMessages.length!==0){for(const e of this._pendingBashMessages)this.sessionManager.appendMessage(e);this._pendingBashMessages=[],this._refreshFinalizedContext()}}setSessionName(e){this.sessionManager.appendSessionInfo(e);const t={type:"session_info_changed",name:this.sessionManager.getSessionName()};this._emit(t),this._extensionRunner.emit(t)}async navigateTree(e,t={}){if(this.isStreaming)throw new Error("Wait for the current response to finish before navigating the session tree.");if(this.isCompacting)throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");const s=this.sessionManager.getLeafId();if(e===s)return{cancelled:!1};if(t.summarize&&!this.model)throw new Error("No model available for summarization");const n=this.sessionManager.getEntry(e);if(!n)throw new Error(`Entry ${e} not found`);const{entries:o,commonAncestorId:i}=Pe(this.sessionManager,s,e);let r=t.customInstructions,a=t.replaceInstructions,l=t.label;const h={targetId:e,oldLeafId:s,commonAncestorId:i,entriesToSummarize:o,userWantsSummary:t.summarize??!1,customInstructions:r,replaceInstructions:a,label:l};this._branchSummaryAbortController=new AbortController;try{let u,m=!1;if(this._extensionRunner.hasHandlers("session_before_tree")){const x=await this._extensionRunner.emit({type:"session_before_tree",preparation:h,signal:this._branchSummaryAbortController.signal});if(x?.cancel)return{cancelled:!0};x?.summary&&t.summarize&&(u=x.summary,m=!0),x?.customInstructions!==void 0&&(r=x.customInstructions),x?.replaceInstructions!==void 0&&(a=x.replaceInstructions),x?.label!==void 0&&(l=x.label)}let d,g,_;if(t.summarize&&o.length>0&&!u){const x=this._branchSummaryAbortController.signal,R=this.settingsManager.getBranchSummarySettings(),y=await Ne(o,{...await this._getSummarizationRequestAuth(this.model,x),signal:x,customInstructions:r,replaceInstructions:a,reserveTokens:R.reserveTokens,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),callbacks:this._summarizationRetryCallbacks({source:"branchSummary"})});if(y.aborted)return{cancelled:!0,aborted:!0};if(y.error)throw new Error(y.error);d=y.summary,_=y.usage,g={readFiles:y.readFiles||[],modifiedFiles:y.modifiedFiles||[]}}else u&&(d=u.summary,g=u.details,_=u.usage);let f,w;n.type==="message"&&n.message.role==="user"?(f=n.parentId,w=P(n.message.content,"")):n.type==="custom_message"?(f=n.parentId,w=P(n.content,"")):f=e;let p;if(d){const x=this.sessionManager.branchWithSummary(f,d,g,m,_);p=this.sessionManager.getEntry(x),l&&this.sessionManager.appendLabelChange(x,l)}else f===null?this.sessionManager.resetLeaf():this.sessionManager.branch(f);return l&&!d&&this.sessionManager.appendLabelChange(e,l),this._refreshFinalizedContext(),this._restoreToolsFromTranscript(),await this._extensionRunner.emit({type:"session_tree",newLeafId:this.sessionManager.getLeafId(),oldLeafId:s,summaryEntry:p,fromExtension:d?m:void 0}),{editorText:w,cancelled:!1,summaryEntry:p}}finally{this._branchSummaryAbortController=void 0,this._resolveIdleWaitIfIdle()}}getUserMessagesForForking(){const e=this.sessionManager.getEntries(),t=[];for(const s of e){if(s.type!=="message"||s.message.role!=="user")continue;const n=P(s.message.content,"");n&&t.push({entryId:s.id,text:n})}return t}getSessionStats(){let e=0,t=0,s=0,n=0,o=0;const i=xt();for(const r of this.sessionManager.getEntries()){if(r.type==="usage"?L(i,r.usage):(r.type==="branch_summary"||r.type==="compaction")&&r.usage&&L(i,r.usage),r.type!=="message")continue;n++;const a=r.message;if(a.role==="user")e++;else if(a.role==="toolResult")s++,a.usage&&L(i,a.usage);else if(a.role==="assistant"){t++;const l=a;Array.isArray(l.content)&&(o+=l.content.filter(h=>h.type==="toolCall").length),L(i,l.usage)}}return{sessionFile:this.sessionFile,sessionId:this.sessionId,userMessages:e,assistantMessages:t,toolCalls:o,toolResults:s,totalMessages:n,tokens:{input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,total:i.input+i.output+i.cacheRead+i.cacheWrite},cost:i.cost,contextUsage:this.getContextUsage()}}getContextUsage(){const e=this._limitsModel();if(!e)return;const t=e.contextWindow??0;if(t<=0)return;const s=this.sessionManager.buildSessionProjection(),n=this.sessionManager.getBranch(),o=Z(n);if(o){const a=new Set(s.entries.flatMap(u=>u.messages.some(m=>m.role==="assistant"&&m.stopReason!=="aborted"&&m.stopReason!=="error"&&$(m.usage)>0)?[u.sourceEntry.id]:[])),l=n.findIndex(u=>u.id===o.id);if(!n.slice(l+1).some(u=>a.has(u.id)))return{tokens:null,contextWindow:t,percent:null}}const i=S(s,n),r=i.tokens/t*100;return{tokens:i.tokens,contextWindow:t,percent:r}}async exportToHtml(e,t={}){const s=[t.themeName,this.settingsManager.getTheme()].find(o=>o!==void 0&&Me(o)!==void 0),n=je({getToolRenderers:c(o=>this._extensionRunner.resolveToolRenderers(o,()=>this.getToolDefinition(o)),"getToolRenderers"),theme:we,cwd:this.sessionManager.getCwd()});return await We(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return at(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");return Ee({...await this._getSummarizationRequestAuth(t,e.signal),messages:this.messages,hint:e.hint,signal:e.signal,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),sessionId:this.sessionId})}getLastAssistantText(){const e=this.messages.slice().reverse().find(s=>{if(s.role!=="assistant")return!1;const n=s;return!(n.stopReason==="aborted"&&n.content.length===0)});if(!e)return;let t="";for(const s of e.content)s.type==="text"&&(t+=s.text);return t.trim()||void 0}createReplacedSessionContext(){const e=Object.defineProperties({},Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));return e.sendMessage=(t,s)=>this.sendCustomMessage(t,s),e.sendUserMessage=(t,s)=>this.sendUserMessage(t,s),e}hasExtensionHandlers(e){return this._extensionRunner.hasHandlers(e)}get extensionRunner(){return this._extensionRunner}}export{_s as AgentSession,fs as parseSkillBlock};
@@ -1,6 +1,7 @@
1
+ import { type ChildProcess } from "node:child_process";
1
2
  import type { ExtensionContext } from "./extensions/types.ts";
2
3
  import type { SandboxDenial } from "./sandbox/denial.ts";
3
- import type { SandboxEscalationInput, ShellSandbox } from "./sandbox/shell-sandbox.ts";
4
+ import type { PreparedCommand, SandboxEscalationInput, ShellSandbox } from "./sandbox/shell-sandbox.ts";
4
5
  export declare const MAX_BACKGROUND_PROCESSES = 8;
5
6
  export type BackgroundProcessState = "running" | "exited" | "stopped" | "failed";
6
7
  export interface BackgroundProcessInfo {
@@ -55,6 +56,16 @@ export declare class BackgroundProcessManager {
55
56
  escalation?: SandboxEscalationInput;
56
57
  ctx?: ExtensionContext;
57
58
  }): Promise<BackgroundProcessInfo>;
59
+ adopt(request: {
60
+ child: ChildProcess;
61
+ command: string;
62
+ cwd: string;
63
+ prepared?: PreparedCommand;
64
+ earlier?: Buffer;
65
+ earlierFile?: string;
66
+ }): BackgroundProcessInfo;
67
+ private track;
68
+ private noteListening;
58
69
  private append;
59
70
  private onExit;
60
71
  private entry;
@@ -66,6 +77,8 @@ export declare class BackgroundProcessManager {
66
77
  info: BackgroundProcessInfo;
67
78
  };
68
79
  status(id: string): BackgroundProcessInfo;
80
+ waitForExit(id: string, ms: number, signal?: AbortSignal): Promise<void>;
81
+ write(id: string, text: string): void;
69
82
  list(): BackgroundProcessInfo[];
70
83
  stop(id: string, graceMs?: number): Promise<BackgroundProcessInfo>;
71
84
  stopAll(): Promise<void>;
@@ -1,7 +1,8 @@
1
- var k=Object.defineProperty;var f=(p,t)=>k(p,"name",{value:t,configurable:!0});import{spawn as P,spawnSync as B}from"node:child_process";import{closeSync as E,openSync as T,writeSync as A}from"node:fs";import{tmpdir as v}from"node:os";import{join as F}from"node:path";import{getShellConfig as y,getShellEnv as S,killProcessTree as m,trackDetachedChildPid as N,untrackDetachedChildPid as C}from"../utils/shell.js";const R=8,H=512*1024,I=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|[\w.-]+\.local)(?::(\d{2,5}))?(?:\/[^\s'"`)\]]*)?/gi,$=[/\b(?:listening|running|started|serving|available|ready)\b[^\n]*?\bport\s*:?\s*(\d{2,5})\b/i,/\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]):(\d{2,5})\b/i],O=/\x1b\[[0-9;]*[A-Za-z]/g;function M(p){const t=p.replace(O,""),o=new Set,e=new Set;for(const s of t.matchAll(I))e.add(s[0].replace(/[.,;]+$/,"")),s[1]&&o.add(Number(s[1]));for(const s of t.split(`
2
- `))for(const n of $){const d=n.exec(s);d&&o.add(Number(d[1]))}return{ports:[...o].filter(s=>s>0&&s<65536),urls:[...e]}}f(M,"detectListening");function _(p){if(process.platform==="win32")return[];const t=B("lsof",["-nP","-a","-iTCP","-sTCP:LISTEN","-g",String(p),"-Fn"],{encoding:"utf8",timeout:2e3});if(t.status!==0||!t.stdout)return[];const o=new Set;for(const e of t.stdout.split(`
3
- `)){const s=/^n.*:(\d+)$/.exec(e.trim());s&&o.add(Number(s[1]))}return[...o]}f(_,"listeningPortsOf");let D=0;class K{static{f(this,"BackgroundProcessManager")}entries=new Map;options;exitHandler=f(()=>this.killAllNow(),"exitHandler");exitHookInstalled=!1;constructor(t={}){this.options=t}get maxProcesses(){return this.options.maxProcesses??R}emit(t,o){this.options.onEvent?.({type:"background_process",event:t,process:this.snapshot(o)})}snapshot(t){return{...t.info,ports:[...t.info.ports],urls:[...t.info.urls]}}running(){return[...this.entries.values()].filter(t=>t.info.state==="running")}async start(t){if(this.running().length>=this.maxProcesses)throw new Error(`Too many background processes (limit ${this.maxProcesses}). Stop one with the process tool (action "stop") first.`);const o=y(this.options.shellPath?.()),e=this.options.sandbox?.();let s;e?.active&&(s=await e.prepare({command:t.command,cwd:t.cwd,shell:o.shell,env:S(),toolCallId:t.toolCallId,toolName:"process",escalation:t.escalation,background:!0,ctx:t.ctx}));const n=`bg${++D}`,d=F(v(),`dal-bg-${process.pid}-${n}.log`),c=o.commandTransport==="stdin",l=s?.command??t.command;let w,r;try{w=T(d,"w"),r=P(o.shell,c?o.args:[...o.args,l],{cwd:t.cwd,detached:process.platform!=="win32",env:S(),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0})}catch(a){throw await s?.finish(0,""),a}c&&(r.stdin?.on("error",()=>{}),r.stdin?.end(l)),r.pid&&N(r.pid),this.exitHookInstalled||(process.on("exit",this.exitHandler),this.exitHookInstalled=!0);let g;const i={info:{id:n,...t.name?{name:t.name}:{},command:t.command,cwd:t.cwd,...r.pid?{pid:r.pid}:{},state:"running",startedAt:Date.now(),ports:[],urls:[],sandboxed:s?.sandboxed===!0,portsReachableFromHost:!(s?.sandboxed&&process.platform==="linux"),logFile:d,outputBytes:0},child:r,chunks:[],bufferedBytes:0,droppedBytes:0,readOffset:0,logFd:w,prepared:s,exited:new Promise(a=>{g=a})};this.entries.set(n,i);const b=f(a=>{this.append(i,a);const u=M(a.toString("utf8"));let x=!1;for(const h of u.ports)i.info.ports.includes(h)||(i.info.ports.push(h),x=!0);for(const h of u.urls)i.info.urls.includes(h)||(i.info.urls.push(h),x=!0);x&&this.emit("port",i)},"onData");return r.stdout?.on("data",b),r.stderr?.on("data",b),r.once("error",a=>{this.append(i,Buffer.from(`
1
+ var b=Object.defineProperty;var d=(l,t)=>b(l,"name",{value:t,configurable:!0});import{spawn as k,spawnSync as S}from"node:child_process";import{closeSync as P,openSync as u,writeSync as E}from"node:fs";import{tmpdir as m}from"node:os";import{join as g}from"node:path";import{getShellConfig as F,getShellEnv as w,killProcessTree as p,trackDetachedChildPid as B,untrackDetachedChildPid as y}from"../utils/shell.js";const T=8,$=512*1024,v=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|[\w.-]+\.local)(?::(\d{2,5}))?(?:\/[^\s'"`)\]]*)?/gi,A=[/\b(?:listening|running|started|serving|available|ready)\b[^\n]*?\bport\s*:?\s*(\d{2,5})\b/i,/\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]):(\d{2,5})\b/i],N=/\x1b\[[0-9;]*[A-Za-z]/g;function C(l){const t=l.replace(N,""),n=new Set,o=new Set;for(const e of t.matchAll(v))o.add(e[0].replace(/[.,;]+$/,"")),e[1]&&n.add(Number(e[1]));for(const e of t.split(`
2
+ `))for(const s of A){const i=s.exec(e);i&&n.add(Number(i[1]))}return{ports:[...n].filter(e=>e>0&&e<65536),urls:[...o]}}d(C,"detectListening");function R(l){if(process.platform==="win32")return[];const t=S("lsof",["-nP","-a","-iTCP","-sTCP:LISTEN","-g",String(l),"-Fn"],{encoding:"utf8",timeout:2e3});if(t.status!==0||!t.stdout)return[];const n=new Set;for(const o of t.stdout.split(`
3
+ `)){const e=/^n.*:(\d+)$/.exec(o.trim());e&&n.add(Number(e[1]))}return[...n]}d(R,"listeningPortsOf");let h=0;class D{static{d(this,"BackgroundProcessManager")}entries=new Map;options;exitHandler=d(()=>this.killAllNow(),"exitHandler");exitHookInstalled=!1;constructor(t={}){this.options=t}get maxProcesses(){return this.options.maxProcesses??T}emit(t,n){this.options.onEvent?.({type:"background_process",event:t,process:this.snapshot(n)})}snapshot(t){return{...t.info,ports:[...t.info.ports],urls:[...t.info.urls]}}running(){return[...this.entries.values()].filter(t=>t.info.state==="running")}async start(t){if(this.running().length>=this.maxProcesses)throw new Error(`Too many background processes (limit ${this.maxProcesses}). Stop one with the process tool (action "kill") first.`);const n=F(this.options.shellPath?.()),o=this.options.sandbox?.();let e;o?.active&&(e=await o.prepare({command:t.command,cwd:t.cwd,shell:n.shell,env:w(),toolCallId:t.toolCallId,toolName:"process",escalation:t.escalation,background:!0,ctx:t.ctx}));const s=`bg${++h}`,i=g(m(),`dal-bg-${process.pid}-${s}.log`),r=n.commandTransport==="stdin",a=e?.command??t.command;let c,f;try{c=u(i,"w"),f=k(n.shell,r?n.args:[...n.args,a],{cwd:t.cwd,detached:process.platform!=="win32",env:w(),stdio:["pipe","pipe","pipe"],windowsHide:!0})}catch(x){throw await e?.finish(0,""),x}return f.stdin?.on("error",()=>{}),r&&f.stdin?.end(a),this.track({child:f,command:t.command,cwd:t.cwd,...t.name?{name:t.name}:{},logFile:i,logFd:c,prepared:e,stdin:!r})}adopt(t){if(this.running().length>=this.maxProcesses)throw new Error(`Too many background processes (limit ${this.maxProcesses}).`);const n=`bg${++h}`,o=g(m(),`dal-bg-${process.pid}-${n}.log`),e=u(o,"w"),s=this.track({child:t.child,command:t.command,cwd:t.cwd,logFile:o,logFd:e,prepared:t.prepared,stdin:!1,id:n}),i=this.entry(s.id),r=t.earlier??(t.earlierFile?Buffer.from(`[earlier output: ${t.earlierFile}]
4
+ `):void 0);return r&&r.length>0&&(this.append(i,r),i.readOffset=r.length,this.noteListening(i,r)),this.snapshot(i)}track(t){const{child:n,prepared:o}=t,e=t.id??`bg${++h}`;n.pid&&B(n.pid),this.exitHookInstalled||(process.on("exit",this.exitHandler),this.exitHookInstalled=!0);let s;const i={info:{id:e,...t.name?{name:t.name}:{},command:t.command,cwd:t.cwd,...n.pid?{pid:n.pid}:{},state:"running",startedAt:Date.now(),ports:[],urls:[],sandboxed:o?.sandboxed===!0,portsReachableFromHost:!(o?.sandboxed&&process.platform==="linux"),logFile:t.logFile,outputBytes:0},child:n,stdin:t.stdin,chunks:[],bufferedBytes:0,droppedBytes:0,readOffset:0,logFd:t.logFd,prepared:o,exited:new Promise(a=>{s=a})};this.entries.set(e,i);const r=d(a=>{this.append(i,a),this.noteListening(i,a)},"onData");return n.stdout?.on("data",r),n.stderr?.on("data",r),n.once("error",a=>{this.append(i,Buffer.from(`
4
5
  [failed to start: ${a.message}]
5
- `)),this.onExit(i,null,null,"failed").then(g)}),r.once("close",(a,u)=>{this.onExit(i,a,u,i.info.state==="stopped"?"stopped":"exited").then(g)}),this.emit("started",i),this.snapshot(i)}append(t,o){if(t.info.outputBytes+=o.length,t.logFd!==void 0)try{A(t.logFd,o)}catch{}for(t.chunks.push(o),t.bufferedBytes+=o.length;t.bufferedBytes>H&&t.chunks.length>1;){const e=t.chunks.shift();t.bufferedBytes-=e.length,t.droppedBytes+=e.length}}async onExit(t,o,e,s){if(t.info.endedAt===void 0){if(t.info.endedAt=Date.now(),t.info.state=s,t.info.exitCode=o,t.info.signal=e,t.child?.pid&&C(t.child.pid),t.logFd!==void 0){try{E(t.logFd)}catch{}t.logFd=void 0}if(t.prepared){const n=await t.prepared.finish(s==="stopped"?0:o,Buffer.concat(t.chunks).toString("utf8"));n&&(t.info.denial=n)}this.emit(s==="stopped"?"stopped":"exited",t)}}entry(t){const o=this.entries.get(t);if(!o){const e=[...this.entries.keys()].join(", ")||"none";throw new Error(`No background process "${t}" (known: ${e}).`)}return o}read(t,o={}){const e=this.entry(t),s=Buffer.concat(e.chunks),n=e.droppedBytes;let d,c=!1;if(o.tail!==void 0){const l=s.toString("utf8").split(`
6
- `);l.at(-1)===""&&l.pop(),c=l.length>o.tail||e.droppedBytes>0,d=l.slice(-Math.max(0,o.tail)).join(`
7
- `)}else{const l=Math.max(e.readOffset,n);c=e.readOffset<n,d=s.subarray(l-n).toString("utf8"),e.readOffset=n+s.length}return{text:d,truncated:c,info:this.snapshot(e)}}status(t){const o=this.entry(t);if(o.info.state==="running"&&o.info.pid&&o.info.portsReachableFromHost){let e=!1;for(const s of _(o.info.pid))o.info.ports.includes(s)||(o.info.ports.push(s),e=!0);e&&this.emit("port",o)}return this.snapshot(o)}list(){return[...this.entries.values()].map(t=>this.snapshot(t))}async stop(t,o=3e3){const e=this.entry(t);if(e.info.state!=="running"||!e.child?.pid)return this.snapshot(e);e.info.state="stopped";const s=e.child.pid;if(process.platform==="win32")m(s);else try{process.kill(-s,"SIGTERM")}catch{m(s)}const n=setTimeout(()=>m(s),o);return await e.exited,clearTimeout(n),this.snapshot(e)}async stopAll(){await Promise.all(this.running().map(t=>this.stop(t.info.id,1e3))),process.removeListener("exit",this.exitHandler),this.exitHookInstalled=!1}killAllNow(){for(const t of this.running())t.child?.pid&&m(t.child.pid)}}export{K as BackgroundProcessManager,R as MAX_BACKGROUND_PROCESSES,M as detectListening};
6
+ `)),this.onExit(i,null,null,"failed").then(s)}),n.once("close",(a,c)=>{this.onExit(i,a,c,i.info.state==="stopped"?"stopped":"exited").then(s)}),this.emit("started",i),this.snapshot(i)}noteListening(t,n){const o=C(n.toString("utf8"));let e=!1;for(const s of o.ports)t.info.ports.includes(s)||(t.info.ports.push(s),e=!0);for(const s of o.urls)t.info.urls.includes(s)||(t.info.urls.push(s),e=!0);e&&this.emit("port",t)}append(t,n){if(t.info.outputBytes+=n.length,t.logFd!==void 0)try{E(t.logFd,n)}catch{}for(t.chunks.push(n),t.bufferedBytes+=n.length;t.bufferedBytes>$&&t.chunks.length>1;){const o=t.chunks.shift();t.bufferedBytes-=o.length,t.droppedBytes+=o.length}}async onExit(t,n,o,e){if(t.info.endedAt===void 0){if(t.info.endedAt=Date.now(),t.info.state=e,t.info.exitCode=n,t.info.signal=o,t.child?.pid&&y(t.child.pid),t.logFd!==void 0){try{P(t.logFd)}catch{}t.logFd=void 0}if(t.prepared){const s=await t.prepared.finish(e==="stopped"?0:n,Buffer.concat(t.chunks).toString("utf8"));s&&(t.info.denial=s)}this.emit(e==="stopped"?"stopped":"exited",t)}}entry(t){const n=this.entries.get(t);if(!n){const o=[...this.entries.keys()].join(", ")||"none";throw new Error(`No background process "${t}" (known: ${o}).`)}return n}read(t,n={}){const o=this.entry(t),e=Buffer.concat(o.chunks),s=o.droppedBytes;let i,r=!1;if(n.tail!==void 0){const a=e.toString("utf8").split(`
7
+ `);a.at(-1)===""&&a.pop(),r=a.length>n.tail||o.droppedBytes>0,i=a.slice(-Math.max(0,n.tail)).join(`
8
+ `)}else{const a=Math.max(o.readOffset,s);r=o.readOffset<s,i=e.subarray(a-s).toString("utf8"),o.readOffset=s+e.length}return{text:i,truncated:r,info:this.snapshot(o)}}status(t){const n=this.entry(t);if(n.info.state==="running"&&n.info.pid&&n.info.portsReachableFromHost){let o=!1;for(const e of R(n.info.pid))n.info.ports.includes(e)||(n.info.ports.push(e),o=!0);o&&this.emit("port",n)}return this.snapshot(n)}async waitForExit(t,n,o){const e=this.entry(t);if(e.info.state!=="running"||n<=0)return;let s,i;await Promise.race([e.exited,new Promise(r=>{s=setTimeout(r,n),i=d(()=>r(),"onAbort"),o?.addEventListener("abort",i,{once:!0})})]),s&&clearTimeout(s),i&&o?.removeEventListener("abort",i)}write(t,n){const o=this.entry(t);if(o.info.state!=="running")throw new Error(`Background process "${t}" is not running.`);if(!o.stdin||!o.child?.stdin||o.child.stdin.destroyed)throw new Error(`Background process "${t}" takes no input: only commands started with the process tool (action "start") have stdin.`);o.child.stdin.write(n)}list(){return[...this.entries.values()].map(t=>this.snapshot(t))}async stop(t,n=3e3){const o=this.entry(t);if(o.info.state!=="running"||!o.child?.pid)return this.snapshot(o);o.info.state="stopped";const e=o.child.pid;if(process.platform==="win32")p(e);else try{process.kill(-e,"SIGTERM")}catch{p(e)}const s=setTimeout(()=>p(e),n);return await o.exited,clearTimeout(s),this.snapshot(o)}async stopAll(){await Promise.all(this.running().map(t=>this.stop(t.info.id,1e3))),process.removeListener("exit",this.exitHandler),this.exitHookInstalled=!1}killAllNow(){for(const t of this.running())t.child?.pid&&p(t.child.pid)}}export{D as BackgroundProcessManager,T as MAX_BACKGROUND_PROCESSES,C as detectListening};
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var o=(i,t)=>d(i,"name",{value:t,configurable:!0});import{readFileSync as s,statSync as u}from"node:fs";import{dirname as c,join as f,resolve as a}from"node:path";function h(i){let t=a(i);for(;;){const n=f(t,".git");try{const r=u(n);if(r.isDirectory()||r.isFile())return{path:n,isFile:r.isFile()}}catch{}const e=c(t);if(e===t)return;t=e}}o(h,"findGitEntry");function l(i){if(!i.isFile)return i.path;try{const t=/^gitdir:\s*(.+)\s*$/m.exec(s(i.path,"utf8"));return t?a(c(i.path),t[1].trim()):void 0}catch{return}}o(l,"resolveGitDir");function G(i){const t=h(i);if(!t)return"Not a git repository: git commands will fail here, so do not run them.";const n=l(t);let e;try{e=n?s(f(n,"HEAD"),"utf8").trim():void 0}catch{e=void 0}if(!e)return"Git repository.";const r=/^ref:\s*refs\/heads\/(.+)$/.exec(e);return r?`Git repository, on branch ${r[1]}.`:/^[0-9a-f]{7,}$/i.test(e)?`Git repository, detached HEAD at ${e.slice(0,7)}.`:"Git repository."}o(G,"describeGitState");export{G as describeGitState};
@@ -123,6 +123,12 @@ declare const ModelDefinitionSchema: Type.TObject<{
123
123
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
124
124
  supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
125
125
  vllmPriority: Type.TOptional<Type.TNumber>;
126
+ responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
127
+ input: Type.TNumber;
128
+ output: Type.TNumber;
129
+ cacheRead: Type.TNumber;
130
+ cacheWrite: Type.TNumber;
131
+ }>>>;
126
132
  }>, Type.TObject<{
127
133
  supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
128
134
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
@@ -280,6 +286,12 @@ declare const ModelOverrideSchema: Type.TObject<{
280
286
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
281
287
  supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
282
288
  vllmPriority: Type.TOptional<Type.TNumber>;
289
+ responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
290
+ input: Type.TNumber;
291
+ output: Type.TNumber;
292
+ cacheRead: Type.TNumber;
293
+ cacheWrite: Type.TNumber;
294
+ }>>>;
283
295
  }>, Type.TObject<{
284
296
  supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
285
297
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
@@ -388,6 +400,12 @@ declare const ProviderConfigSchema: Type.TObject<{
388
400
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
389
401
  supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
390
402
  vllmPriority: Type.TOptional<Type.TNumber>;
403
+ responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
404
+ input: Type.TNumber;
405
+ output: Type.TNumber;
406
+ cacheRead: Type.TNumber;
407
+ cacheWrite: Type.TNumber;
408
+ }>>>;
391
409
  }>, Type.TObject<{
392
410
  supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
393
411
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
@@ -548,6 +566,12 @@ declare const ProviderConfigSchema: Type.TObject<{
548
566
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
549
567
  supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
550
568
  vllmPriority: Type.TOptional<Type.TNumber>;
569
+ responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
570
+ input: Type.TNumber;
571
+ output: Type.TNumber;
572
+ cacheRead: Type.TNumber;
573
+ cacheWrite: Type.TNumber;
574
+ }>>>;
551
575
  }>, Type.TObject<{
552
576
  supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
553
577
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
@@ -705,6 +729,12 @@ declare const ProviderConfigSchema: Type.TObject<{
705
729
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;
706
730
  supportsLongCacheRetention: Type.TOptional<Type.TBoolean>;
707
731
  vllmPriority: Type.TOptional<Type.TNumber>;
732
+ responseModelCosts: Type.TOptional<Type.TRecord<"^.*$", Type.TObject<{
733
+ input: Type.TNumber;
734
+ output: Type.TNumber;
735
+ cacheRead: Type.TNumber;
736
+ cacheWrite: Type.TNumber;
737
+ }>>>;
708
738
  }>, Type.TObject<{
709
739
  supportsDeveloperRole: Type.TOptional<Type.TBoolean>;
710
740
  sessionAffinityFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>;