dal-code 1.0.42 → 1.0.43
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.
- package/CHANGELOG.md +7 -0
- package/dist/core/agent-session.js +9 -9
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/types.d.ts +17 -0
- package/dist/core/sandbox/shell-sandbox.js +7 -5
- package/dist/core/tools/bash.d.ts +1 -0
- package/dist/core/tools/bash.js +13 -13
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/dal/manifest.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/main.js +3 -3
- package/dist/modes/rpc/approvals.js +1 -0
- package/dist/modes/rpc/message-meta.js +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +15 -1
- package/dist/modes/rpc/rpc-client.js +3 -3
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +55 -1
- package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +2 -1
- package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -2
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-remote/package.json +32 -0
- package/dist/node_modules/@dalcode/dal-remote/src/cli.js +10 -0
- package/dist/node_modules/@dalcode/dal-remote/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-remote/src/install.js +8 -0
- package/dist/node_modules/@dalcode/dal-remote/src/paths.js +1 -0
- package/dist/node_modules/@dalcode/dal-remote/src/service.js +8 -0
- package/dist/node_modules/@dalcode/dal-remote/src/spec.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/background.js +8 -8
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +19 -19
- package/dist/node_modules/@dalcode/dal-subagent/src/progress.js +1 -0
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,13 @@ DAL Code 的发布说明。这里只写用户看得见的变化。
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [1.0.43] - 2026-10-18
|
|
12
|
+
|
|
13
|
+
- 不再问你一件最终一定会被拦下的事:`git clean -fd`、`rm -rf ~`、`git push --force` 这类会被危险命令拦截挡下的命令,现在直接拒绝并说明原因,不会先弹审批让你确认之后又被拦;正常需要审批的命令照旧只问一次。
|
|
14
|
+
- 新增 `dal remote` 命令,为 DAL Code 手机端做准备:`dal remote enable` 在这台电脑或服务器上安装并启动手机端用的后台服务(Linux 用 systemd 用户服务,服务器上会开启注销后继续运行;macOS 用登录项),开机自动启动、崩溃后自动重启,然后显示配对二维码和链接;`dal remote status` 查看是否开启和运行,`dal remote logs` 查看日志,`dal remote pair` 再次显示配对信息,`dal remote disable` 停止并移除服务(配对信息保留,再开不用重新配对)。默认关闭,不运行 `enable` 就什么都不装、什么都不启动;安装的版本固定,下载内容逐字节核对,不一致就不装。手机端的后台服务正式发布之前,`enable` 会直接说明“还没有发布,暂时无法开启”。
|
|
15
|
+
- 接入 DAL Code 的程序(包括即将推出的手机端)现在能拿到结构化的审批请求(要运行什么、风险高低、可选的允许或拒绝)、历史消息的原始时间,以及每个子助手的进度,便于显示审批按钮、耗时和子助手进度。终端和桌面应用里的使用方式不变。
|
|
16
|
+
- 国内网络下第一次调试 Node.js 程序时,调试器改从国内镜像下载(1.0.42 起已生效),不再经常卡在 GitHub 上下载失败;下载内容仍逐字节核对,与官方原件一致才会使用。
|
|
17
|
+
|
|
11
18
|
## [1.0.42] - 2026-10-18
|
|
12
19
|
|
|
13
20
|
- 助手生成的 PPT 会在文件里一并保存这份演示的大纲和所用风格:在 DAL Code 里对它「换风格」时直接按原内容重新排版,不用再让助手重做一遍。用 PowerPoint、WPS、Keynote 打开不受影响。
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var le=Object.defineProperty;var h=(T,e)=>le(T,"name",{value:e,configurable:!0});import{readFileSync as de,rmSync as ce}from"node:fs";import{basename as he,dirname as ue}from"node:path";import{runToolCall as me}from"@earendil-works/pi-agent-core";import{contentText as P,getCurrentSystemMessage as
|
|
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:oe(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}=A(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===we)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:oe(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&&A(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=h((o,i)=>this._modelRuntime.getModel(o,i),"getModel"),s=Tt(this.sessionManager.getBranch(),t);if(!s||s.provider===e.provider&&s.modelId===e.id)return;const n=t(s.provider,s.modelId);!A(e)&&!(n&&A(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=tt({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,c=await Pe(a,{autoResizeImages:this.settingsManager.getImageAutoResize(),...l?{resizeOptions:l}:{}});if(!(!r&&c===a))return{content:c,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 Xe({getTools:h(()=>this._getCallableTools(),"getTools"),isSequential:h(()=>this.agent.toolExecution==="sequential","isSequential"),runToolCall:h((o,i,r,a)=>{const l=this._findLastAssistantMessage();return l?me(o,{tools:this._getCallableTools(),assistantMessage:l,context:{messages:this.agent.state.messages,tools:this.agent.state.tools},beforeToolCall:h(c=>this._beforeToolCall(c,i),"beforeToolCall"),afterToolCall:h(c=>this._afterToolCall(c,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:h(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=We(s,t.keepRecentTokens);if(o.edits.length===0||n-o.tokensSaved>e*Ue)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||A(s)?{...e,messages:t.messages}:(this._requestCompactionChecked=!0,this._exceedsCompactionThreshold(s,t)?(await this._compactAtRequestBoundary(s.contextWindow),{...e,messages:this.sessionManager.buildSessionProjection().messages}):{...e,messages:t.messages})}async _compactAtRequestBoundary(e){await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(e)),this._flushPendingCustomMessages()}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n=this._failedResponse;this._failedResponse=void 0;const o=h(async()=>{const g=this.sessionManager.buildSessionProjection(),x={...t.context,messages:g.messages,tools:this.agent.state.tools.slice()},f=await e?.({...t,context:x,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{previous:f,context:f?.context??x,projection:g}},"prepare");let{previous:i,context:r,projection:a}=await o();const l=i?.model??this.agent.state.model,c=i?.thinkingLevel??this.agent.state.thinkingLevel,m=this._requestCompactionChecked;if(this._requestCompactionChecked=!1,!A(l))return!m&&l&&this._exceedsCompactionThreshold(l,a)&&(await this._compactAtRequestBoundary(l.contextWindow),{previous:i,context:r}=await o()),{...i,context:r,model:l,thinkingLevel:c};const u=r.messages.findLastIndex(g=>g.role==="assistant"),d=r.messages.slice(u+1).some(g=>g.role==="user"),p=Ct(this.sessionManager.getBranch(),l.provider,l.id),y=await this._modelRuntime.resolveModel(l,D(r.messages),{reason:n?"retry":d?"user":"continuation",thinkingLevel:c,signal:s,failed:n,state:p});if(y.state!==void 0&&y.state!==p){const g={provider:l.provider,modelId:l.id,state:y.state},x=this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(At,g));x&&this._emit({type:"entry_appended",entry:x})}return this._exceedsCompactionThreshold(y.model,a)&&(await this._compactAtRequestBoundary(y.model.contextWindow),{previous:i,context:r}=await o()),{...i,context:r,model:y.model,thinkingLevel:y.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=ne({...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=ut.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(c=>c.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=h(async e=>{if(e.type==="agent_start"&&this._agentRunAbortRequested&&this.agent.abort(),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?wt(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=ze(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&&ce(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),fe(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||!A(this.model))return;const e=Rt(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 gt(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:h(a=>this._getToolExposure(a),"getExposure"),getNamespace:h(a=>this._toolDefinitions.get(a)?.definition.namespace,"getNamespace"),getPromptGuidelines:h(a=>this._toolPromptGuidelines.get(a)??[],"getPromptGuidelines")},r=new Map;for(const{definition:a,sourceInfo:l}of s)try{const c=a.prepareLoadout?.(i);for(const[m,u]of Object.entries(c?.descriptions??{}))r.set(m,u);for(const m of c?.hiddenDeclarations??[])n.add(m)}catch(c){this._extensionRunner.emitError({extensionPath:l.path,event:"prepare_loadout",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.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 c=this._toolPromptSnippets.get(l);c&&(s[l]=c)}const n=this._resourceLoader.getSystemPrompt(),o=this._resourceLoader.getAppendSystemPrompt(),i=o.length>0?o.join(`
|
|
1
|
+
var le=Object.defineProperty;var h=(T,e)=>le(T,"name",{value:e,configurable:!0});import{readFileSync as de,rmSync as ce}from"node:fs";import{basename as he,dirname as ue}from"node:path";import{runToolCall as me}from"@earendil-works/pi-agent-core";import{contentText as P,getCurrentSystemMessage as N,isNetworkAssistantError as ge,retryDelayMs as pe}from"@earendil-works/pi-ai";import{clampThinkingLevel as q,cleanupSessionResources as fe,getSupportedThinkingLevels as _e,isContextOverflow as B,isRecoverableLength as ye,isRetryableAssistantError as xe,modelsAreEqual as k,resetApiProviders as Me,streamSimple as we}from"@earendil-works/pi-ai/compat";import{configureShellEnvironment as be}from"../dal/child-env.js";import{fill as z,noteUserMessageLanguage as Re,t as I}from"../dal/i18n.js";import{getThemeByName as Te,theme as Ce}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as Ae}from"../utils/frontmatter.js";import{processImage as ve}from"../utils/image-process.js";import{setOutputFileDirectory as Se}from"../utils/output-files.js";import{sleep as Ee}from"../utils/sleep.js";import{normalizeToolResultImages as Pe}from"../utils/tool-result-images.js";import{formatNoApiKeyFoundMessage as O,formatNoModelSelectedMessage as $}from"./auth-guidance.js";import{BackgroundProcessManager as ke}from"./background-processes.js";import{executeBashWithOperations as Ie}from"./bash-executor.js";import{generateBugReportSummary as Le}from"./bug-report.js";import{calculateContextTokens as H,collectEntriesForBranchSummary as Ne,compact as Be,compactionThreshold as G,estimateContextTokens as Oe,estimateProjectedContextTokens as S,estimateTokens as De,generateBranchSummary as Fe,PRUNE_TARGET_RATIO as Ue,planToolOutputPruning as We,prepareCompaction as Q,shouldCompact as V}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as je,THINKING_LEVEL_OPTIONS as qe}from"./defaults.js";import{markBlankAssistantAsError as ze}from"./empty-assistant.js";import{exportSessionToHtml as $e}from"./export-html/index.js";import{createToolHtmlRenderer as He}from"./export-html/tool-renderer.js";import{ExtensionRunner as Ge,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 Ve}from"./model-registry.js";import{isPlaceholderModel as Ke,pickHouseModel as Je}from"./model-resolver.js";import{NestedToolCallRunner as Xe}from"./nested-tool-calls.js";import{buildRuleSet as Ye,EMPTY_RULE_SET as Ze}from"./permissions/rules.js";import{buildReadGuard as et,evaluateToolPolicy as tt,permissionAskHandlers as st,setProcessReadGuard as nt}from"./permissions/tool-policy.js";import{expandPromptTemplate as Y}from"./prompt-templates.js";import{filesystemRules as ot,resolveSandboxPolicy as it,SANDBOX_ENV as rt,sandboxEnvironmentValue as at}from"./sandbox/policy.js";import{createScratchDir as lt,ShellSandbox as dt,setProcessShellSandbox as ct}from"./sandbox/shell-sandbox.js";import{exportSessionToJsonl as ht}from"./session-export.js";import{getLatestCompactionEntry as Z,SessionManager as ut}from"./session-manager.js";import{applyToolModifiers as ee,DEFAULT_TOOL_NAMES as mt}from"./settings-manager.js";import{BUILTIN_PATH_PREFIX as te,createSyntheticSourceInfo as F,isSyntheticPath as se}from"./source-info.js";import{buildSystemPrompt as gt,buildSystemPromptSections as pt,diffSystemPromptSections as ft,normalizeBuildSystemPromptOptions as ne}from"./system-prompt.js";import{createLocalBashOperations as _t}from"./tools/bash.js";import{createAllToolDefinitions as yt}from"./tools/index.js";import{createProcessToolDefinition as xt}from"./tools/process.js";import{createToolDefinitionFromAgentTool as Mt}from"./tools/tool-definition-wrapper.js";import{addUsageToTotals as L,combineUsage as wt,createUsageTotals as bt}from"./usage-totals.js";import{findLatestResponse as Rt,getBranchSelection as Tt,getVirtualModelState as Ct,isVirtualModel as A,VIRTUAL_MODEL_STATE_ENTRY as At}from"./virtual-models.js";function xs(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}h(xs,"parseSkillBlock");function oe(T){return T?Object.fromEntries(Object.entries(T).filter(e=>e[1]!==null)):void 0}h(oe,"withoutDeletedHeaders");function ie(T){let e=0;for(const t of T)e+=De(t);return e}h(ie,"estimateMessagesTokens");class Ms{static{h(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_promptAbortGeneration=0;_agentRunAbortRequested=!1;_preparingRun;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_requestCompactionChecked=!1;_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=Ze;_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 ke({sandbox:h(()=>this._shellSandbox,"sandbox"),shellPath:h(()=>this.settingsManager.getShellPath(),"shellPath"),onEvent:h(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._usesDefaultTools&&this._restoreToolsFromTranscript(this._defaultToolModifiers)}get modelRuntime(){return this._modelRuntime}async _askPermission(e){const t=this._extensionRunner.createContext();for(const a of st()){const r=await a(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"),o=z(I("\u89C4\u5219 {rule} \u8981\u6C42\u5148\u786E\u8BA4\u518D\u8FD0\u884C\u3002"),{rule:e.rule});return await t.ui.select([o,z(I("\u5DE5\u5177\uFF1A{tool}"),{tool:e.toolName}),s].join(`
|
|
2
|
+
`),[n,I("\u62D2\u7EDD")],{approval:{source:"rule",toolCallId:e.toolCallId,toolName:e.toolName,args:e.input,risk:{level:"medium",reason:o,ruleId:`rule:${e.rule}`},title:o,description:s,options:["allow_once","deny"]}})===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:oe(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}=A(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===we)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:oe(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&&A(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=h((o,i)=>this._modelRuntime.getModel(o,i),"getModel"),s=Tt(this.sessionManager.getBranch(),t);if(!s||s.provider===e.provider&&s.modelId===e.id)return;const n=t(s.provider,s.modelId);!A(e)&&!(n&&A(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=tt({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 a;if(i.hasHandlers("tool_call"))try{a=await i.emitToolCall({type:"tool_call",toolName:e.name,toolCallId:e.id,...s?{parentToolCallId:s}:{},input:n})}catch(r){throw r instanceof Error?r:new Error(`Extension failed, blocking execution: ${String(r)}`)}if(a?.block)return a;if(o?.behavior==="ask"){const r=await this._askPermission({toolCallId:e.id,toolName:e.name,input:n,cwd:this._cwd,rule:o.rule,source:o.source});if(!r.approved)return{block:!0,reason:`Not approved (permission rule ${o.rule} asks first)${r.message?`: ${r.message}`:"."}`}}return a}async _afterToolCall({toolCall:e,args:t,result:s,isError:n},o){const i=this._extensionRunner,a=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,r=a?.content??s.content??[],l=this._limitsModel()?.inputLimits?.images?.resize,c=await Pe(r,{autoResizeImages:this.settingsManager.getImageAutoResize(),...l?{resizeOptions:l}:{}});if(!(!a&&c===r))return{content:c,details:a?.details,structuredContent:a?a.structuredContent:s.structuredContent,isError:a?.isError??n,usage:a?.usage}}async _executeNestedToolCall(e,t,s,n){return this._nestedToolCalls??=new Xe({getTools:h(()=>this._getCallableTools(),"getTools"),isSequential:h(()=>this.agent.toolExecution==="sequential","isSequential"),runToolCall:h((o,i,a,r)=>{const l=this._findLastAssistantMessage();return l?me(o,{tools:this._getCallableTools(),assistantMessage:l,context:{messages:this.agent.state.messages,tools:this.agent.state.tools},beforeToolCall:h(c=>this._beforeToolCall(c,i),"beforeToolCall"),afterToolCall:h(c=>this._afterToolCall(c,i),"afterToolCall"),signal:a,onUpdate:r}):Promise.resolve({toolCall:o,result:{content:[{type:"text",text:"No assistant message issued this call"}],details:{}},isError:!0})},"runToolCall"),emit:h(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=We(s,t.keepRecentTokens);if(o.edits.length===0||n-o.tokensSaved>e*Ue)return!1;for(const i of o.edits){const a=this.sessionManager.getEntry(this.sessionManager.appendContextEdit(i.targetId,{content:i.content}));a&&this._emit({type:"entry_appended",entry:a})}return this._refreshFinalizedContext(),!0}async _compactBeforeNextAssistantResponse(e){const t=this.sessionManager.buildSessionProjection(),s=this.model;return!s||A(s)?{...e,messages:t.messages}:(this._requestCompactionChecked=!0,this._exceedsCompactionThreshold(s,t)?(await this._compactAtRequestBoundary(s.contextWindow),{...e,messages:this.sessionManager.buildSessionProjection().messages}):{...e,messages:t.messages})}async _compactAtRequestBoundary(e){await this._runAutoCompaction("threshold",!1,this._compactionThresholdFor(e)),this._flushPendingCustomMessages()}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n=this._failedResponse;this._failedResponse=void 0;const o=h(async()=>{const g=this.sessionManager.buildSessionProjection(),x={...t.context,messages:g.messages,tools:this.agent.state.tools.slice()},f=await e?.({...t,context:x,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{previous:f,context:f?.context??x,projection:g}},"prepare");let{previous:i,context:a,projection:r}=await o();const l=i?.model??this.agent.state.model,c=i?.thinkingLevel??this.agent.state.thinkingLevel,m=this._requestCompactionChecked;if(this._requestCompactionChecked=!1,!A(l))return!m&&l&&this._exceedsCompactionThreshold(l,r)&&(await this._compactAtRequestBoundary(l.contextWindow),{previous:i,context:a}=await o()),{...i,context:a,model:l,thinkingLevel:c};const u=a.messages.findLastIndex(g=>g.role==="assistant"),d=a.messages.slice(u+1).some(g=>g.role==="user"),p=Ct(this.sessionManager.getBranch(),l.provider,l.id),y=await this._modelRuntime.resolveModel(l,D(a.messages),{reason:n?"retry":d?"user":"continuation",thinkingLevel:c,signal:s,failed:n,state:p});if(y.state!==void 0&&y.state!==p){const g={provider:l.provider,modelId:l.id,state:y.state},x=this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(At,g));x&&this._emit({type:"entry_appended",entry:x})}return this._exceedsCompactionThreshold(y.model,r)&&(await this._compactAtRequestBoundary(y.model.contextWindow),{previous:i,context:a}=await o()),{...i,context:a,model:y.model,thinkingLevel:y.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 a=this._findPersistedMessageEntryId(i);return a?[a]:[]}),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,a=this._runSystemPromptOptions??this._baseSystemPromptOptions,r=ne({...a,selectedTools:this.getActiveToolNames(),toolSnippets:{...this._baseSystemPromptOptions.toolSnippets,...a.toolSnippets},toolGuidelines:{...this._baseSystemPromptOptions.toolGuidelines,...a.toolGuidelines}}),l=this._preparePromptAndToolLoadout(r,i.messages);return this._runSystemPromptOptions=r,{...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 a=S(e.buildSessionProjection(),e.getBranch()).tokens;o=e.appendCompaction(n.summary,n.firstKeptEntryId,a,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=ut.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,r=o.some(c=>c.role!=="system")&&i!=="assistant",l=this._pendingCustomMessages.length>0;return{contextEntries:s.entries,contextMessages:s.messages,llmMessages:o,pendingMessages:n,canContinue:r||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=h(async e=>{if(e.type==="agent_start"&&this._agentRunAbortRequested&&this.agent.abort(),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?wt(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=ze(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 a=0;a<i.messages.length;a++){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,a)=>n[a]===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 a=this.sessionManager.appendContextEdit(i,null),r=this.sessionManager.getEntry(a);r&&this._emit({type:"entry_appended",entry:r})}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&&ce(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),fe(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||!A(this.model))return;const e=Rt(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 gt(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 a=this._toolRegistry.get(i);return a&&this._getToolExposure(i)!=="hidden"&&this._isActivatable(i)?[a]:[]}),s=t.flatMap(i=>{const a=this._toolDefinitions.get(i.name);return a?.definition.prepareLoadout?[a]:[]}),n=new Set;let o=t;if(s.length>0){const i={declared:t,callable:this._getCallableTools(new Set(t.map(r=>r.name))),registered:[...this._toolRegistry.values()],getExposure:h(r=>this._getToolExposure(r),"getExposure"),getNamespace:h(r=>this._toolDefinitions.get(r)?.definition.namespace,"getNamespace"),getPromptGuidelines:h(r=>this._toolPromptGuidelines.get(r)??[],"getPromptGuidelines")},a=new Map;for(const{definition:r,sourceInfo:l}of s)try{const c=r.prepareLoadout?.(i);for(const[m,u]of Object.entries(c?.descriptions??{}))a.set(m,u);for(const m of c?.hiddenDeclarations??[])n.add(m)}catch(c){this._extensionRunner.emitError({extensionPath:l.path,event:"prepare_loadout",error:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0})}o=t.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,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 c=this._toolPromptSnippets.get(l);c&&(s[l]=c)}const n=this._resourceLoader.getSystemPrompt(),o=this._resourceLoader.getAppendSystemPrompt(),i=o.length>0?o.join(`
|
|
3
3
|
|
|
4
|
-
`):"",
|
|
4
|
+
`):"",a=this._resourceLoader.getSkills().skills,r=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=ne({cwd:this._cwd,gitState:!0,projectFacts:!0,skills:a,contextFiles:r,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=ft(N(t)?.sections??{},pt(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:a,toolsRemoved:r,...l}=i,c=a?.filter(u=>!o.has(u.name))??[],m=r?.filter(u=>!o.has(u.name))??[];return{...l,...c.length>0?{toolsAdded:c}:{},...m.length>0?{toolsRemoved:m}:{}}})}}_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(r=>r.role!=="system")]}}_restoreToolsFromTranscript(e=[]){this._pendingToolNames.clear();const t=N(this.sessionManager.buildSessionContext().messages);if(!t)return;const s=ee((t.toolsAdded??[]).map(n=>n.name),e);this._pendingToolNames=new Set(s.filter(n=>this._isAllowedTool(n))),this._setActiveTools(s)}async _startRun(e,t={}){const s={cancellable:t.cancelled!==void 0};this._preparingRun=s,this._isAgentRunActive=!0,this._agentRunAbortRequested=!1;const n=h(()=>{this._preparingRun===s&&this._releasePreparingRun()},"endWithoutRun");let o;try{const i=t.cancelled??(()=>!1);o=await this._prepareRun(e,()=>i()||this._preparingRun!==s)}catch(i){throw n(),i}if(!o){n();return}this._preparingRun=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),t.onStarted?.(),this._failedResponse=void 0,this._recordSelection(),this._pendingToolNames.clear();try{for(await this.agent.prompt(o);!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()}}_releasePreparingRun(){this._preparingRun=void 0,this._isAgentRunActive=!1,this._agentRunAbortRequested=!1,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),this._resolveIdleWaitIfIdle()}async _prepareRun(e,t){const s=this._findLastAssistantMessage();if(s&&(await this._checkCompaction(s,!1),t()))return;const n=this._baseSystemPromptOptions.selectedTools,o=await this._extensionRunner.emitBeforeAgentStart(e,this._baseSystemPromptOptions);if(t())return;o.systemPromptOptions.selectedTools.length!==n.length||o.systemPromptOptions.selectedTools.some((c,m)=>c!==n[m])||(o.systemPromptOptions.selectedTools=this.getActiveToolNames());let a;if(e.messageType==="custom")a=e.message;else{const c=await this._normalizePromptImages(e.images);if(t())return;a={role:"user",content:[{type:"text",text:c.hints.length>0?`${e.prompt}
|
|
5
5
|
|
|
6
6
|
${c.hints.join(`
|
|
7
|
-
`)}`:e.prompt},...c.images],timestamp:Date.now()}}const
|
|
7
|
+
`)}`:e.prompt},...c.images],timestamp:Date.now()}}const r=[...this._pendingNextTurnMessages];this._pendingNextTurnMessages=[];for(const c of o.messages)r.push({role:"custom",customType:c.customType,content:c.content??[],display:c.display,details:c.details,timestamp:Date.now()});r.push(a);const l=this._preparePromptAndToolLoadout(o.systemPromptOptions);return this._runSystemPromptOptions=o.systemPromptOptions,l&&r.unshift(l),r}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 ve(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=h(()=>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 a=await this._runInputHandlers(e,t?.images,t?.source??"interactive",this.isStreaming?t?.streamingBehavior:void 0);if(i())return;if(!a){o?.("handled");return}const{text:r,images:l}=a;(t?.source??"interactive")!=="extension"&&Re(r);let c=r;if(n&&(c=this._expandSkillCommand(c),c=Y(c,[...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(c,l):await this._queueSteer(c,l),o?.("queued");return}if(!this.model)throw new Error($());const m=this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0;if(!i()){if(!m)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));await this._startRun({messageType:"user",prompt:c,images:l},{onStarted:h(()=>o?.("started"),"onStarted"),cancelled:i})}}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 a=this._extensionRunner.createCommandContext();t?.(),this._emit({type:"extension_command_start",command:n});try{return await i.handler(o,a),this._emit({type:"extension_command_end",command:n}),!0}catch(r){const l=r instanceof Error?r.message:String(r);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=de(o.filePath,"utf-8"),a=Ae(i).trim(),r=`<skill name="${o.name}" location="${o.filePath}">
|
|
8
8
|
References are relative to ${o.baseDir}.
|
|
9
9
|
|
|
10
|
-
${
|
|
11
|
-
</skill>`;return n?`${
|
|
10
|
+
${a}
|
|
11
|
+
</skill>`;return n?`${r}
|
|
12
12
|
|
|
13
|
-
${n}`:
|
|
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._preparingRun?.cancellable?this._releasePreparingRun():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(!Ke(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Je([...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(m=>`${m.provider}\0${m.id}`)),n=this._scopedModels.filter(m=>s.has(`${m.model.provider}\0${m.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(m=>k(m.model,o));i===-1&&(i=0);const r=n.length,a=e==="forward"?(i+1)%r:(i-1+r)%r,l=n[a],c=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(c),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(c=>k(c,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?_e(this.model):[...je]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return j(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??qe}_clampThinkingLevel(e,t){return this.model?j(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 Ne(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 f=await this._extensionRunner.emit({type:"session_before_compact",preparation:r,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(f?.cancel)throw s=!0,new Error("Compaction cancelled");f?.compaction&&(a=f.compaction,t=!0)}let l,c,m,u,d;if(a)l=a.summary,c=a.firstKeptEntryId,m=a.tokensBefore,u=a.usage,d=a.details;else{const f=await this._runDefaultCompaction(r,n,e,this._compactionAbortController.signal,"manual");l=f.summary,c=f.firstKeptEntryId,m=f.tokensBefore,u=f.usage,d=f.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,m,d,t,u);const p=this.sessionManager.getEntries();this._refreshFinalizedContext();const y=ie(this.sessionManager.buildSessionProjection().messages),g=p.find(f=>f.type==="compaction"&&f.summary===l);this._extensionRunner&&g&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:g,fromExtension:t,reason:"manual",willRetry:!1});const x={summary:l,firstKeptEntryId:c,tokensBefore:m,estimatedTokensAfter:y,usage:u,details:d};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:x,aborted:!1,willRetry:!1}),x}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=this.sessionManager.getBranch(),l=Z(a);let c=!1;if(l!==null){const _=this._findPersistedMessageEntryId(e),R=_?a.findIndex(C=>C.id===_):-1;c=R>=0?R<a.indexOf(l):e.timestamp<=new Date(l.timestamp).getTime()}if(c)return!1;const m=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),d=u===void 0||m.entries.some(_=>_.sourceEntry.id===u&&_.messages.some(R=>R.role==="assistant")),p=this.sessionManager.getBranch(),y=u?p.findIndex(_=>_.id===u):-1,g=y>=0?p.slice(y+1):[],x=g.some(_=>_.type==="context_edit"),f=g.filter(_=>_.type==="context_edit"&&_.targetId===u).at(-1),M=u===void 0||!g.some(_=>_.type==="compaction")&&f?.replacement!==null,v=d&&!x,b=e.stopReason==="error"&&N(e),w=i&&(b&&M||v&&N(e,r)),re=i&&d&&ye(e,this.settingsManager.getOutputTokenLimit(o.maxTokens),o.contextWindow);if(w||re){const _=e.stopReason!=="stop";if(!_)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const C=w?"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:C}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:C,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const R=await this._runAutoCompaction("overflow",_);return R&&(this._failedResponse=e),R}let E;const U=m,ae=U.entries.some(_=>_.sourceEntry.type==="context_edit"),W=e.usage?$(e.usage):0;if(ae)E=S(U,p).tokens;else if(e.stopReason==="error"||W===0){const _=this.agent.state.messages,R=Oe(_);if(R.lastUsageIndex!==null){const C=_[R.lastUsageIndex];if(l&&C.role==="assistant"&&C.timestamp<=new Date(l.timestamp).getTime())return!1}E=R.tokens}else E=W;const q=this._compactionBaseTokens();return V(E,r,n,q)?await this._runAutoCompaction("threshold",!1,G(r,n,q)):!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 c=this.sessionManager.getBranch(),m=Q(c,o);if(!m)return!1;i=new AbortController,this._autoCompactionAbortController=i,r=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let u;if(this._extensionRunner.hasHandlers("session_before_compact")){const w=await this._extensionRunner.emit({type:"session_before_compact",preparation:m,branchEntries:c,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(w?.cancel)throw l=!0,new Error("Compaction cancelled");w?.compaction&&(u=w.compaction,a=!0)}i.signal.throwIfAborted();let d,p,y,g,x;if(u)d=u.summary,p=u.firstKeptEntryId,y=u.tokensBefore,g=u.usage,x=u.details;else{const w=await this._runDefaultCompaction(m,n,void 0,i.signal,e);d=w.summary,p=w.firstKeptEntryId,y=w.tokensBefore,g=w.usage,x=w.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,p,y,x,a,g);const f=this.sessionManager.getEntries();this._refreshFinalizedContext();const M=ie(this.sessionManager.buildSessionProjection().messages),v=f.find(w=>w.type==="compaction"&&w.summary===d);this._extensionRunner&&v&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:v,fromExtension:a,reason:e,willRetry:t});const b={summary:d,firstKeptEntryId:p,tokensBefore:y,estimatedTokensAfter:M,usage:g,details:x};return this._emit({type:"compaction_end",reason:e,result:b,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(c){const m=c instanceof Error?c.message:"compaction failed",u=i?.signal.aborted===!0||l;if(r){const d=u?void 0:e==="overflow"?`Context overflow recovery failed: ${m}`:`Auto-compaction failed: ${m}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:u,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:u,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=se(t.extensionPath)?void 0:ue(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return se(e)?`extension:${e.replace(/[<>]/g,"")}`:`extension:${he(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=h(()=>{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:h((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:h((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:h((s,n)=>{const o=this.sessionManager.appendCustomEntry(s,n),i=this.sessionManager.getEntry(o);i&&this._emit({type:"entry_appended",entry:i})},"appendEntry"),appendUsage:h((s,n)=>{const o=this.sessionManager.appendUsage(n.kind,n.provider??"",n.model??"",s,n.note);this._emit({type:"entry_appended",entry:o})},"appendUsage"),emitHostEvent:h((s,n)=>{this._emit({type:"extension_event",name:s,data:n??null})},"emitHostEvent"),setSessionName:h(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:h(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:h((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:h(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:h(()=>this.getAllTools(),"getAllTools"),getSettings:h(()=>this.settingsManager.getSettings(),"getSettings"),setActiveTools:h(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:h(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:h(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:h(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:h(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:h(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:h(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:h(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:h(()=>this.model,"getModel"),getScopedModels:h(()=>this._scopedModels,"getScopedModels"),isIdle:h(()=>this.isIdle,"isIdle"),isProjectTrusted:h(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:h(()=>this.agent.signal,"getSignal"),abort:h(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:h(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:h(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:h(()=>this.getContextUsage(),"getContextUsage"),compact:h(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:h(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:h(()=>this._baseSystemPromptOptions,"getSystemPromptOptions"),executeTool:h((s,n,o,i)=>this._executeNestedToolCall(s,n,o,i),"executeTool"),getCallableTools:h(()=>this._getCallableTools(),"getCallableTools")},{registerProvider:h((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:h(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:h(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider"),registerVirtualModel:h(s=>{this._modelRuntime.registerVirtualModel(s),this._refreshCurrentModelFromRegistry()},"registerVirtualModel"),unregisterVirtualModel:h((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,p])=>[d,{definition:p,sourceInfo:F(`${te}${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 p=this._normalizePromptSnippet(d.promptSnippet);return p?[d.name,p]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(r.values()).map(({definition:d})=>{const p=this._normalizePromptGuidelines(d.promptGuidelines);return p.length>0?[d.name,p]:void 0}).filter(d=>d!==void 0));const a=this._extensionRunner,l=K(i,a),c=K(Array.from(this._baseToolDefinitions.values()).filter(d=>this._isAllowedTool(d.name)).map(d=>({definition:d,sourceInfo:F(`${te}${d.name}`,{source:"builtin"})})),a),m=new Map(c.map(d=>[d.name,d]));for(const d of l)m.set(d.name,d);this._toolRegistry=m;const u=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&u.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&u.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&u.push(d);u.push(...this._pendingToolNames),this._setActiveTools([...new Set(u)])}_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??=lt(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();be(this.settingsManager.getShellEnvironmentPolicy());const o=it({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=Se(()=>this.getScratchDir());const i=new dt({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:h(u=>this._emit(u),"onEvent"),scratchDir:h(()=>this.getScratchDir(),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=i,r?.dispose(),ct(i),process.env[rt]=at(o),this._permissionRules=Ye(this.settingsManager.getPermissionRuleSources()),this._readGuard=et({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:ot(o,this._cwd).denyRead}:{}}),nt(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([u,d])=>[u,Mt(d)])):yt(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i,background:this._backgroundProcesses}});this._baseToolDefinitions=new Map(Object.entries(a).map(([u,d])=>[u,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",xt(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[u,d]of e.flagValues)l.runtime.flagValues.set(u,d);this._extensionRunner=new Ge(l.extensions,l.runtime,this._cwd,this.sessionManager,new Ve(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const c=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],m=e.activeToolNames??c;this._refreshToolRegistry({activeToolNames:m,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=h(()=>this._usesDefaultTools?ee(this.settingsManager.getDefaultTools()??mt,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),Me(),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 N(e,(this._modelForMessage(e)??this.model)?.contextWindow??0)?!1:xe(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:h((t,s,n,o)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:o})},"onRetryScheduled"),onRetryAttemptStart:h(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:h(()=>{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=pe(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error",cause:ge(e)?"network":"provider"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await Ee(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
|
|
13
|
+
${n}`:r}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.sendCustomMessage(e,t));return}await this._startRun({messageType:"custom",message: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._preparingRun?.cancellable?this._releasePreparingRun():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(!Ke(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Je([...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(m=>`${m.provider}\0${m.id}`)),n=this._scopedModels.filter(m=>s.has(`${m.model.provider}\0${m.model.id}`));if(n.length<=1)return;const o=this.model;let i=n.findIndex(m=>k(m.model,o));i===-1&&(i=0);const a=n.length,r=e==="forward"?(i+1)%a:(i-1+a)%a,l=n[r],c=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(c),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(c=>k(c,n));o===-1&&(o=0);const i=s.length,a=e==="forward"?(o+1)%i:(o-1+i)%i,r=s[a],l=this._getThinkingLevelForModelSwitch(r);return this.agent.state.model=r,this.sessionManager.appendModelChange(r.provider,r.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(r.provider,r.id),this._addPersistedDefaultToNonEmptyScope(r)),this.setThinkingLevel(l),await this._emitModelSelect(r,n,"cycle"),{model:r,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?_e(this.model):[...qe]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return q(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??je}_clampThinkingLevel(e,t){return this.model?q(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 a=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`);a=l}const r=await this._getSummarizationRequestAuth(a,n);return Be(e,r.model,r.apiKey,r.headers,s,n,r.thinkingLevel,this.agent.streamFunction,r.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($());const o=this.settingsManager.getCompactionSettings(n),i=this.sessionManager.getBranch(),a=Q(i,o);if(!a)throw i[i.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let r;if(this._extensionRunner.hasHandlers("session_before_compact")){const f=await this._extensionRunner.emit({type:"session_before_compact",preparation:a,branchEntries:i,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(f?.cancel)throw s=!0,new Error("Compaction cancelled");f?.compaction&&(r=f.compaction,t=!0)}let l,c,m,u,d;if(r)l=r.summary,c=r.firstKeptEntryId,m=r.tokensBefore,u=r.usage,d=r.details;else{const f=await this._runDefaultCompaction(a,n,e,this._compactionAbortController.signal,"manual");l=f.summary,c=f.firstKeptEntryId,m=f.tokensBefore,u=f.usage,d=f.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(l,c,m,d,t,u);const p=this.sessionManager.getEntries();this._refreshFinalizedContext();const y=ie(this.sessionManager.buildSessionProjection().messages),g=p.find(f=>f.type==="compaction"&&f.summary===l);this._extensionRunner&&g&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:g,fromExtension:t,reason:"manual",willRetry:!1});const x={summary:l,firstKeptEntryId:c,tokensBefore:m,estimatedTokensAfter:y,usage:u,details:d};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:x,aborted:!1,willRetry:!1}),x}catch(n){const o=n instanceof Error?n.message:String(n),i=this._compactionAbortController.signal.aborted||s,a=i?void 0:`Compaction failed: ${o}`;throw this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:i,willRetry:!1,errorMessage:a}),await this._emitSessionCompactFailed({reason:"manual",errorMessage:a,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,a=(o??this.model)?.contextWindow??0,r=this.sessionManager.getBranch(),l=Z(r);let c=!1;if(l!==null){const _=this._findPersistedMessageEntryId(e),R=_?r.findIndex(C=>C.id===_):-1;c=R>=0?R<r.indexOf(l):e.timestamp<=new Date(l.timestamp).getTime()}if(c)return!1;const m=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),d=u===void 0||m.entries.some(_=>_.sourceEntry.id===u&&_.messages.some(R=>R.role==="assistant")),p=this.sessionManager.getBranch(),y=u?p.findIndex(_=>_.id===u):-1,g=y>=0?p.slice(y+1):[],x=g.some(_=>_.type==="context_edit"),f=g.filter(_=>_.type==="context_edit"&&_.targetId===u).at(-1),M=u===void 0||!g.some(_=>_.type==="compaction")&&f?.replacement!==null,v=d&&!x,b=e.stopReason==="error"&&B(e),w=i&&(b&&M||v&&B(e,a)),re=i&&d&&ye(e,this.settingsManager.getOutputTokenLimit(o.maxTokens),o.contextWindow);if(w||re){const _=e.stopReason!=="stop";if(!_)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const C=w?"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:C}),await this._emitSessionCompactFailed({reason:"overflow",errorMessage:C,aborted:!1,willRetry:!1,fromExtension:!1}),!1}this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s);const R=await this._runAutoCompaction("overflow",_);return R&&(this._failedResponse=e),R}let E;const U=m,ae=U.entries.some(_=>_.sourceEntry.type==="context_edit"),W=e.usage?H(e.usage):0;if(ae)E=S(U,p).tokens;else if(e.stopReason==="error"||W===0){const _=this.agent.state.messages,R=Oe(_);if(R.lastUsageIndex!==null){const C=_[R.lastUsageIndex];if(l&&C.role==="assistant"&&C.timestamp<=new Date(l.timestamp).getTime())return!1}E=R.tokens}else E=W;const j=this._compactionBaseTokens();return V(E,a,n,j)?await this._runAutoCompaction("threshold",!1,G(a,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,a=!1,r=!1,l=!1;try{if(!n)return!1;const c=this.sessionManager.getBranch(),m=Q(c,o);if(!m)return!1;i=new AbortController,this._autoCompactionAbortController=i,a=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();let u;if(this._extensionRunner.hasHandlers("session_before_compact")){const w=await this._extensionRunner.emit({type:"session_before_compact",preparation:m,branchEntries:c,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(w?.cancel)throw l=!0,new Error("Compaction cancelled");w?.compaction&&(u=w.compaction,r=!0)}i.signal.throwIfAborted();let d,p,y,g,x;if(u)d=u.summary,p=u.firstKeptEntryId,y=u.tokensBefore,g=u.usage,x=u.details;else{const w=await this._runDefaultCompaction(m,n,void 0,i.signal,e);d=w.summary,p=w.firstKeptEntryId,y=w.tokensBefore,g=w.usage,x=w.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(d,p,y,x,r,g);const f=this.sessionManager.getEntries();this._refreshFinalizedContext();const M=ie(this.sessionManager.buildSessionProjection().messages),v=f.find(w=>w.type==="compaction"&&w.summary===d);this._extensionRunner&&v&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:v,fromExtension:r,reason:e,willRetry:t});const b={summary:d,firstKeptEntryId:p,tokensBefore:y,estimatedTokensAfter:M,usage:g,details:x};return this._emit({type:"compaction_end",reason:e,result:b,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(c){const m=c instanceof Error?c.message:"compaction failed",u=i?.signal.aborted===!0||l;if(a){const d=u?void 0:e==="overflow"?`Context overflow recovery failed: ${m}`:`Auto-compaction failed: ${m}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:u,willRetry:!1,errorMessage:d}),await this._emitSessionCompactFailed({reason:e,errorMessage:d,aborted:u,willRetry:!1,fromExtension:r})}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=se(t.extensionPath)?void 0:ue(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return se(e)?`extension:${e.replace(/[<>]/g,"")}`:`extension:${he(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=h(()=>{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:h((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:h((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:h((s,n)=>{const o=this.sessionManager.appendCustomEntry(s,n),i=this.sessionManager.getEntry(o);i&&this._emit({type:"entry_appended",entry:i})},"appendEntry"),appendUsage:h((s,n)=>{const o=this.sessionManager.appendUsage(n.kind,n.provider??"",n.model??"",s,n.note);this._emit({type:"entry_appended",entry:o})},"appendUsage"),emitHostEvent:h((s,n)=>{this._emit({type:"extension_event",name:s,data:n??null})},"emitHostEvent"),setSessionName:h(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:h(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:h((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:h(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:h(()=>this.getAllTools(),"getAllTools"),getSettings:h(()=>this.settingsManager.getSettings(),"getSettings"),setActiveTools:h(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:h(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:h(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:h(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:h(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:h(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:h(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:h(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:h(()=>this.model,"getModel"),getScopedModels:h(()=>this._scopedModels,"getScopedModels"),isIdle:h(()=>this.isIdle,"isIdle"),isProjectTrusted:h(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:h(()=>this.agent.signal,"getSignal"),abort:h(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:h(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:h(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:h(()=>this.getContextUsage(),"getContextUsage"),compact:h(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:h(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:h(()=>this._baseSystemPromptOptions,"getSystemPromptOptions"),executeTool:h((s,n,o,i)=>this._executeNestedToolCall(s,n,o,i),"executeTool"),getCallableTools:h(()=>this._getCallableTools(),"getCallableTools")},{registerProvider:h((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:h(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:h(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider"),registerVirtualModel:h(s=>{this._modelRuntime.registerVirtualModel(s),this._refreshCurrentModelFromRegistry()},"registerVirtualModel"),unregisterVirtualModel:h((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)),a=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>this._isAllowedTool(d)).map(([d,p])=>[d,{definition:p,sourceInfo:F(`${te}${d}`,{source:"builtin"})}]));for(const d of i)a.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=a,this._toolPromptSnippets=new Map(Array.from(a.values()).map(({definition:d})=>{const p=this._normalizePromptSnippet(d.promptSnippet);return p?[d.name,p]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(a.values()).map(({definition:d})=>{const p=this._normalizePromptGuidelines(d.promptGuidelines);return p.length>0?[d.name,p]:void 0}).filter(d=>d!==void 0));const r=this._extensionRunner,l=K(i,r),c=K(Array.from(this._baseToolDefinitions.values()).filter(d=>this._isAllowedTool(d.name)).map(d=>({definition:d,sourceInfo:F(`${te}${d.name}`,{source:"builtin"})})),r),m=new Map(c.map(d=>[d.name,d]));for(const d of l)m.set(d.name,d);this._toolRegistry=m;const u=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>this._isAllowedTool(d));if(n)for(const d of this._toolRegistry.keys())n(d)&&this._isDeclarable(d)&&u.push(d);else if(e?.includeAllExtensionTools)for(const d of l)this._isActivatedOnRegistration(d.name)&&u.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())!t.has(d)&&this._isActivatedOnRegistration(d)&&u.push(d);u.push(...this._pendingToolNames),this._setActiveTools([...new Set(u)])}_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??=lt(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();be(this.settingsManager.getShellEnvironmentPolicy());const o=it({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=Se(()=>this.getScratchDir());const i=new dt({policy:o,onEscalation:this._sandboxOptions.onEscalation,onEvent:h(u=>this._emit(u),"onEvent"),scratchDir:h(()=>this.getScratchDir(),"scratchDir")}),a=this._shellSandbox;this._shellSandbox=i,a?.dispose(),ct(i),process.env[rt]=at(o),this._permissionRules=Ye(this.settingsManager.getPermissionRuleSources()),this._readGuard=et({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:ot(o,this._cwd).denyRead}:{}}),nt(this._readGuard);const r=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([u,d])=>[u,Mt(d)])):yt(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:i,background:this._backgroundProcesses}});this._baseToolDefinitions=new Map(Object.entries(r).map(([u,d])=>[u,d])),this._baseToolsOverride||this._baseToolDefinitions.set("process",xt(this._cwd,this._backgroundProcesses,{sandboxed:i.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[u,d]of e.flagValues)l.runtime.flagValues.set(u,d);this._extensionRunner=new Ge(l.extensions,l.runtime,this._cwd,this.sessionManager,new Ve(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const c=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],m=e.activeToolNames??c;this._refreshToolRegistry({activeToolNames:m,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=h(()=>this._usesDefaultTools?ee(this.settingsManager.getDefaultTools()??mt,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),Me(),await this._resourceLoader.reload();const i=n().filter(r=>!o.has(r));for(const r of this.getActiveToolNames())this._pendingToolNames.add(r);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:xe(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:h((t,s,n,o)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:o})},"onRetryScheduled"),onRetryAttemptStart:h(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:h(()=>{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=pe(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error",cause:ge(e)?"network":"provider"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await Ee(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(),a=o?`${o}
|
|
15
|
+
${e}`:e;try{const r=await Ie(a,this.sessionManager.getCwd(),s?.operations??_t({shellPath:i}),{onChunk:h(l=>{t?.(l),this._emit({type:"bash_execution_update",id:s?.id,delta:l})},"onChunk"),signal:n.signal});return this.recordBashResult(e,r,s),r}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}=Ne(this.sessionManager,s,e);let a=t.customInstructions,r=t.replaceInstructions,l=t.label;const c={targetId:e,oldLeafId:s,commonAncestorId:i,entriesToSummarize:o,userWantsSummary:t.summarize??!1,customInstructions:a,replaceInstructions:r,label:l};this._branchSummaryAbortController=new AbortController;try{let m,u=!1;if(this._extensionRunner.hasHandlers("session_before_tree")){const M=await this._extensionRunner.emit({type:"session_before_tree",preparation:c,signal:this._branchSummaryAbortController.signal});if(M?.cancel)return{cancelled:!0};M?.summary&&t.summarize&&(m=M.summary,u=!0),M?.customInstructions!==void 0&&(a=M.customInstructions),M?.replaceInstructions!==void 0&&(r=M.replaceInstructions),M?.label!==void 0&&(l=M.label)}let d,p,y;if(t.summarize&&o.length>0&&!m){const M=this._branchSummaryAbortController.signal,v=this.settingsManager.getBranchSummarySettings(),b=await Fe(o,{...await this._getSummarizationRequestAuth(this.model,M),signal:M,customInstructions:a,replaceInstructions:r,reserveTokens:v.reserveTokens,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),callbacks:this._summarizationRetryCallbacks({source:"branchSummary"})});if(b.aborted)return{cancelled:!0,aborted:!0};if(b.error)throw new Error(b.error);d=b.summary,y=b.usage,p={readFiles:b.readFiles||[],modifiedFiles:b.modifiedFiles||[]}}else m&&(d=m.summary,p=m.details,y=m.usage);let g,x;n.type==="message"&&n.message.role==="user"?(g=n.parentId,x=P(n.message.content,"")):n.type==="custom_message"?(g=n.parentId,x=P(n.content,"")):g=e;let f;if(d){const M=this.sessionManager.branchWithSummary(g,d,p,u,y);f=this.sessionManager.getEntry(M),l&&this.sessionManager.appendLabelChange(M,l)}else g===null?this.sessionManager.resetLeaf():this.sessionManager.branch(g);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:f,fromExtension:d?u:void 0}),{editorText:x,cancelled:!1,summaryEntry:f}}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=bt();for(const a of this.sessionManager.getEntries()){if(a.type==="usage"?L(i,a.usage):(a.type==="branch_summary"||a.type==="compaction")&&a.usage&&L(i,a.usage),a.type!=="message")continue;n++;const r=a.message;if(r.role==="user")e++;else if(r.role==="toolResult")s++,r.usage&&L(i,r.usage);else if(r.role==="assistant"){t++;const l=r;Array.isArray(l.content)&&(o+=l.content.filter(c=>c.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 r=new Set(s.entries.flatMap(m=>m.messages.some(u=>u.role==="assistant"&&u.stopReason!=="aborted"&&u.stopReason!=="error"&&H(u.usage)>0)?[m.sourceEntry.id]:[])),l=n.findIndex(m=>m.id===o.id);if(!n.slice(l+1).some(m=>r.has(m.id)))return{tokens:null,contextWindow:t,percent:null}}const i=S(s,n),a=i.tokens/t*100;return{tokens:i.tokens,contextWindow:t,percent:a}}async exportToHtml(e,t={}){const s=[t.themeName,this.settingsManager.getTheme()].find(o=>o!==void 0&&Te(o)!==void 0),n=He({getToolRenderers:h(o=>this._extensionRunner.resolveToolRenderers(o,()=>this.getToolDefinition(o)),"getToolRenderers"),theme:Ce,cwd:this.sessionManager.getCwd()});return await $e(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return ht(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");return Le({...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{Ms as AgentSession,xs as parseSkillBlock};
|
|
@@ -3,6 +3,6 @@ export type { SourceInfo } from "../source-info.ts";
|
|
|
3
3
|
export { createExtensionRuntime, discoverAndLoadExtensions, loadExtensionFromFactory, loadExtensions, } from "./loader.ts";
|
|
4
4
|
export type { ExtensionErrorListener, ForkHandler, NavigateTreeHandler, NewSessionHandler, ShutdownHandler, SwitchSessionHandler, } from "./runner.ts";
|
|
5
5
|
export { ExtensionRunner } from "./runner.ts";
|
|
6
|
-
export type { AfterProviderResponseEvent, AgentActivityOutcome, AgentBeforeSettleEvent, AgentBeforeSettleEventResult, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppendEntryHandler, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BashToolResultEvent, BeforeAgentStartCustomEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeAgentStartUserEvent, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BoundaryContextPreview, BoundaryResult, BoundaryState, BuildSystemPromptOptions, CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult, CompactionEntryDraft, CompactOptions, ContextEditEntryDraft, ContextEvent, ContextEventResult, ContextUsage, ContextWithSystemEvent, CustomEntryDraft, CustomMessageEntryDraft, CustomToolCallEvent, CustomToolResultEvent, EditorFactory, EditToolCallEvent, EditToolResultEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, ExecuteToolOptions, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionMode, ExtensionRuntime, ExtensionShortcut, ExtensionToolContext, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionVirtualModel, ExtensionWidgetOptions, FindToolCallEvent, FindToolResultEvent, GetActiveToolsHandler, GetAllToolsHandler, GetCommandsHandler, GetThinkingLevelHandler, GetToolAllowlistHandler, GetToolDenylistHandler, GrepToolCallEvent, GrepToolResultEvent, InlineExtension, InputEvent, InputEventResult, InputSource, IsToolAllowedHandler, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, LsToolResultEvent, MarkdownTransformContext, MarkdownTransformer, McpServersChangeEvent, MessageEndEvent, MessageEndEventResult, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelPickerEntry, ModelPickerEntryState, ModelSelectEvent, ModelSelectSource, NormalizedBuildSystemPromptOptions, PowerShellToolCallEvent, PowerShellToolResultEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderChatModelConfig, ProviderConfig, ProviderModelConfig, ProviderStreamEvent, ReadToolCallEvent, ReadToolResultEvent, RegisteredCommand, RegisteredModelPickerEntry, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SendMessageHandler, SendUserMessageHandler, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionBoundaryDraft, SessionCompactEvent, SessionCompactFailedEvent, SessionEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SetActiveToolsHandler, SetLabelHandler, SetModelHandler, SetThinkingLevelHandler, TerminalInputHandler, ThinkingLevelSelectEvent, ToolAnnotations, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolExposure, ToolInfo, ToolLoadout, ToolLoadoutChanges, ToolNamespace, ToolRendererResolver, ToolRenderers, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TreePreparation, TurnEndEvent, TurnEndEventResult, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } from "./types.ts";
|
|
6
|
+
export type { AfterProviderResponseEvent, AgentActivityOutcome, AgentBeforeSettleEvent, AgentBeforeSettleEventResult, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppendEntryHandler, AppKeybinding, ApprovalOptionKind, ApprovalPrompt, ApprovalSource, AutocompleteProviderFactory, BashToolCallEvent, BashToolResultEvent, BeforeAgentStartCustomEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeAgentStartUserEvent, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BoundaryContextPreview, BoundaryResult, BoundaryState, BuildSystemPromptOptions, CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult, CompactionEntryDraft, CompactOptions, ContextEditEntryDraft, ContextEvent, ContextEventResult, ContextUsage, ContextWithSystemEvent, CustomEntryDraft, CustomMessageEntryDraft, CustomToolCallEvent, CustomToolResultEvent, EditorFactory, EditToolCallEvent, EditToolResultEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, ExecuteToolOptions, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionMode, ExtensionRuntime, ExtensionShortcut, ExtensionToolContext, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionVirtualModel, ExtensionWidgetOptions, FindToolCallEvent, FindToolResultEvent, GetActiveToolsHandler, GetAllToolsHandler, GetCommandsHandler, GetThinkingLevelHandler, GetToolAllowlistHandler, GetToolDenylistHandler, GrepToolCallEvent, GrepToolResultEvent, InlineExtension, InputEvent, InputEventResult, InputSource, IsToolAllowedHandler, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, LsToolResultEvent, MarkdownTransformContext, MarkdownTransformer, McpServersChangeEvent, MessageEndEvent, MessageEndEventResult, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelPickerEntry, ModelPickerEntryState, ModelSelectEvent, ModelSelectSource, NormalizedBuildSystemPromptOptions, PowerShellToolCallEvent, PowerShellToolResultEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderChatModelConfig, ProviderConfig, ProviderModelConfig, ProviderStreamEvent, ReadToolCallEvent, ReadToolResultEvent, RegisteredCommand, RegisteredModelPickerEntry, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SendMessageHandler, SendUserMessageHandler, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionBoundaryDraft, SessionCompactEvent, SessionCompactFailedEvent, SessionEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SetActiveToolsHandler, SetLabelHandler, SetModelHandler, SetThinkingLevelHandler, TerminalInputHandler, ThinkingLevelSelectEvent, ToolAnnotations, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolExposure, ToolInfo, ToolLoadout, ToolLoadoutChanges, ToolNamespace, ToolRendererResolver, ToolRenderers, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TreePreparation, TurnEndEvent, TurnEndEventResult, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } from "./types.ts";
|
|
7
7
|
export { defineTool, extensionPanelLines, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isPowerShellToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, resolveExtensionNotify, } from "./types.ts";
|
|
8
8
|
export { wrapRegisteredTool, wrapRegisteredTools } from "./wrapper.ts";
|
|
@@ -30,6 +30,23 @@ export type { AppKeybinding, KeybindingsManager } from "../keybindings.ts";
|
|
|
30
30
|
export interface ExtensionUIDialogOptions {
|
|
31
31
|
signal?: AbortSignal;
|
|
32
32
|
timeout?: number;
|
|
33
|
+
approval?: ApprovalPrompt;
|
|
34
|
+
}
|
|
35
|
+
export type ApprovalOptionKind = "deny" | "allow_once" | "allow_session";
|
|
36
|
+
export type ApprovalSource = "guard" | "sandbox" | "rule" | "workspace" | "extension";
|
|
37
|
+
export interface ApprovalPrompt {
|
|
38
|
+
source: ApprovalSource;
|
|
39
|
+
toolCallId?: string;
|
|
40
|
+
toolName?: string;
|
|
41
|
+
args?: Record<string, unknown>;
|
|
42
|
+
risk?: {
|
|
43
|
+
level: "low" | "medium" | "high";
|
|
44
|
+
reason: string;
|
|
45
|
+
ruleId?: string;
|
|
46
|
+
};
|
|
47
|
+
title: string;
|
|
48
|
+
description?: string;
|
|
49
|
+
options: ApprovalOptionKind[];
|
|
33
50
|
}
|
|
34
51
|
export type WidgetPlacement = "aboveEditor" | "belowEditor";
|
|
35
52
|
export interface ExtensionWidgetOptions {
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
var G=Object.defineProperty;var m=(
|
|
2
|
-
`)){const
|
|
3
|
-
`)}planNetworkEscalation(
|
|
4
|
-
${
|
|
5
|
-
`),
|
|
1
|
+
var G=Object.defineProperty;var m=(e,o)=>G(e,"name",{value:o,configurable:!0});import{spawnSync as Q}from"node:child_process";import{mkdirSync as V,mkdtempSync as z,rmSync as J}from"node:fs";import{tmpdir as Z}from"node:os";import{isAbsolute as P,join as q,relative as oo,resolve as eo}from"node:path";import{fill as v,t as h}from"../../dal/i18n.js";import{detectSandboxAvailability as no}from"./availability.js";import{collectBlockedAccesses as O}from"./denial.js";import{detectNetworkCommand as T,FAIL_FAST_NETWORK_ENV as U,networkDomainsFor as io,packageCacheDirs as ao}from"./package-managers.js";import{domainMatches as B,expandPath as L,filesystemRules as to}from"./policy.js";import{acquireSandboxRuntime as so,ensureFilteringProxy as ro,proxyUnavailableReason as M,registerNetworkGrant as lo,releaseSandboxRuntime as co,violationsForCommand as mo,wrapCommand as ho}from"./runtime.js";import{prepareWindowsCommand as fo}from"./windows.js";const C=Symbol.for("dal.sandbox.escalationHandlers"),k=globalThis;k[C]instanceof Set||(k[C]=new Set);const N=k[C];function Io(e){return N.add(e),()=>{N.delete(e)}}m(Io,"registerSandboxEscalationHandler");const F=Symbol.for("dal.sandbox.processSandbox");function Ro(e){k[F]=e}m(Ro,"setProcessShellSandbox");function Ao(){return k[F]}m(Ao,"getProcessShellSandbox");const K=new Map;function po(e){const o=K.get(e);if(o)return o;const n=Q("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:e,encoding:"utf8",timeout:3e3}),r=[];if(n.status===0)for(const s of n.stdout.split(`
|
|
2
|
+
`)){const a=s.trim();if(!a)continue;const i=P(a)?a:eo(e,a),t=oo(e,i);(t.startsWith("..")||P(t))&&r.push(i)}const l=[...new Set(r)];return K.set(e,l),l}m(po,"gitDirsOutside");function S(e){return Array.isArray(e)?e.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[]}m(S,"cleanList");let uo=0;class Po{static{m(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(o){this.policy=o.policy,this.onEscalation=o.onEscalation,this.onEvent=o.onEvent,this.availabilityOverride=o.availability,this.sharedScratch=o.scratchDir,this.active&&(so(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=bo(),this.ownScratch)}async dispose(){this.ownScratch&&(J(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await co())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??no()}status(){const o=this.availability(),n=M();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&o.available,platform:o.platform,...o.mechanism?{mechanism:o.mechanism}:{},...this.active&&!o.available&&o.reason?{unavailableReason:o.reason}:{},...o.isolationTier?{isolationTier:o.isolationTier}:{},...o.limitations?.length?{limitations:[...o.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...n?{proxyError:n}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const o=this.policy.level==="read-only"?"writes only to $TMPDIR (session scratch)":"writes only to the working directory, $TMPDIR (session scratch) and package caches (agent/editor config, git hooks and .env stay read-only)",n=this.policy.network.allowedDomains,r=(n.length>0?`network off except ${n.join(", ")}`:"network off")+(this.policy.level==="workspace-write"?" (package installs via npm/pnpm/yarn/pip/uv/cargo/go and curl/wget/git clone ask the user for their hosts by themselves: run them plainly, without sandbox_escalation)":"");return`OS sandbox (${this.policy.level}): ${o}; ${r}; ~/.ssh and other credentials unreadable. Use sandbox_escalation only after the result says the sandbox blocked something the task needs.`}unavailableRefusal(){if(!this.active)return;const o=this.availability();if(!o.available)return[`Command refused: the sandbox level is "${this.policy.level}", but ${o.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
|
|
3
|
+
`)}planNetworkEscalation(o){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const n=T(o.command);if(!n)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=io(n,o.cwd).filter(i=>!r.some(t=>B(i,t))&&!l.some(t=>B(i,t)));if(s.length===0)return;const a=n.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:a,justification:a==="package-install"?h("\u8FD9\u6761\u547D\u4EE4\u8981\u5B89\u88C5\u4F9D\u8D56\uFF0C\u9700\u8981\u4ECE\u8F6F\u4EF6\u6E90\u4E0B\u8F7D\u3002"):h("\u8FD9\u6761\u547D\u4EE4\u8981\u4ECE\u7F51\u4E0A\u4E0B\u8F7D\u6587\u4EF6\u3002")}}async prepare(o){const n=this.policy.level;if(n==="off")return H(o.command,{level:n,sandboxed:!1});const r=this.unavailableRefusal();if(r&&o.escalation?.mode!=="unsandboxed")throw new Error(r);let l=[],s=[],a;const i=o.escalation||r?void 0:this.planNetworkEscalation(o),t=i?await this.approveEscalation(o,i,i.trigger):void 0;if(i&&t&&t.decidedBy!=="none"){const f={request:t.request,decision:t.decision};if(a=f,!f.decision.approved)throw new Error(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${i.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`);l=t.allowDomains,s=t.allowWrite}else if(o.escalation){const{decidedBy:f,allowDomains:x,allowWrite:j,...b}=await this.approveEscalation(o,o.escalation);if(a=b,!b.decision.approved)throw new Error(`Sandbox escalation refused${b.decision.message?`: ${b.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(b.request.mode==="unsandboxed")return H(o.command,{level:n,sandboxed:!1,escalation:a});l=x,s=j}const d=this.availability(),p=o.shellKind??"bash";if(p!=="bash"&&d.mechanism!=="mxc")throw new Error(`Command refused: ${p} commands cannot run inside the ${d.mechanism??"OS"} sandbox, and the sandbox level is "${n}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);const u=this.scratchDir();n==="workspace-write"&&wo(T(o.command)?.managers);const w=to(this.policy,o.cwd,{gitDirs:this.policy.level==="workspace-write"?po(o.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:u}),c={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...l],deniedDomains:this.policy.network.deniedDomains,refusals:[]},D=`${process.pid}-${++uo}`,g=c.allowedDomains.length===0;if(d.mechanism==="mxc"&&d.mxc){const f=g?{...o.env??process.env,...U}:o.env;return this.prepareWindows({...o,...f?{env:f}:{}},{level:n,shellKind:p,scratch:u,rules:w,grant:c,runId:D,escalation:a,availability:d})}const y=vo(u),E=g?Object.entries(U).map(([f,x])=>` ${f}=${x}`).join(""):"",I=`export DAL_SANDBOX_RUN=${D} TMPDIR=${y} TMP=${y} TEMP=${y}${E}
|
|
4
|
+
${o.command}`,X=Date.now(),W=await ho({command:I,shell:o.shell,allowWrite:w.allowWrite,denyWrite:w.denyWrite,denyRead:w.denyRead,allowLocalBinding:o.background===!0||this.policy.network.allowLocalBinding,...d.ripgrep?{ripgrep:d.ripgrep}:{}},c),$={level:n,sandboxed:!0,...a?{escalation:a}:{}};let R=!1;return{command:W.command,sandboxed:!0,details:$,finish:m(async(f,x)=>{if(R)return $.denial;if(R=!0,W.release(),f===0)return;const j=d.platform==="darwin"?await mo(I,X,400):[],b=O({refusals:c.refusals,violations:j,output:x});if(!b)return;const A=W.proxied?void 0:M(),_={level:n,platform:d.platform,command:o.command,cwd:o.cwd,blocked:b,scratchDir:u,...A&&b.some(Y=>Y.kind==="network")?{networkProxyError:A}:{}};return $.denial=_,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:_}),_},"finish")}}async prepareWindows(o,n){const{level:r,grant:l,availability:s}=n,a=s.mxc;if(!a)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let i,t;if(l.allowedDomains.length>0){const c=await ro();"port"in c?i=c.port:t=c.error}const d=fo({runtime:a,kind:n.shellKind,shellPath:o.shell,command:o.command,cwd:o.cwd,level:r,rules:n.rules,env:o.env??process.env,scratchDir:n.scratch,runId:n.runId,...i!==void 0?{proxyPort:i}:{},allowLocalNetwork:o.background===!0||this.policy.network.allowLocalBinding}),p=lo(l),u={level:r,sandboxed:!0,...n.escalation?{escalation:n.escalation}:{}};let w=!1;return{command:d.command,sandboxed:!0,details:u,finish:m(async(c,D)=>{if(w)return u.denial;if(w=!0,p(),d.cleanup(),c===0)return;const g=O({refusals:l.refusals,violations:[],output:D});if(!g)return;const y={level:r,platform:s.platform,command:o.command,cwd:o.cwd,blocked:g,scratchDir:n.scratch,...t&&g.some(E=>E.kind==="network")?{networkProxyError:t}:{}};return u.denial=y,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:y}),y},"finish")}}uiApprovals=Promise.resolve();queueUiApproval(o){const n=this.uiApprovals.then(o,o);return this.uiApprovals=n.catch(()=>{}),n}async approveEscalation(o,n,r){const l=n.mode==="unsandboxed"?"unsandboxed":"allow",s={toolCallId:o.toolCallId,toolName:o.toolName,command:o.command,cwd:o.cwd,level:this.policy.level,mode:l,justification:typeof n.justification=="string"?n.justification.trim():"",allowDomains:l==="allow"?S(n.allow_domains):[],allowWrite:l==="allow"?S(n.allow_write).map(i=>L(i,o.cwd)):[],background:o.background===!0,...r?{trigger:r}:{}},a=m((i,t)=>{const d=i.approved&&i.scope==="session"&&l==="unsandboxed"?{...i,scope:"once"}:i,p=d.approved&&l==="allow"?d.grant:void 0,u=[...new Set([...s.allowDomains,...S(p?.allowDomains)])],w=[...new Set([...s.allowWrite,...S(p?.allowWrite).map(c=>L(c,o.cwd))])];if(d.approved&&d.scope==="session"){for(const c of u)this.sessionDomains.add(c);for(const c of w)this.sessionWritable.add(c)}return r&&t==="none"||this.onEvent?.({type:"sandbox_escalation",toolCallId:o.toolCallId,toolName:o.toolName,request:s,decision:d,decidedBy:t}),{request:s,decision:d,decidedBy:t,allowDomains:u,allowWrite:w}},"finish");if(!s.justification)return a({approved:!1,message:"an escalation needs a justification"},"none");if(l==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return a({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const i=await this.onEscalation(s,o.ctx);if(i)return a(i,"sdk")}for(const i of N){const t=await i(s,o.ctx);if(t)return a(t,"handler")}if(o.ctx?.hasUI){const i=o.ctx;return a(await this.queueUiApproval(()=>yo(s,i,o.signal)),"ui")}return a({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function H(e,o){return{command:e,sandboxed:!1,details:o,finish:m(async()=>{},"finish")}}m(H,"passthrough");function wo(e){if(!(!e||e.length===0))for(const o of ao(e))try{V(o,{recursive:!0,mode:448})}catch{}}m(wo,"ensurePackageCaches");function bo(){return z(q(Z(),"dal-sandbox-"))}m(bo,"createScratchDir");function vo(e){return`'${e.replace(/'/g,"'\\''")}'`}m(vo,"shellQuote");async function yo(e,o,n){if(n?.aborted)return{approved:!1,message:"the turn was interrupted before the user answered"};const r=h("\u4EC5\u672C\u6B21\u5141\u8BB8"),l=h("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),s=h("\u62D2\u7EDD"),a=e.mode==="unsandboxed"?h("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[e.allowDomains.length>0?v(h("\u8BBF\u95EE {domains}"),{domains:e.allowDomains.join(", ")}):"",e.allowWrite.length>0?v(h("\u5199\u5165 {paths}"),{paths:e.allowWrite.join(", ")}):""].filter(Boolean).join(h("\uFF0C\u5E76")),i=[v(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:a}),v(h("\u547D\u4EE4\uFF1A{command}"),{command:e.command}),v(h("\u76EE\u5F55\uFF1A{cwd}"),{cwd:e.cwd}),e.trigger?v(h("\u539F\u56E0\uFF1A{reason}"),{reason:e.justification}):v(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:e.justification})].join(`
|
|
5
|
+
`),t=e.mode==="unsandboxed"?[r,s]:[r,l,s],d=v(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:a}),p=await o.ui.select(i,t,{...n?{signal:n}:{},approval:{source:"sandbox",toolCallId:e.toolCallId,toolName:e.toolName,args:{command:e.command,cwd:e.cwd,mode:e.mode,...e.allowDomains.length>0?{allowDomains:e.allowDomains}:{},...e.allowWrite.length>0?{allowWrite:e.allowWrite}:{},justification:e.justification},risk:{level:e.mode==="unsandboxed"?"high":"medium",reason:e.trigger?e.justification:v(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:e.justification}),ruleId:`sandbox:${e.mode}`},title:d,description:i.split(`
|
|
6
|
+
`).slice(1).join(`
|
|
7
|
+
`),options:e.mode==="unsandboxed"?["allow_once","deny"]:["allow_once","allow_session","deny"]}});return n?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:p===r?{approved:!0,scope:"once"}:p===l?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}m(yo,"askThroughUi");export{Po as ShellSandbox,bo as createScratchDir,Ao as getProcessShellSandbox,Io as registerSandboxEscalationHandler,Ro as setProcessShellSandbox};
|
|
@@ -61,6 +61,7 @@ export interface ShellExecutionRequest {
|
|
|
61
61
|
}
|
|
62
62
|
export type ShellExecutionGuard = (request: ShellExecutionRequest) => Promise<string | undefined> | string | undefined;
|
|
63
63
|
export declare function registerShellExecutionGuard(guard: ShellExecutionGuard): () => void;
|
|
64
|
+
export declare function shellExecutionRefusal(request: ShellExecutionRequest): Promise<string | undefined>;
|
|
64
65
|
export interface BashSpawnContext {
|
|
65
66
|
command: string;
|
|
66
67
|
cwd: string;
|