dal-code 1.0.43 → 1.0.44
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 +9 -0
- package/dist/core/agent-session.js +7 -7
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/permissions/tool-policy.d.ts +2 -1
- package/dist/core/permissions/tool-policy.js +1 -1
- package/dist/core/sandbox/shell-sandbox.js +6 -6
- package/dist/core/tool-denial.d.ts +13 -0
- package/dist/core/tool-denial.js +1 -0
- package/dist/core/tools/bash.js +13 -13
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -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-bridge/src/index.js +1 -1
- 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 -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 +2 -2
- 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/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/src/cli.js +14 -9
- package/dist/node_modules/@dalcode/dal-remote/src/processes.js +2 -0
- package/dist/node_modules/@dalcode/dal-remote/src/service.js +7 -7
- package/dist/node_modules/@dalcode/dal-remote/src/spec.js +1 -1
- 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 +21 -21
- package/dist/node_modules/@dalcode/dal-subagent/src/progress.js +1 -1
- 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/dist/agent-loop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +1 -0
- 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/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,15 @@ DAL Code 的发布说明。这里只写用户看得见的变化。
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [1.0.44] - 2026-10-18
|
|
12
|
+
|
|
13
|
+
- 接入 DAL Code 的程序(包括手机端)重新打开历史对话时,能看到当时每个子助手做了多少步、最后停在哪一步、成功还是失败以及结论摘要,不再只有实时运行时才看得到子助手进度。
|
|
14
|
+
|
|
15
|
+
- 接入 DAL Code 的程序(包括手机端)重新打开一段历史对话时,能准确认出哪些操作被拒绝了、是谁拒绝的(你本人、审批规则、沙箱、危险命令拦截,还是 DAL Code 桌面应用),不再只能靠提示文字去猜。终端里的显示不变。
|
|
16
|
+
|
|
17
|
+
- `dal remote enable` 在 macOS 上不再提示“守护进程已启动,但还拿不到配对信息”:手机端后台服务改为按正常优先级运行,启动从半分钟以上缩短到一两秒,开启后当场显示配对二维码。启动较慢时会显示“正在等待守护进程就绪”的进度;服务启动失败或反复崩溃时直接说明失败,并给出日志最后几行,不再假装已经开好。
|
|
18
|
+
- `dal remote disable` 会确认手机端后台服务的所有进程都已退出,按时没退出的会被强制结束并列出;`dal remote status` 会列出不属于正在运行的服务的残留进程。
|
|
19
|
+
|
|
11
20
|
## [1.0.43] - 2026-10-18
|
|
12
21
|
|
|
13
22
|
- 不再问你一件最终一定会被拦下的事:`git clean -fd`、`rm -rf ~`、`git push --force` 这类会被危险命令拦截挡下的命令,现在直接拒绝并说明原因,不会先弹审批让你确认之后又被拦;正常需要审批的命令照旧只问一次。
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var
|
|
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(`
|
|
1
|
+
var ce=Object.defineProperty;var h=(T,e)=>ce(T,"name",{value:e,configurable:!0});import{readFileSync as he,rmSync as ue}from"node:fs";import{basename as me,dirname as ge}from"node:path";import{runToolCall as pe}from"@earendil-works/pi-agent-core";import{contentText as P,getCurrentSystemMessage as N,isNetworkAssistantError as fe,retryDelayMs as _e}from"@earendil-works/pi-ai";import{clampThinkingLevel as $,cleanupSessionResources as ye,getSupportedThinkingLevels as xe,isContextOverflow as B,isRecoverableLength as Me,isRetryableAssistantError as we,modelsAreEqual as k,resetApiProviders as be,streamSimple as Re}from"@earendil-works/pi-ai/compat";import{configureShellEnvironment as Te}from"../dal/child-env.js";import{fill as H,noteUserMessageLanguage as Ce,t as I}from"../dal/i18n.js";import{getThemeByName as Ae,theme as ve}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as Se}from"../utils/frontmatter.js";import{processImage as Ee}from"../utils/image-process.js";import{setOutputFileDirectory as Pe}from"../utils/output-files.js";import{sleep as ke}from"../utils/sleep.js";import{normalizeToolResultImages as Ie}from"../utils/tool-result-images.js";import{formatNoApiKeyFoundMessage as D,formatNoModelSelectedMessage as G}from"./auth-guidance.js";import{BackgroundProcessManager as Le}from"./background-processes.js";import{executeBashWithOperations as Ne}from"./bash-executor.js";import{generateBugReportSummary as Be}from"./bug-report.js";import{calculateContextTokens as Q,collectEntriesForBranchSummary as De,compact as Oe,compactionThreshold as V,estimateContextTokens as Fe,estimateProjectedContextTokens as S,estimateTokens as Ue,generateBranchSummary as We,PRUNE_TARGET_RATIO as je,planToolOutputPruning as qe,prepareCompaction as K,shouldCompact as J}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as ze,THINKING_LEVEL_OPTIONS as $e}from"./defaults.js";import{markBlankAssistantAsError as He}from"./empty-assistant.js";import{exportSessionToHtml as Ge}from"./export-html/index.js";import{createToolHtmlRenderer as Qe}from"./export-html/tool-renderer.js";import{ExtensionRunner as Ve,wrapRegisteredTools as X}from"./extensions/index.js";import{emitSessionShutdownEvent as Ke}from"./extensions/runner.js";import{createToolNameMatcher as Y,isMcpToolName as Z}from"./mcp-servers.js";import{convertToLlm as O}from"./messages.js";import{ModelRegistry as Je}from"./model-registry.js";import{isPlaceholderModel as Xe,pickHouseModel as Ye}from"./model-resolver.js";import{NestedToolCallRunner as Ze}from"./nested-tool-calls.js";import{buildRuleSet as et,EMPTY_RULE_SET as tt}from"./permissions/rules.js";import{buildReadGuard as st,evaluateToolPolicy as nt,permissionAskHandlers as ot,setProcessReadGuard as it}from"./permissions/tool-policy.js";import{expandPromptTemplate as ee}from"./prompt-templates.js";import{filesystemRules as rt,resolveSandboxPolicy as at,SANDBOX_ENV as lt,sandboxEnvironmentValue as dt}from"./sandbox/policy.js";import{createScratchDir as ct,ShellSandbox as ht,setProcessShellSandbox as ut}from"./sandbox/shell-sandbox.js";import{exportSessionToJsonl as mt}from"./session-export.js";import{getLatestCompactionEntry as te,SessionManager as gt}from"./session-manager.js";import{applyToolModifiers as se,DEFAULT_TOOL_NAMES as pt}from"./settings-manager.js";import{BUILTIN_PATH_PREFIX as ne,createSyntheticSourceInfo as F,isSyntheticPath as oe}from"./source-info.js";import{buildSystemPrompt as ft,buildSystemPromptSections as _t,diffSystemPromptSections as yt,normalizeBuildSystemPromptOptions as ie}from"./system-prompt.js";import{toolDenial as U,withToolDenial as W}from"./tool-denial.js";import{createLocalBashOperations as xt}from"./tools/bash.js";import{createAllToolDefinitions as Mt}from"./tools/index.js";import{createProcessToolDefinition as wt}from"./tools/process.js";import{createToolDefinitionFromAgentTool as bt}from"./tools/tool-definition-wrapper.js";import{addUsageToTotals as L,combineUsage as Rt,createUsageTotals as Tt}from"./usage-totals.js";import{findLatestResponse as Ct,getBranchSelection as At,getVirtualModelState as vt,isVirtualModel as A,VIRTUAL_MODEL_STATE_ENTRY as St}from"./virtual-models.js";function bs(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(bs,"parseSkillBlock");function re(T){return T?Object.fromEntries(Object.entries(T).filter(e=>e[1]!==null)):void 0}h(re,"withoutDeletedHeaders");function ae(T){let e=0;for(const t of T)e+=Ue(t);return e}h(ae,"estimateMessagesTokens");class Rs{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=tt;_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=Y(e.allowedToolNames),this._allowlistFiltersMcp=e.allowedToolNames.length===0||e.allowedToolNames.some(t=>t.startsWith("mcp__"))),this._excludedTools=e.excludedToolNames?Y(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 Le({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 ot()){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=H(I("\u89C4\u5219 {rule} \u8981\u6C42\u5148\u786E\u8BA4\u518D\u8FD0\u884C\u3002"),{rule:e.rule});return await t.ui.select([o,H(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(D(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:re(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(D(e.provider))}async _getSummarizationRequestAuth(e,t){const{model:s,thinkingLevel:n}=A(e)?await this._modelRuntime.resolveModel(e,O(this.messages),{reason:"direct",thinkingLevel:this.thinkingLevel,signal:t}):{model:e,thinkingLevel:this.thinkingLevel};if(this.agent.streamFunction===Re)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:re(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=At(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=nt({toolName:e.name,input:n,cwd:this._cwd},{rules:this._permissionRules,readGuard:this._readGuard});if(o?.behavior==="deny")return{block:!0,reason:o.reason,details:W(void 0,U("permission-rule",o.reason,o.rule))};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){const{denied:r,...l}=a,c=l.reason||"Tool execution was blocked";return{...l,details:W(void 0,U(r?.source??"extension",c,r?.ruleId))}}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){const l=`Not approved (permission rule ${o.rule} asks first)${r.message?`: ${r.message}`:"."}`;return{block:!0,reason:l,details:W(void 0,U("ask-rule",l,o.rule))}}}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 Ie(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 Ze({getTools:h(()=>this._getCallableTools(),"getTools"),isSequential:h(()=>this.agent.toolExecution==="sequential","isSequential"),runToolCall:h((o,i,a,r)=>{const l=this._findLastAssistantMessage();return l?pe(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:J(S(t,this.sessionManager.getBranch()).tokens,e.contextWindow,this.settingsManager.getCompactionSettings(this.model),this._compactionBaseTokens())}_compactionThresholdFor(e){return V(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=qe(s,t.keepRecentTokens);if(o.edits.length===0||n-o.tokensSaved>e*je)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=vt(this.sessionManager.getBranch(),l.provider,l.id),y=await this._modelRuntime.resolveModel(l,O(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(St,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=ie({...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=gt.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=O(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?Rt(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=He(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&&ue(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),ye(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=Ct(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 ft(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&&Z(e)}_isActivatable(e){return!this._allowedTools||this._allowedTools(e)||!Z(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
|
-
`):"",a=this._resourceLoader.getSkills().skills,r=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=
|
|
4
|
+
`):"",a=this._resourceLoader.getSkills().skills,r=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=ie({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=yt(N(t)?.sections??{},_t(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=se((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 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
|
|
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 Ee(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"&&Ce(r);let c=r;if(n&&(c=this._expandSkillCommand(c),c=ee(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(G());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(D(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=he(o.filePath,"utf-8"),a=Se(i).trim(),r=`<skill name="${o.name}" location="${o.filePath}">
|
|
8
8
|
References are relative to ${o.baseDir}.
|
|
9
9
|
|
|
10
10
|
${a}
|
|
11
11
|
</skill>`;return n?`${r}
|
|
12
12
|
|
|
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=
|
|
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
|
|
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=ee(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(!Xe(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Ye([...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?xe(this.model):[...$e]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return $(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??ze}_clampThinkingLevel(e,t){return this.model?$(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 Oe(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(G());const o=this.settingsManager.getCompactionSettings(n),i=this.sessionManager.getBranch(),a=K(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=ae(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=te(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)),le=i&&d&&Me(e,this.settingsManager.getOutputTokenLimit(o.maxTokens),o.contextWindow);if(w||le){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 j=m,de=j.entries.some(_=>_.sourceEntry.type==="context_edit"),q=e.usage?Q(e.usage):0;if(de)E=S(j,p).tokens;else if(e.stopReason==="error"||q===0){const _=this.agent.state.messages,R=Fe(_);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=q;const z=this._compactionBaseTokens();return J(E,a,n,z)?await this._runAutoCompaction("threshold",!1,V(a,n,z)):!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=K(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=ae(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=oe(t.extensionPath)?void 0:ge(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return oe(e)?`extension:${e.replace(/[<>]/g,"")}`:`extension:${me(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(`${ne}${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=X(i,r),c=X(Array.from(this._baseToolDefinitions.values()).filter(d=>this._isAllowedTool(d.name)).map(d=>({definition:d,sourceInfo:F(`${ne}${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??=ct(),this._sandboxScratch}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();Te(this.settingsManager.getShellEnvironmentPolicy());const o=at({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"});this._releaseOutputFileDirectory??=Pe(()=>this.getScratchDir());const i=new ht({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(),ut(i),process.env[lt]=dt(o),this._permissionRules=et(this.settingsManager.getPermissionRuleSources()),this._readGuard=st({cwd:this._cwd,rules:this._permissionRules,...o.level!=="off"?{protectedReads:rt(o,this._cwd).denyRead}:{}}),it(this._readGuard);const r=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([u,d])=>[u,bt(d)])):Mt(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",wt(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 Ve(l.extensions,l.runtime,this._cwd,this.sessionManager,new Je(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 Ke(t,{type:"session_shutdown",reason:"reload"}),t.invalidate();const n=h(()=>this._usesDefaultTools?se(this.settingsManager.getDefaultTools()??pt,this._defaultToolModifiers):[],"getDefaultTools"),o=new Set(n());await this.settingsManager.reload(),this.syncQueueModesFromSettings(),be(),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:we(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=_e(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error",cause:fe(e)?"network":"provider"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await ke(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 Ne(a,this.sessionManager.getCwd(),s?.operations??xt({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}=De(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 We(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=Tt();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=te(n);if(o){const r=new Set(s.entries.flatMap(m=>m.messages.some(u=>u.role==="assistant"&&u.stopReason!=="aborted"&&u.stopReason!=="error"&&Q(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&&Ae(o)!==void 0),n=Qe({getToolRenderers:h(o=>this._extensionRunner.resolveToolRenderers(o,()=>this.getToolDefinition(o)),"getToolRenderers"),theme:ve,cwd:this.sessionManager.getCwd()});return await Ge(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return mt(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");return Be({...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{Rs as AgentSession,bs as parseSkillBlock};
|
|
@@ -19,6 +19,7 @@ import type { Settings } from "../settings-manager.ts";
|
|
|
19
19
|
import type { SlashCommandInfo } from "../slash-commands.ts";
|
|
20
20
|
import type { SourceInfo } from "../source-info.ts";
|
|
21
21
|
import type { BuildSystemPromptOptions, NormalizedBuildSystemPromptOptions } from "../system-prompt.ts";
|
|
22
|
+
import type { ToolDenialHint } from "../tool-denial.ts";
|
|
22
23
|
import type { BashOperations } from "../tools/bash.ts";
|
|
23
24
|
import type { EditToolDetails } from "../tools/edit.ts";
|
|
24
25
|
import type { BashToolDetails, BashToolInput, EditToolInput, FindToolDetails, FindToolInput, GrepToolDetails, GrepToolInput, LsToolDetails, LsToolInput, PowerShellToolDetails, PowerShellToolInput, ReadToolDetails, ReadToolInput, WriteToolInput } from "../tools/index.ts";
|
|
@@ -720,6 +721,7 @@ export type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from
|
|
|
720
721
|
export interface ToolCallEventResult {
|
|
721
722
|
block?: boolean;
|
|
722
723
|
reason?: string;
|
|
724
|
+
denied?: ToolDenialHint;
|
|
723
725
|
terminate?: boolean;
|
|
724
726
|
}
|
|
725
727
|
export type UserBashEventResult = {
|
|
@@ -29,7 +29,8 @@ export declare function setProcessReadGuard(guard: ReadGuard | undefined): void;
|
|
|
29
29
|
export declare function readAccessDenial(absolutePath: string, guard?: ReadGuard | undefined): string | undefined;
|
|
30
30
|
export type ToolPolicyDecision = {
|
|
31
31
|
behavior: "deny";
|
|
32
|
-
reason: string;
|
|
32
|
+
reason: string ;
|
|
33
|
+
rule?: string;
|
|
33
34
|
} | {
|
|
34
35
|
behavior: "ask";
|
|
35
36
|
rule: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var t=(e,n)=>m(e,"name",{value:n,configurable:!0});import{existsSync as p,realpathSync as h}from"node:fs";import{isAbsolute as y,relative as b,resolve as v,sep as R}from"node:path";import{isReadOnlyBashCommand as k}from"../tools/bash-read-only.js";import{resolveToCwd as S}from"../tools/path-utils.js";import{matchPermissionRules as g,pathPatternMatches as w,readDenyPatterns as x,targetPathOf as P}from"./rules.js";const d=Symbol.for("dal.permissions.askHandlers"),a=globalThis;a[d]instanceof Set||(a[d]=new Set);const c=a[d];function j(e){return c.add(e),()=>{c.delete(e)}}t(j,"registerPermissionAskHandler");function B(){return[...c]}t(B,"permissionAskHandlers");let u;function C(e){u=e}t(C,"setProcessReadGuard");function l(e,n){const r=b(n,e);return r===""||r!==".."&&!r.startsWith(`..${R}`)&&!y(r)}t(l,"isWithin");function f(e){try{return p(e)?h(e):e}catch{return e}}t(f,"realpathOrSelf");function A(e,n=u){if(!n)return;const r=[...new Set([v(e),f(e)])];for(const s of n.deniedPaths){const o=f(s);if(r.some(i=>l(i,s)||l(i,o)))return`Reading ${e} is blocked: it is a protected credential location (${s}). The sandbox keeps it unreadable for every tool.`}for(const{pattern:s,rule:o}of n.deniedPatterns)if(r.some(i=>w(s,i,n.cwd)))return`Reading ${e} is blocked by the permission rule ${o}.`}t(A,"readAccessDenial");const $=new Set(["read","grep","find","ls","lsp"]);function L(e,n){if($.has(e.toolName)&&n.readGuard){const s=P(e);if(s!==void 0){const o=A(S(s,e.cwd),n.readGuard);if(o)return{behavior:"deny",reason:o}}}const r=g(n.rules,e,k);if(r?.behavior==="deny")return{behavior:"deny",reason:`Blocked by the permission rule ${r.rule} (${r.source==="user"?"~/.dal/agent/settings.json":".dal/settings.json"}).`};if(r?.behavior==="ask")return{behavior:"ask",rule:r.rule,source:r.source}}t(L,"evaluateToolPolicy");function M(e){const n=x(e.rules),r=e.protectedReads??[];if(!(r.length===0&&n.length===0))return{cwd:e.cwd,deniedPaths:r,deniedPatterns:n}}t(M,"buildReadGuard");export{M as buildReadGuard,L as evaluateToolPolicy,B as permissionAskHandlers,A as readAccessDenial,j as registerPermissionAskHandler,C as setProcessReadGuard};
|
|
1
|
+
var m=Object.defineProperty;var t=(e,n)=>m(e,"name",{value:n,configurable:!0});import{existsSync as p,realpathSync as h}from"node:fs";import{isAbsolute as y,relative as b,resolve as v,sep as R}from"node:path";import{isReadOnlyBashCommand as k}from"../tools/bash-read-only.js";import{resolveToCwd as S}from"../tools/path-utils.js";import{matchPermissionRules as g,pathPatternMatches as w,readDenyPatterns as x,targetPathOf as P}from"./rules.js";const d=Symbol.for("dal.permissions.askHandlers"),a=globalThis;a[d]instanceof Set||(a[d]=new Set);const c=a[d];function j(e){return c.add(e),()=>{c.delete(e)}}t(j,"registerPermissionAskHandler");function B(){return[...c]}t(B,"permissionAskHandlers");let u;function C(e){u=e}t(C,"setProcessReadGuard");function l(e,n){const r=b(n,e);return r===""||r!==".."&&!r.startsWith(`..${R}`)&&!y(r)}t(l,"isWithin");function f(e){try{return p(e)?h(e):e}catch{return e}}t(f,"realpathOrSelf");function A(e,n=u){if(!n)return;const r=[...new Set([v(e),f(e)])];for(const s of n.deniedPaths){const o=f(s);if(r.some(i=>l(i,s)||l(i,o)))return`Reading ${e} is blocked: it is a protected credential location (${s}). The sandbox keeps it unreadable for every tool.`}for(const{pattern:s,rule:o}of n.deniedPatterns)if(r.some(i=>w(s,i,n.cwd)))return`Reading ${e} is blocked by the permission rule ${o}.`}t(A,"readAccessDenial");const $=new Set(["read","grep","find","ls","lsp"]);function L(e,n){if($.has(e.toolName)&&n.readGuard){const s=P(e);if(s!==void 0){const o=A(S(s,e.cwd),n.readGuard);if(o)return{behavior:"deny",reason:o}}}const r=g(n.rules,e,k);if(r?.behavior==="deny")return{behavior:"deny",rule:r.rule,reason:`Blocked by the permission rule ${r.rule} (${r.source==="user"?"~/.dal/agent/settings.json":".dal/settings.json"}).`};if(r?.behavior==="ask")return{behavior:"ask",rule:r.rule,source:r.source}}t(L,"evaluateToolPolicy");function M(e){const n=x(e.rules),r=e.protectedReads??[];if(!(r.length===0&&n.length===0))return{cwd:e.cwd,deniedPaths:r,deniedPatterns:n}}t(M,"buildReadGuard");export{M as buildReadGuard,L as evaluateToolPolicy,B as permissionAskHandlers,A as readAccessDenial,j as registerPermissionAskHandler,C as setProcessReadGuard};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){const
|
|
3
|
-
`)}planNetworkEscalation(o){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const n=
|
|
4
|
-
${o.command}`,
|
|
5
|
-
`),t=e.mode==="unsandboxed"?[r,s]:[r,l,s],d=v(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:
|
|
1
|
+
var Q=Object.defineProperty;var c=(e,o)=>Q(e,"name",{value:o,configurable:!0});import{spawnSync as V}from"node:child_process";import{mkdirSync as z,mkdtempSync as J,rmSync as Z}from"node:fs";import{tmpdir as q}from"node:os";import{isAbsolute as T,join as oo,relative as eo,resolve as no}from"node:path";import{ToolExecutionError as ao}from"@earendil-works/pi-agent-core";import{fill as v,t as h}from"../../dal/i18n.js";import{toolDenial as io,withToolDenial as to}from"../tool-denial.js";import{detectSandboxAvailability as so}from"./availability.js";import{collectBlockedAccesses as O}from"./denial.js";import{detectNetworkCommand as U,FAIL_FAST_NETWORK_ENV as B,networkDomainsFor as ro,packageCacheDirs as lo}from"./package-managers.js";import{domainMatches as L,expandPath as M,filesystemRules as co}from"./policy.js";import{acquireSandboxRuntime as mo,ensureFilteringProxy as ho,proxyUnavailableReason as F,registerNetworkGrant as fo,releaseSandboxRuntime as po,violationsForCommand as uo,wrapCommand as wo}from"./runtime.js";import{prepareWindowsCommand as bo}from"./windows.js";function S(e,o){return new ao(e,to({sandbox:o},io("sandbox",e)))}c(S,"sandboxRefusal");const N=Symbol.for("dal.sandbox.escalationHandlers"),D=globalThis;D[N]instanceof Set||(D[N]=new Set);const R=D[N];function Uo(e){return R.add(e),()=>{R.delete(e)}}c(Uo,"registerSandboxEscalationHandler");const K=Symbol.for("dal.sandbox.processSandbox");function Bo(e){D[K]=e}c(Bo,"setProcessShellSandbox");function Lo(){return D[K]}c(Lo,"getProcessShellSandbox");const H=new Map;function vo(e){const o=H.get(e);if(o)return o;const n=V("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 i=s.trim();if(!i)continue;const a=T(i)?i:no(e,i),t=eo(e,a);(t.startsWith("..")||T(t))&&r.push(a)}const l=[...new Set(r)];return H.set(e,l),l}c(vo,"gitDirsOutside");function E(e){return Array.isArray(e)?e.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[]}c(E,"cleanList");let yo=0;class Mo{static{c(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&&(mo(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=go(),this.ownScratch)}async dispose(){this.ownScratch&&(Z(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await po())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??so()}status(){const o=this.availability(),n=F();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=U(o.command);if(!n)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=ro(n,o.cwd).filter(a=>!r.some(t=>L(a,t))&&!l.some(t=>L(a,t)));if(s.length===0)return;const i=n.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:i,justification:i==="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 X(o.command,{level:n,sandboxed:!1});const r=this.unavailableRefusal();if(r&&o.escalation?.mode!=="unsandboxed")throw S(r,{level:n,sandboxed:!1});let l=[],s=[],i;const a=o.escalation||r?void 0:this.planNetworkEscalation(o),t=a?await this.approveEscalation(o,a,a.trigger):void 0;if(a&&t&&t.decidedBy!=="none"){const f={request:t.request,decision:t.decision};if(i=f,!f.decision.approved)throw S(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${a.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`,{level:n,sandboxed:!1,escalation:f});l=t.allowDomains,s=t.allowWrite}else if(o.escalation){const{decidedBy:f,allowDomains:g,allowWrite:_,...b}=await this.approveEscalation(o,o.escalation);if(i=b,!b.decision.approved)throw S(`Sandbox escalation refused${b.decision.message?`: ${b.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`,{level:n,sandboxed:!1,escalation:i});if(b.request.mode==="unsandboxed")return X(o.command,{level:n,sandboxed:!1,escalation:i});l=g,s=_}const d=this.availability(),p=o.shellKind??"bash";if(p!=="bash"&&d.mechanism!=="mxc")throw S(`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\`.`,{level:n,sandboxed:!1});const u=this.scratchDir();n==="workspace-write"&&xo(U(o.command)?.managers);const w=co(this.policy,o.cwd,{gitDirs:this.policy.level==="workspace-write"?vo(o.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:u}),m={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...l],deniedDomains:this.policy.network.deniedDomains,refusals:[]},k=`${process.pid}-${++yo}`,x=m.allowedDomains.length===0;if(d.mechanism==="mxc"&&d.mxc){const f=x?{...o.env??process.env,...B}:o.env;return this.prepareWindows({...o,...f?{env:f}:{}},{level:n,shellKind:p,scratch:u,rules:w,grant:m,runId:k,escalation:i,availability:d})}const y=Do(u),W=x?Object.entries(B).map(([f,g])=>` ${f}=${g}`).join(""):"",I=`export DAL_SANDBOX_RUN=${k} TMPDIR=${y} TMP=${y} TEMP=${y}${W}
|
|
4
|
+
${o.command}`,Y=Date.now(),$=await wo({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}:{}},m),j={level:n,sandboxed:!0,...i?{escalation:i}:{}};let A=!1;return{command:$.command,sandboxed:!0,details:j,finish:c(async(f,g)=>{if(A)return j.denial;if(A=!0,$.release(),f===0)return;const _=d.platform==="darwin"?await uo(I,Y,400):[],b=O({refusals:m.refusals,violations:_,output:g});if(!b)return;const P=$.proxied?void 0:F(),C={level:n,platform:d.platform,command:o.command,cwd:o.cwd,blocked:b,scratchDir:u,...P&&b.some(G=>G.kind==="network")?{networkProxyError:P}:{}};return j.denial=C,this.onEvent?.({type:"sandbox_denied",toolCallId:o.toolCallId,toolName:o.toolName,denial:C}),C},"finish")}}async prepareWindows(o,n){const{level:r,grant:l,availability:s}=n,i=s.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let a,t;if(l.allowedDomains.length>0){const m=await ho();"port"in m?a=m.port:t=m.error}const d=bo({runtime:i,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,...a!==void 0?{proxyPort:a}:{},allowLocalNetwork:o.background===!0||this.policy.network.allowLocalBinding}),p=fo(l),u={level:r,sandboxed:!0,...n.escalation?{escalation:n.escalation}:{}};let w=!1;return{command:d.command,sandboxed:!0,details:u,finish:c(async(m,k)=>{if(w)return u.denial;if(w=!0,p(),d.cleanup(),m===0)return;const x=O({refusals:l.refusals,violations:[],output:k});if(!x)return;const y={level:r,platform:s.platform,command:o.command,cwd:o.cwd,blocked:x,scratchDir:n.scratch,...t&&x.some(W=>W.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"?E(n.allow_domains):[],allowWrite:l==="allow"?E(n.allow_write).map(a=>M(a,o.cwd)):[],background:o.background===!0,...r?{trigger:r}:{}},i=c((a,t)=>{const d=a.approved&&a.scope==="session"&&l==="unsandboxed"?{...a,scope:"once"}:a,p=d.approved&&l==="allow"?d.grant:void 0,u=[...new Set([...s.allowDomains,...E(p?.allowDomains)])],w=[...new Set([...s.allowWrite,...E(p?.allowWrite).map(m=>M(m,o.cwd))])];if(d.approved&&d.scope==="session"){for(const m of u)this.sessionDomains.add(m);for(const m of w)this.sessionWritable.add(m)}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 i({approved:!1,message:"an escalation needs a justification"},"none");if(l==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return i({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const a=await this.onEscalation(s,o.ctx);if(a)return i(a,"sdk")}for(const a of R){const t=await a(s,o.ctx);if(t)return i(t,"handler")}if(o.ctx?.hasUI){const a=o.ctx;return i(await this.queueUiApproval(()=>ko(s,a,o.signal)),"ui")}return i({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function X(e,o){return{command:e,sandboxed:!1,details:o,finish:c(async()=>{},"finish")}}c(X,"passthrough");function xo(e){if(!(!e||e.length===0))for(const o of lo(e))try{z(o,{recursive:!0,mode:448})}catch{}}c(xo,"ensurePackageCaches");function go(){return J(oo(q(),"dal-sandbox-"))}c(go,"createScratchDir");function Do(e){return`'${e.replace(/'/g,"'\\''")}'`}c(Do,"shellQuote");async function ko(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"),i=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")),a=[v(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),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:i}),p=await o.ui.select(a,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:a.split(`
|
|
6
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"}}
|
|
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"}}c(ko,"askThroughUi");export{Mo as ShellSandbox,go as createScratchDir,Lo as getProcessShellSandbox,Uo as registerSandboxEscalationHandler,Bo as setProcessShellSandbox};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type ToolDenialSource = "permission-rule" | "ask-rule" | "dal-guard" | "sandbox" | "dangerous-command" | "bridge" | "extension";
|
|
2
|
+
export interface ToolDenial {
|
|
3
|
+
source: ToolDenialSource;
|
|
4
|
+
reason: string;
|
|
5
|
+
ruleId?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface ToolDenialHint {
|
|
8
|
+
source: ToolDenialSource;
|
|
9
|
+
ruleId?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function withToolDenial(details: unknown, denial: ToolDenial): Record<string, unknown>;
|
|
12
|
+
export declare function toolDenial(source: ToolDenialSource, reason: string, ruleId?: string): ToolDenial;
|
|
13
|
+
export declare function getToolDenial(details: unknown): ToolDenial | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty;var t=(e,n)=>f(e,"name",{value:n,configurable:!0});function u(e,n){return{...e&&typeof e=="object"&&!Array.isArray(e)?e:{},denied:n}}t(u,"withToolDenial");function c(e,n,o){return{source:e,reason:n,...o?{ruleId:o}:{}}}t(c,"toolDenial");function p(e){if(!e||typeof e!="object")return;const n=e.denied;if(!n||typeof n!="object")return;const{source:o,reason:r}=n;return typeof o=="string"&&typeof r=="string"?n:void 0}t(p,"getToolDenial");export{p as getToolDenial,c as toolDenial,u as withToolDenial};
|