dal-code 1.0.26 → 1.0.27
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 +13 -0
- package/dal-docs/settings.md +18 -2
- package/dist/core/agent-session.d.ts +13 -0
- package/dist/core/agent-session.js +9 -9
- package/dist/core/background-processes.js +4 -4
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/permission-surface.js +1 -1
- package/dist/core/extensions/runner.js +1 -1
- package/dist/core/extensions/types.d.ts +3 -0
- package/dist/core/sandbox/availability.d.ts +6 -1
- package/dist/core/sandbox/availability.js +1 -1
- package/dist/core/sandbox/denial.js +3 -3
- package/dist/core/sandbox/runtime.d.ts +10 -0
- package/dist/core/sandbox/runtime.js +1 -1
- package/dist/core/sandbox/shell-sandbox.d.ts +6 -0
- package/dist/core/sandbox/shell-sandbox.js +5 -5
- package/dist/core/sandbox/windows.d.ts +122 -0
- package/dist/core/sandbox/windows.js +5 -0
- package/dist/core/tools/bash.d.ts +1 -0
- package/dist/core/tools/bash.js +6 -6
- package/dist/core/tools/powershell.js +2 -2
- package/dist/modes/rpc/environment-update.js +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +14 -0
- package/dist/modes/rpc/rpc-client.js +3 -3
- package/dist/modes/rpc/rpc-mode.d.ts +1 -0
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +13 -0
- 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-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- 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-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/add-wizard.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
- package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
- package/dist/node_modules/@dalcode/dal-mcp/src/report.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
- 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-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- 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-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
- 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/amazon-bedrock.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-coding-agent/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 +5 -5
- package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/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-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/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 +10 -2
- package/package.json +9 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,19 @@ DAL Code 的发布说明。这里只写用户看得见的变化。
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [1.0.27] - 2026-09-29
|
|
12
|
+
|
|
13
|
+
- **需要留意:不再内置 chrome-devtools MCP 服务器。** 以前在 DAL Code 中每个新会话都会用 `npx -y chrome-devtools-mcp@latest` 从网络下载并启动它:没有固定版本、没问过你,离线时用不了,还让每次新对话的第一条消息多等 10–30 秒。现在默认不配置任何 MCP 服务器。需要浏览器调试工具时,用 `/mcp add` 自己添加,并写明版本号,例如 `npx -y chrome-devtools-mcp@<版本号> --headless`。已经在 `mcp.json` 里自己配置过的服务器不受影响。
|
|
14
|
+
- 新会话不再等 MCP 服务器连上才开始:第一条消息立刻发出,「停止」也立刻生效。各个 MCP 服务器在后台同时连接,每个最多等 30 秒(可用环境变量 `DAL_MCP_CONNECT_TIMEOUT_MS` 调整),连上后它的工具从下一次请求起可用;上次用过的服务器,工具一开始就可用,助手调用时会等它连上。连不上或超时的服务器会说明原因,`/mcp` 列表里显示「连接中 / 已连接 / 连接失败」。
|
|
15
|
+
- 修复发出消息后马上点「停止」,助手仍然开始回答(甚至自动重试)的问题:消息还在准备阶段时停止,这条消息会被取消,不会再发给模型。
|
|
16
|
+
- 在其他程序中嵌入 DAL 时,宿主能实时收到每个 MCP 服务器的连接状态(连接中、已连接、失败及原因)。
|
|
17
|
+
- 在其他程序中嵌入 DAL 时,宿主可以在同一个 DAL 进程运行期间更新每轮对话用的凭据和编号,不必每轮重开一个进程;因此上一轮启动的开发服务器等后台进程,在下一轮还在运行。
|
|
18
|
+
- 在其他程序中嵌入 DAL 时,宿主可以直接查看沙箱状态、列出后台进程、读取它们的输出和停止它们。
|
|
19
|
+
- 在其他程序中运行 `/review` 这类较慢的命令时,DAL 在命令开始时就确认收到,并在命令结束时另行通知,不再因为等待过久被宿主当成超时。
|
|
20
|
+
- 在 DAL Code 中,越出沙箱的请求选择「允许并记住(本会话)」后,同一会话里需要同样域名或目录的命令不再逐条询问。
|
|
21
|
+
- **Windows 上助手的命令也在系统沙箱里运行了。** 使用微软的 Microsoft eXecution Containers(mxc),规则与 macOS / Linux 相同:只能写当前工作目录和本会话的临时目录,默认断网,按域名放行的网络走 DAL 的过滤代理;bash(Git Bash)和 PowerShell 命令都在沙箱里执行,它们再启动的 `cmd.exe` 等程序同样受限。需要 Windows 11 24H2 或 Windows Server 2025 以上,并安装 mxc:`npm install -g @microsoft/mxc-sdk@0.6.0`(DAL Code 自带)。缺少任一条件时,命令会被拒绝并说明原因,不会悄悄在沙箱外运行;仍可用 `--sandbox off` 明确关闭。
|
|
22
|
+
- 与 macOS / Linux 的差别:受保护的文件(`.env`、`.vscode`、`~/.ssh` 等)只有在命令开始前已存在才受保护;允许本地监听的后台进程也能访问局域网。`get_sandbox_status` 会列出这些限制。
|
|
23
|
+
|
|
11
24
|
## [1.0.26] - 2026-09-29
|
|
12
25
|
|
|
13
26
|
- **需要留意:助手运行的命令默认在系统沙箱里执行,并且默认断网。** 独立使用 `dal` 时,助手执行的 shell 命令(包括子助手的命令)只能写当前工作目录和本会话自己的临时目录,读不到 `~/.ssh`、云服务凭据、钥匙串等敏感文件,也改不了 `.git/hooks`、`.dal`、`.claude`、`.vscode`、`.env` 这类会在以后自动执行或存放密钥的文件;网络默认关闭。macOS 使用系统自带的 Seatbelt,Linux 需要安装 bubblewrap(`bwrap`)和 ripgrep,需要按域名放行网络时再装 `socat`。
|
package/dal-docs/settings.md
CHANGED
|
@@ -55,15 +55,31 @@ server name). `/mcp` edits them interactively.
|
|
|
55
55
|
```json
|
|
56
56
|
{
|
|
57
57
|
"mcpServers": {
|
|
58
|
-
"filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] },
|
|
58
|
+
"filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem@<version>", "."] },
|
|
59
59
|
"docs": { "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer <token>" } },
|
|
60
|
-
"
|
|
60
|
+
"old-server": { "disabled": true }
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
```
|
|
64
64
|
|
|
65
65
|
Tools appear as `mcp__<server>__<tool>` and always require approval.
|
|
66
66
|
|
|
67
|
+
No server is built in. Pin the version of anything launched through `npx`
|
|
68
|
+
(`package@1.2.3`, not `@latest`): an unpinned package is fetched from the
|
|
69
|
+
network and may change on every start. The browser tools DAL Code sessions used
|
|
70
|
+
to get by default are one `/mcp add` away:
|
|
71
|
+
`npx -y chrome-devtools-mcp@<version> --headless`.
|
|
72
|
+
|
|
73
|
+
A session never waits for MCP servers. Servers connect in the background, all
|
|
74
|
+
at once; each gets `DAL_MCP_CONNECT_TIMEOUT_MS` (default 30000) to answer
|
|
75
|
+
`initialize` and `tools/list` before it is marked failed. A server's tools are
|
|
76
|
+
registered when it connects and the model sees them on its next request. Tools
|
|
77
|
+
of a server used before are known from the cache and available immediately; a
|
|
78
|
+
call made while that server is still connecting waits for it. `/mcp` shows
|
|
79
|
+
each server as connecting, connected or failed (with the reason), and hosts
|
|
80
|
+
receive the same as `mcp_status` events (see the RPC event docs, "Host
|
|
81
|
+
events").
|
|
82
|
+
|
|
67
83
|
## Custom models — models.json
|
|
68
84
|
|
|
69
85
|
Models normally come from the DeepAILab gateway after `/login`.
|
|
@@ -41,6 +41,17 @@ export type AgentSessionEvent = Exclude<AgentEvent, {
|
|
|
41
41
|
} | {
|
|
42
42
|
type: "session_info_changed";
|
|
43
43
|
name: string | undefined;
|
|
44
|
+
} | {
|
|
45
|
+
type: "extension_command_start";
|
|
46
|
+
command: string;
|
|
47
|
+
} | {
|
|
48
|
+
type: "extension_command_end";
|
|
49
|
+
command: string;
|
|
50
|
+
error?: string;
|
|
51
|
+
} | {
|
|
52
|
+
type: "extension_event";
|
|
53
|
+
name: string;
|
|
54
|
+
data: unknown;
|
|
44
55
|
} | {
|
|
45
56
|
type: "thinking_level_changed";
|
|
46
57
|
level: ThinkingLevel;
|
|
@@ -159,6 +170,7 @@ export declare class AgentSession {
|
|
|
159
170
|
private _unsubscribeAgent?;
|
|
160
171
|
private _eventListeners;
|
|
161
172
|
private _isAgentRunActive;
|
|
173
|
+
private _promptAbortGeneration;
|
|
162
174
|
private _agentRunAbortRequested;
|
|
163
175
|
private _idleWaitPromise;
|
|
164
176
|
private _resolveIdleWait;
|
|
@@ -298,6 +310,7 @@ export declare class AgentSession {
|
|
|
298
310
|
private _runInputHandlers;
|
|
299
311
|
private _normalizePromptImages;
|
|
300
312
|
prompt(text: string, options?: PromptOptions): Promise<void>;
|
|
313
|
+
private _prompt;
|
|
301
314
|
private _tryExecuteExtensionCommand;
|
|
302
315
|
private _expandSkillCommand;
|
|
303
316
|
private _queueUserInput;
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var X=Object.defineProperty;var c=(
|
|
2
|
-
`),[n,I("\u62D2\u7EDD")])===n?{approved:!0}:{approved:!1,message:"the user declined"}}getSandboxStatus(){return this._shellSandbox?.status()}get backgroundProcesses(){return this._backgroundProcesses}async _getRequiredRequestAuth(e,t){let s;try{s=await this._modelRuntime.getAuth(e,{signal:t})}catch(i){const o=i instanceof Error?i.cause:void 0;throw o instanceof Error&&o.message==="authHeader requires a resolved API key"?new Error(F(e.provider)):i}if(s&&(s.auth.apiKey||s.auth.headers))return{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:V(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(F(e.provider))}async _getSummarizationRequestAuth(e,t){if(this.agent.streamFunction===le)return this._getRequiredRequestAuth(e,t);try{const s=await this._modelRuntime.getAuth(e,{signal:t});return s?{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:V(s.auth.headers),env:s.env}:{model:e}}catch(s){if(t?.aborted)throw s;return{model:e}}}_installAgentToolHooks(){this.agent.beforeToolCall=async({toolCall:e,args:t})=>{const s=t??{},n=Ue({toolName:e.name,input:s,cwd:this._cwd},{rules:this._permissionRules,readGuard:this._readGuard});if(n?.behavior==="deny")return{block:!0,reason:n.reason};const i=this._extensionRunner;let o;if(i.hasHandlers("tool_call"))try{o=await i.emitToolCall({type:"tool_call",toolName:e.name,toolCallId:e.id,input:s})}catch(r){throw r instanceof Error?r:new Error(`Extension failed, blocking execution: ${String(r)}`)}if(o?.block)return o;if(n?.behavior==="ask"){const r=await this._askPermission({toolCallId:e.id,toolName:e.name,input:s,cwd:this._cwd,rule:n.rule,source:n.source});if(!r.approved)return{block:!0,reason:`Not approved (permission rule ${n.rule} asks first)${r.message?`: ${r.message}`:"."}`}}return o},this.agent.afterToolCall=async({toolCall:e,args:t,result:s,isError:n})=>{const i=this._extensionRunner,o=i.hasHandlers("tool_result")?await i.emitToolResult({type:"tool_result",toolName:e.name,toolCallId:e.id,input:t,content:s.content,details:s.details,isError:n,usage:s.usage}):void 0,r=o?.content??s.content??[],l=this.model?.inputLimits?.images?.resize,a=await pe(r,{autoResizeImages:this.settingsManager.getImageAutoResize(),...l?{resizeOptions:l}:{}});if(!(!o&&a===r))return{content:a,details:o?.details,isError:o?.isError??n,usage:o?.usage}}}async _compactBeforeNextAssistantResponse(e){const t=this.model,s=this.settingsManager.getCompactionSettings(t),n=this.sessionManager.buildSessionProjection();return!t||t.contextWindow<=0||!H(k(n,this.sessionManager.getBranch()).tokens,t.contextWindow,s)?{...e,messages:n.messages}:(await this._runAutoCompaction("threshold",!1),{...e,messages:this.sessionManager.buildSessionProjection().messages})}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n={...t.context,messages:this.sessionManager.buildSessionProjection().messages,tools:this.agent.state.tools.slice()},i=await e?.({...t,context:n,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{...i,context:i?.context??n,model:i?.model??this.agent.state.model,thinkingLevel:i?.thinkingLevel??this.agent.state.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(o=>{const r=this._findPersistedMessageEntryId(o);return r?[r]:[]}),i=await this._extensionRunner.emitBoundary({type:"turn_end",turnIndex:this._turnIndex,message:e,toolResults:t,messageEntryId:s,toolResultEntryIds:n,outcome:this._lastActivityOutcome},o=>this._buildBoundaryContext(o,"turn_end"));return this._commitBoundaryDrafts(i.entries),i.continue&&!this._buildBoundaryContext([],"turn_end").canContinue?(this._reportInvalidBoundaryContinuation("turn_end"),!1):i.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),i=await e?.(t,s);if(i?.action==="end")return i;if(n||i?.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,messages:this.sessionManager.buildSessionProjection().messages}),i=await e?.({...t,context:n},s),o=i?.context??n,r=this._runSystemPromptOptions??this._baseSystemPromptOptions,l=Q({...r,selectedTools:this.getActiveToolNames(),toolSnippets:{...this._baseSystemPromptOptions.toolSnippets,...r.toolSnippets},toolGuidelines:{...this._baseSystemPromptOptions.toolGuidelines,...r.toolGuidelines}}),a=this._preparePromptAndToolLoadout(l,o.messages);return this._runSystemPromptOptions=l,{...i,context:{...o,tools:this.agent.state.tools.slice()},messages:a?[...i?.messages??[],a]:i?.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 i;switch(n.type){case"custom":i=e.appendCustomEntry(n.customType,n.data);break;case"custom_message":i=e.appendCustomMessageEntry(n.customType,n.content,n.display,n.details);break;case"context_edit":i=e.appendContextEdit(n.targetId,n.replacement);break;case"compaction":{const r=k(e.buildSessionProjection(),e.getBranch()).tokens;i=e.appendCompaction(n.summary,n.firstKeptEntryId,r,n.details,!0,n.usage);break}}const o=e.getEntry(i);o&&s.push(o)}return s}_createBoundaryPreviewManager(e){const t=this.sessionManager.getHeader();if(!t)throw new Error("Session header is missing");const s=Ve.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(),i=Ie(s.messages),o=i[i.length-1]?.role,l=i.some(m=>m.role!=="system")&&o!=="assistant",a=this._pendingCustomMessages.length>0;return{contextEntries:s.entries,contextMessages:s.messages,llmMessages:i,pendingMessages:n,canContinue:l||a||(t==="turn_end"?this.agent.hasQueuedMessages():o==="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{await this._extensionRunner.emit({type:"agent_settled"}),this._emit({type:"agent_settled"})}finally{this._isEmittingAgentSettled=!1}const e=this._deferredSettledActions.splice(0);if(e.length>0){try{for(const t of e)await t()}finally{this._resolveIdleWaitIfIdle()}return}this._resolveIdleWaitIfIdle()}_handleAgentEvent=c(async e=>{if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=E(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=Ce(t);if(s!==t){e.message=s;const n=this.agent.state.messages;for(let i=n.length-1;i>=0;i--)if(n[i]===t){n[i]=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 o of[...this.sessionManager.getBranch()].reverse())if(o.type==="message"&&o.message===e)return o.id;const s=this.agent.state.messages.indexOf(e);if(s<0)return;const n=this.sessionManager.buildSessionProjection();let i=0;for(const o of n.entries)for(let r=0;r<o.messages.length;r++){if(i===s)return this._entryIdsByMessage.set(e,o.sourceEntry.id),o.sourceEntry.id;i++}}_omitRecoveryAttempt(e,t=[]){const s=[e,...t],n=s.map(o=>this._findPersistedMessageEntryId(o));if(s.some((o,r)=>n[r]===void 0&&this.agent.state.messages.includes(o)))throw new Error("Cannot persist recovery omission because a projected message has no source entry");for(const o of n){if(!o)continue;const r=this.sessionManager.appendContextEdit(o,null),l=this.sessionManager.getEntry(r);l&&this._emit({type:"entry_appended",entry:l})}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};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."),this._disconnectFromAgent(),this._eventListeners=[];const e=this._shellSandbox,t=this._sandboxScratch;this._sandboxScratch=void 0,this._backgroundProcesses.stopAll().finally(()=>(t&&Z(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),ne(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 isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return Je(this._runSystemPromptOptions??this._baseSystemPromptOptions)}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}isToolAllowed(e){return(!this._allowedToolNames||this._allowedToolNames.has(e))&&!this._excludedToolNames?.has(e)}getToolDenylist(){return this._excludedToolNames&&this._excludedToolNames.size>0?[...this._excludedToolNames]:void 0}getToolAllowlist(){if(this._allowedToolNames)return[...this._allowedToolNames].filter(e=>!this._excludedToolNames?.has(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,sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=[],s=[];for(const n of e){const i=this._toolRegistry.get(n);i&&(t.push(i),s.push(n))}this.agent.state.tools=t,this._rebuildSystemPrompt(s)}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(a=>this._toolRegistry.has(a)),s={};for(const a of this._toolRegistry.keys()){const m=this._toolPromptSnippets.get(a);m&&(s[a]=m)}const n=this._resourceLoader.getSystemPrompt(),i=this._resourceLoader.getAppendSystemPrompt(),o=i.length>0?i.join(`
|
|
1
|
+
var X=Object.defineProperty;var c=(S,e)=>X(S,"name",{value:e,configurable:!0});import{readFileSync as Y,rmSync as Z}from"node:fs";import{basename as ee,dirname as te}from"node:path";import{contentText as E,getCurrentSystemMessage as B,retryDelayMs as se}from"@earendil-works/pi-ai";import{clampThinkingLevel as D,cleanupSessionResources as ne,getSupportedThinkingLevels as ie,isContextOverflow as N,isRecoverableLength as oe,isRetryableAssistantError as re,modelsAreEqual as P,resetApiProviders as ae,streamSimple as le}from"@earendil-works/pi-ai/compat";import{configureShellEnvironment as de}from"../dal/child-env.js";import{fill as W,t as I}from"../dal/i18n.js";import{getThemeByName as ce,theme as he}from"../modes/interactive/theme/theme.js";import{stripFrontmatter as ue}from"../utils/frontmatter.js";import{processImage as me}from"../utils/image-process.js";import{sleep as ge}from"../utils/sleep.js";import{normalizeToolResultImages as pe}from"../utils/tool-result-images.js";import{formatNoApiKeyFoundMessage as F,formatNoModelSelectedMessage as z}from"./auth-guidance.js";import{BackgroundProcessManager as fe}from"./background-processes.js";import{executeBashWithOperations as _e}from"./bash-executor.js";import{generateBugReportSummary as ye}from"./bug-report.js";import{calculateContextTokens as j,collectEntriesForBranchSummary as xe,compact as we,estimateContextTokens as be,estimateProjectedContextTokens as k,estimateTokens as Me,generateBranchSummary as Re,prepareCompaction as q,shouldCompact as H}from"./compaction/index.js";import{DEFAULT_THINKING_LEVEL as Ae,THINKING_LEVEL_OPTIONS as Se}from"./defaults.js";import{markBlankAssistantAsError as Ce}from"./empty-assistant.js";import{exportSessionToHtml as ve}from"./export-html/index.js";import{createToolHtmlRenderer as Te}from"./export-html/tool-renderer.js";import{ExtensionRunner as Ee,wrapRegisteredTools as $}from"./extensions/index.js";import{emitSessionShutdownEvent as Pe}from"./extensions/runner.js";import{convertToLlm as Ie}from"./messages.js";import{ModelRegistry as ke}from"./model-registry.js";import{isPlaceholderModel as Le,pickHouseModel as Be}from"./model-resolver.js";import{buildRuleSet as Ne,EMPTY_RULE_SET as Fe}from"./permissions/rules.js";import{buildReadGuard as Oe,evaluateToolPolicy as Ue,permissionAskHandlers as De,setProcessReadGuard as We}from"./permissions/tool-policy.js";import{expandPromptTemplate as G}from"./prompt-templates.js";import{filesystemRules as ze,resolveSandboxPolicy as je,SANDBOX_ENV as qe,sandboxEnvironmentValue as He}from"./sandbox/policy.js";import{createScratchDir as $e,ShellSandbox as Ge,setProcessShellSandbox as Ke}from"./sandbox/shell-sandbox.js";import{exportSessionToJsonl as Qe}from"./session-export.js";import{getLatestCompactionEntry as K,SessionManager as Ve}from"./session-manager.js";import{createSyntheticSourceInfo as O}from"./source-info.js";import{buildSystemPrompt as Je,buildSystemPromptSections as Xe,diffSystemPromptSections as Ye,normalizeBuildSystemPromptOptions as Q}from"./system-prompt.js";import{createLocalBashOperations as Ze}from"./tools/bash.js";import{createAllToolDefinitions as et}from"./tools/index.js";import{createProcessToolDefinition as tt}from"./tools/process.js";import{createToolDefinitionFromAgentTool as st}from"./tools/tool-definition-wrapper.js";import{addUsageToTotals as L,createUsageTotals as nt}from"./usage-totals.js";function Ht(S){const e=S.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);return e?{name:e[1],location:e[2],content:e[3],userMessage:e[4]?.trim()||void 0}:null}c(Ht,"parseSkillBlock");function V(S){return S?Object.fromEntries(Object.entries(S).filter(e=>e[1]!==null)):void 0}c(V,"withoutDeletedHeaders");function J(S){let e=0;for(const t of S)e+=Me(t);return e}c(J,"estimateMessagesTokens");class $t{static{c(this,"AgentSession")}agent;sessionManager;settingsManager;_scopedModels;_unsubscribeAgent;_eventListeners=[];_isAgentRunActive=!1;_promptAbortGeneration=0;_agentRunAbortRequested=!1;_idleWaitPromise;_resolveIdleWait;_steeringMessages=[];_followUpMessages=[];_pendingNextTurnMessages=[];_pendingCustomMessages=[];_compactionAbortController=void 0;_autoCompactionAbortController=void 0;_overflowRecoveryAttempted=!1;_branchSummaryAbortController=void 0;_retryAbortController=void 0;_retryAttempt=0;_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;_allowedToolNames;_excludedToolNames;_baseToolsOverride;_sandboxOptions;_permissionRules=Fe;_readGuard;_shellSandbox;_sandboxScratch;_backgroundProcesses;_sessionStartEvent;_extensionUIContext;_extensionMode="print";_extensionCommandContextActions;_extensionAbortHandler;_extensionShutdownHandler;_extensionErrorListener;_extensionErrorUnsubscriber;_modelRuntime;_desiredModel;_cacheWarmer;_toolRegistry=new Map;_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._allowedToolNames=e.allowedToolNames?new Set(e.allowedToolNames):void 0,this._excludedToolNames=e.excludedToolNames?new Set(e.excludedToolNames):void 0,this._baseToolsOverride=e.baseToolsOverride,this._sandboxOptions=e.sandbox??{},this._backgroundProcesses=new fe({sandbox:c(()=>this._shellSandbox,"sandbox"),shellPath:c(()=>this.settingsManager.getShellPath(),"shellPath"),onEvent:c(t=>this._emit(t),"onEvent")}),this._sessionStartEvent=e.sessionStartEvent??{type:"session_start",reason:"startup"},this._unsubscribeAgent=this.agent.subscribe(this._handleAgentEvent),this._installAgentToolHooks(),this._installAgentNextTurnRefresh(),this._installAgentRequestProjection(),this._installAgentBoundaryHooks(),this._installAgentForcedPromptProjection(),this._buildRuntime({activeToolNames:this._initialActiveToolNames,includeAllExtensionTools:!0}),this._initialActiveToolNames===void 0&&this._restoreToolsFromTranscript()}get modelRuntime(){return this._modelRuntime}async _askPermission(e){const t=this._extensionRunner.createContext();for(const o of De()){const r=await o(e,t);if(r)return r}if(!t.hasUI)return{approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"};const s=typeof e.input.command=="string"?e.input.command:JSON.stringify(e.input),n=I("\u4EC5\u672C\u6B21\u5141\u8BB8");return await t.ui.select([W(I("\u89C4\u5219 {rule} \u8981\u6C42\u5148\u786E\u8BA4\u518D\u8FD0\u884C\u3002"),{rule:e.rule}),W(I("\u5DE5\u5177\uFF1A{tool}"),{tool:e.toolName}),s].join(`
|
|
2
|
+
`),[n,I("\u62D2\u7EDD")])===n?{approved:!0}:{approved:!1,message:"the user declined"}}getSandboxStatus(){return this._shellSandbox?.status()}get backgroundProcesses(){return this._backgroundProcesses}async _getRequiredRequestAuth(e,t){let s;try{s=await this._modelRuntime.getAuth(e,{signal:t})}catch(i){const o=i instanceof Error?i.cause:void 0;throw o instanceof Error&&o.message==="authHeader requires a resolved API key"?new Error(F(e.provider)):i}if(s&&(s.auth.apiKey||s.auth.headers))return{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:V(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(F(e.provider))}async _getSummarizationRequestAuth(e,t){if(this.agent.streamFunction===le)return this._getRequiredRequestAuth(e,t);try{const s=await this._modelRuntime.getAuth(e,{signal:t});return s?{model:s.auth.baseUrl?{...e,baseUrl:s.auth.baseUrl}:e,apiKey:s.auth.apiKey,headers:V(s.auth.headers),env:s.env}:{model:e}}catch(s){if(t?.aborted)throw s;return{model:e}}}_installAgentToolHooks(){this.agent.beforeToolCall=async({toolCall:e,args:t})=>{const s=t??{},n=Ue({toolName:e.name,input:s,cwd:this._cwd},{rules:this._permissionRules,readGuard:this._readGuard});if(n?.behavior==="deny")return{block:!0,reason:n.reason};const i=this._extensionRunner;let o;if(i.hasHandlers("tool_call"))try{o=await i.emitToolCall({type:"tool_call",toolName:e.name,toolCallId:e.id,input:s})}catch(r){throw r instanceof Error?r:new Error(`Extension failed, blocking execution: ${String(r)}`)}if(o?.block)return o;if(n?.behavior==="ask"){const r=await this._askPermission({toolCallId:e.id,toolName:e.name,input:s,cwd:this._cwd,rule:n.rule,source:n.source});if(!r.approved)return{block:!0,reason:`Not approved (permission rule ${n.rule} asks first)${r.message?`: ${r.message}`:"."}`}}return o},this.agent.afterToolCall=async({toolCall:e,args:t,result:s,isError:n})=>{const i=this._extensionRunner,o=i.hasHandlers("tool_result")?await i.emitToolResult({type:"tool_result",toolName:e.name,toolCallId:e.id,input:t,content:s.content,details:s.details,isError:n,usage:s.usage}):void 0,r=o?.content??s.content??[],a=this.model?.inputLimits?.images?.resize,l=await pe(r,{autoResizeImages:this.settingsManager.getImageAutoResize(),...a?{resizeOptions:a}:{}});if(!(!o&&l===r))return{content:l,details:o?.details,isError:o?.isError??n,usage:o?.usage}}}async _compactBeforeNextAssistantResponse(e){const t=this.model,s=this.settingsManager.getCompactionSettings(t),n=this.sessionManager.buildSessionProjection();return!t||t.contextWindow<=0||!H(k(n,this.sessionManager.getBranch()).tokens,t.contextWindow,s)?{...e,messages:n.messages}:(await this._runAutoCompaction("threshold",!1),{...e,messages:this.sessionManager.buildSessionProjection().messages})}_installAgentRequestProjection(){const e=this.agent.prepareRequest;this.agent.prepareRequest=async(t,s)=>{const n={...t.context,messages:this.sessionManager.buildSessionProjection().messages,tools:this.agent.state.tools.slice()},i=await e?.({...t,context:n,model:this.agent.state.model,thinkingLevel:this.agent.state.thinkingLevel},s);return{...i,context:i?.context??n,model:i?.model??this.agent.state.model,thinkingLevel:i?.thinkingLevel??this.agent.state.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(o=>{const r=this._findPersistedMessageEntryId(o);return r?[r]:[]}),i=await this._extensionRunner.emitBoundary({type:"turn_end",turnIndex:this._turnIndex,message:e,toolResults:t,messageEntryId:s,toolResultEntryIds:n,outcome:this._lastActivityOutcome},o=>this._buildBoundaryContext(o,"turn_end"));return this._commitBoundaryDrafts(i.entries),i.continue&&!this._buildBoundaryContext([],"turn_end").canContinue?(this._reportInvalidBoundaryContinuation("turn_end"),!1):i.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),i=await e?.(t,s);if(i?.action==="end")return i;if(n||i?.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,messages:this.sessionManager.buildSessionProjection().messages}),i=await e?.({...t,context:n},s),o=i?.context??n,r=this._runSystemPromptOptions??this._baseSystemPromptOptions,a=Q({...r,selectedTools:this.getActiveToolNames(),toolSnippets:{...this._baseSystemPromptOptions.toolSnippets,...r.toolSnippets},toolGuidelines:{...this._baseSystemPromptOptions.toolGuidelines,...r.toolGuidelines}}),l=this._preparePromptAndToolLoadout(a,o.messages);return this._runSystemPromptOptions=a,{...i,context:{...o,tools:this.agent.state.tools.slice()},messages:l?[...i?.messages??[],l]:i?.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 i;switch(n.type){case"custom":i=e.appendCustomEntry(n.customType,n.data);break;case"custom_message":i=e.appendCustomMessageEntry(n.customType,n.content,n.display,n.details);break;case"context_edit":i=e.appendContextEdit(n.targetId,n.replacement);break;case"compaction":{const r=k(e.buildSessionProjection(),e.getBranch()).tokens;i=e.appendCompaction(n.summary,n.firstKeptEntryId,r,n.details,!0,n.usage);break}}const o=e.getEntry(i);o&&s.push(o)}return s}_createBoundaryPreviewManager(e){const t=this.sessionManager.getHeader();if(!t)throw new Error("Session header is missing");const s=Ve.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(),i=Ie(s.messages),o=i[i.length-1]?.role,a=i.some(u=>u.role!=="system")&&o!=="assistant",l=this._pendingCustomMessages.length>0;return{contextEntries:s.entries,contextMessages:s.messages,llmMessages:i,pendingMessages:n,canContinue:a||l||(t==="turn_end"?this.agent.hasQueuedMessages():o==="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{await this._extensionRunner.emit({type:"agent_settled"}),this._emit({type:"agent_settled"})}finally{this._isEmittingAgentSettled=!1}const e=this._deferredSettledActions.splice(0);if(e.length>0){try{for(const t of e)await t()}finally{this._resolveIdleWaitIfIdle()}return}this._resolveIdleWaitIfIdle()}_handleAgentEvent=c(async e=>{if(e.type==="message_start"&&e.message.role==="user"){this._overflowRecoveryAttempted=!1;const t=E(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=Ce(t);if(s!==t){e.message=s;const n=this.agent.state.messages;for(let i=n.length-1;i>=0;i--)if(n[i]===t){n[i]=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 o of[...this.sessionManager.getBranch()].reverse())if(o.type==="message"&&o.message===e)return o.id;const s=this.agent.state.messages.indexOf(e);if(s<0)return;const n=this.sessionManager.buildSessionProjection();let i=0;for(const o of n.entries)for(let r=0;r<o.messages.length;r++){if(i===s)return this._entryIdsByMessage.set(e,o.sourceEntry.id),o.sourceEntry.id;i++}}_omitRecoveryAttempt(e,t=[]){const s=[e,...t],n=s.map(o=>this._findPersistedMessageEntryId(o));if(s.some((o,r)=>n[r]===void 0&&this.agent.state.messages.includes(o)))throw new Error("Cannot persist recovery omission because a projected message has no source entry");for(const o of n){if(!o)continue;const r=this.sessionManager.appendContextEdit(o,null),a=this.sessionManager.getEntry(r);a&&this._emit({type:"entry_appended",entry:a})}this._refreshFinalizedContext()}_findLastAssistantMessage(){const e=this.agent.state.messages;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s.role==="assistant")return s}}_replaceMessageInPlace(e,t){if(e===t)return;const s=e;for(const n of Object.keys(s))delete s[n];Object.assign(s,t)}async _emitExtensionEvent(e){if(e.type==="agent_start")this._turnIndex=0,await this._extensionRunner.emit({type:"agent_start"});else if(e.type==="agent_end")await this._extensionRunner.emit({type:"agent_end",messages:e.messages});else if(e.type==="turn_start"){const t={type:"turn_start",turnIndex:this._turnIndex,timestamp:Date.now()};await this._extensionRunner.emit(t)}else if(e.type==="turn_end")e.message.role==="assistant"&&!this._boundaryDispatchedMessages.delete(e.message)&&await this._dispatchTurnEndBoundary(e.message,e.toolResults),this._turnIndex++;else if(e.type==="message_start"){const t={type:"message_start",message:e.message};await this._extensionRunner.emit(t)}else if(e.type==="message_update"){const t={type:"message_update",message:e.message,assistantMessageEvent:e.assistantMessageEvent};await this._extensionRunner.emit(t)}else if(e.type==="message_end"){const t={type:"message_end",message:e.message},s=await this._extensionRunner.emitMessageEnd(t);if(s){const n=(s.role==="user"||s.role==="assistant"||s.role==="toolResult"||s.role==="custom")&&s.content==null?{...s,content:[]}:s;this._replaceMessageInPlace(e.message,n)}}else if(e.type==="tool_execution_start"){const t={type:"tool_execution_start",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_update"){const t={type:"tool_execution_update",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,partialResult:e.partialResult};await this._extensionRunner.emit(t)}else if(e.type==="tool_execution_end"){const t={type:"tool_execution_end",toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError};await this._extensionRunner.emit(t)}}subscribe(e){return this._eventListeners.push(e),()=>{const t=this._eventListeners.indexOf(e);t!==-1&&this._eventListeners.splice(t,1)}}_disconnectFromAgent(){this._unsubscribeAgent&&(this._unsubscribeAgent(),this._unsubscribeAgent=void 0)}dispose(){try{this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this.abortBash(),this.agent.abort()}catch{}this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."),this._disconnectFromAgent(),this._eventListeners=[];const e=this._shellSandbox,t=this._sandboxScratch;this._sandboxScratch=void 0,this._backgroundProcesses.stopAll().finally(()=>(t&&Z(t,{recursive:!0,force:!0}),e?.dispose())),this._cacheWarmer&&(this._cacheWarmer.onWarmed=void 0,this._cacheWarmer.cancel()),ne(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 isStreaming(){return this._isAgentRunActive}get isIdle(){return!this._isAgentRunActive&&!this.isCompacting}get systemPrompt(){return Je(this._runSystemPromptOptions??this._baseSystemPromptOptions)}get retryAttempt(){return this._retryAttempt}getActiveToolNames(){return this.agent.state.tools.map(e=>e.name)}isToolAllowed(e){return(!this._allowedToolNames||this._allowedToolNames.has(e))&&!this._excludedToolNames?.has(e)}getToolDenylist(){return this._excludedToolNames&&this._excludedToolNames.size>0?[...this._excludedToolNames]:void 0}getToolAllowlist(){if(this._allowedToolNames)return[...this._allowedToolNames].filter(e=>!this._excludedToolNames?.has(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,sourceInfo:t}))}getToolDefinition(e){return this._toolDefinitions.get(e)?.definition}setActiveToolsByName(e){const t=[],s=[];for(const n of e){const i=this._toolRegistry.get(n);i&&(t.push(i),s.push(n))}this.agent.state.tools=t,this._rebuildSystemPrompt(s)}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 u=this._toolPromptSnippets.get(l);u&&(s[l]=u)}const n=this._resourceLoader.getSystemPrompt(),i=this._resourceLoader.getAppendSystemPrompt(),o=i.length>0?i.join(`
|
|
3
3
|
|
|
4
|
-
`):"",r=this._resourceLoader.getSkills().skills,
|
|
4
|
+
`):"",r=this._resourceLoader.getSkills().skills,a=this._resourceLoader.getAgentsFiles().agentsFiles;this._baseSystemPromptOptions=Q({cwd:this._cwd,skills:r,contextFiles:a,customPrompt:n,appendSystemPrompt:o,selectedTools:t,toolSnippets:s,toolGuidelines:Object.fromEntries(this._toolPromptGuidelines)})}_preparePromptAndToolLoadout(e,t=this.agent.state.messages){e.selectedTools=[...new Set(e.selectedTools)].filter(n=>this._toolRegistry.has(n)),this.agent.state.tools=e.selectedTools.flatMap(n=>{const i=this._toolRegistry.get(n);return i?[i]:[]});const s=Ye(B(t)?.sections??{},Xe(e));return s?{role:"system",content:"",sections:s,timestamp:Date.now()}:void 0}_installAgentForcedPromptProjection(){const e=this.agent.transformContext;this.agent.transformContext=async(t,s)=>{const n=e?await e(t,s):t,i=this._runSystemPromptOptions?.forceSystemPrompt;if(i===void 0)return n;const o=B(n);return[{role:"system",content:i,...o?.toolsAdded?{toolsAdded:o.toolsAdded}:{},timestamp:o?.timestamp??Date.now()},...n.filter(a=>a.role!=="system")]}}_restoreToolsFromTranscript(){const e=B(this.sessionManager.buildSessionContext().messages);if(!e)return;const t=(e.toolsAdded??[]).map(s=>s.name).filter(s=>this._toolRegistry.has(s));this.agent.state.tools=t.flatMap(s=>{const n=this._toolRegistry.get(s);return n?[n]:[]}),this._rebuildSystemPrompt(t)}async _runAgentPrompt(e){this._agentRunAbortRequested=!1,this._isAgentRunActive=!0;try{for(await this.agent.prompt(e);!this._agentRunAbortRequested;){if(await this._handlePostAgentRun()){if(this._agentRunAbortRequested)break;await this.agent.continue();continue}if(this._agentRunAbortRequested||!await this._runBeforeSettleBoundary()||this._agentRunAbortRequested)break;await this.agent.continue()}}finally{this._agentRunAbortRequested&&this._finishCancelledRetry(),this._runSystemPromptOptions=void 0,this._flushPendingBashMessages(),this._flushPendingCustomMessages(),await this._emitAgentSettled()}}async _handlePostAgentRun(){const e=this._lastAssistantMessage,t=this._lastAssistantToolResults;return this._lastAssistantMessage=void 0,this._lastAssistantToolResults=[],this._agentRunAbortRequested?(this._finishCancelledRetry(),!1):e?this._isRetryableError(e)&&await this._prepareRetry(e)?(this._agentRunAbortRequested&&this._finishCancelledRetry(),!this._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 i=await this._extensionRunner.emitInput(e,t,s,n);if(i.action!=="handled")return i.action==="transform"?{text:i.text,images:i.images??t}:{text:e,images:t}}async _normalizePromptImages(e){if(!e)return{images:[],hints:[]};const t=[],s=[];for(const n of e){const i=await me(Buffer.from(n.data,"base64"),n.mimeType,{autoResizeImages:this.settingsManager.getImageAutoResize(),resizeOptions:this.model?.inputLimits?.images?.resize});if(!i.ok){s.push(i.message);continue}t.push({type:"image",data:i.data,mimeType:i.mimeType}),s.push(...i.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,i=t?.preflightResult,o=c(()=>this._promptAbortGeneration===s?!1:(i?.(!1),!0),"abortedBeforeRun");let r;try{if(n&&e.startsWith("/")&&await this._tryExecuteExtensionCommand(e,()=>i?.(!0)))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(o())return;if(!a){i?.(!0);return}const{text:l,images:u}=a;let h=l;if(n&&(h=this._expandSkillCommand(h),h=G(h,[...this.promptTemplates])),this.isStreaming){if(!t?.streamingBehavior)throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");t.streamingBehavior==="followUp"?await this._queueFollowUp(h,u):await this._queueSteer(h,u),i?.(!0);return}if(this._flushPendingBashMessages(),this._flushPendingCustomMessages(),!this.model)throw new Error(z());const m=this._modelRuntime.hasConfiguredAuth(this.model.provider)||await this._modelRuntime.checkAuth(this.model.provider)!==void 0;if(o())return;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(F(this.model.provider));const p=this._findLastAssistantMessage();if(p&&(await this._checkCompaction(p,!1),o()))return;const d=this._baseSystemPromptOptions.selectedTools,g=await this._extensionRunner.emitBeforeAgentStart(h,u,this._baseSystemPromptOptions);if(o())return;g.systemPromptOptions.selectedTools.length!==d.length||g.systemPromptOptions.selectedTools.some((b,_)=>b!==d[_])||(g.systemPromptOptions.selectedTools=this.getActiveToolNames());const w=await this._normalizePromptImages(u);if(o())return;const A=w.hints.length>0?`${h}
|
|
5
5
|
|
|
6
|
-
${
|
|
7
|
-
`)}`:
|
|
6
|
+
${w.hints.join(`
|
|
7
|
+
`)}`:h;r=[];const f=[{type:"text",text:A}];f.push(...w.images),r.push({role:"user",content:f,timestamp:Date.now()});for(const b of this._pendingNextTurnMessages)r.push(b);this._pendingNextTurnMessages=[];for(const b of g.messages)r.push({role:"custom",customType:b.customType,content:b.content??[],display:b.display,details:b.details,timestamp:Date.now()});const R=this._preparePromptAndToolLoadout(g.systemPromptOptions);this._runSystemPromptOptions=g.systemPromptOptions,R&&r.unshift(R)}catch(a){throw i?.(!1),a}r&&(i?.(!0),await this._runAgentPrompt(r))}async _tryExecuteExtensionCommand(e,t){const s=e.indexOf(" "),n=s===-1?e.slice(1):e.slice(1,s),i=s===-1?"":e.slice(s+1),o=this._extensionRunner.getCommand(n);if(!o)return!1;const r=this._extensionRunner.createCommandContext();t?.(),this._emit({type:"extension_command_start",command:n});try{return await o.handler(i,r),this._emit({type:"extension_command_end",command:n}),!0}catch(a){const l=a instanceof Error?a.message:String(a);return this._extensionRunner.emitError({extensionPath:`command:${n}`,event:"command",error:l}),this._emit({type:"extension_command_end",command:n,error:l}),!0}}_expandSkillCommand(e){if(!e.startsWith("/skill:"))return e;const t=e.indexOf(" "),s=t===-1?e.slice(7):e.slice(7,t),n=t===-1?"":e.slice(t+1).trim(),i=this.resourceLoader.getSkills().skills.find(o=>o.name===s);if(!i)return e;try{const o=Y(i.filePath,"utf-8"),r=ue(o).trim(),a=`<skill name="${i.name}" location="${i.filePath}">
|
|
8
8
|
References are relative to ${i.baseDir}.
|
|
9
9
|
|
|
10
10
|
${r}
|
|
11
|
-
</skill>`;return n?`${
|
|
11
|
+
</skill>`;return n?`${a}
|
|
12
12
|
|
|
13
|
-
${n}`:
|
|
14
|
-
`),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:t?.expandPromptTemplates??!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this._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){P(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(!Le(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Be([...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=>P(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(h=>`${h.provider}\0${h.id}`)),n=this._scopedModels.filter(h=>s.has(`${h.model.provider}\0${h.model.id}`));if(n.length<=1)return;const i=this.model;let o=n.findIndex(h=>P(h.model,i));o===-1&&(o=0);const r=n.length,l=e==="forward"?(o+1)%r:(o-1+r)%r,a=n[l],m=this._getThinkingLevelForModelSwitch(a.model,a.thinkingLevel);return this.agent.state.model=a.model,this.sessionManager.appendModelChange(a.model.provider,a.model.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(a.model.provider,a.model.id),this._addPersistedDefaultToNonEmptyScope(a.model)),this.setThinkingLevel(m),await this._emitModelSelect(a.model,i,"cycle"),{model:a.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 i=s.findIndex(m=>P(m,n));i===-1&&(i=0);const o=s.length,r=e==="forward"?(i+1)%o:(i-1+o)%o,l=s[r],a=this._getThinkingLevelForModelSwitch(l);return this.agent.state.model=l,this.sessionManager.appendModelChange(l.provider,l.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(l.provider,l.id),this._addPersistedDefaultToNonEmptyScope(l)),this.setThinkingLevel(a),await this._emitModelSelect(l,n,"cycle"),{model:l,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e,t={}){const s=this.getAvailableThinkingLevels(),n=s.includes(e)?e:this._clampThinkingLevel(e,s),i=this.agent.state.thinkingLevel,o=n!==i;this.agent.state.thinkingLevel=n,t.persist&&this.settingsManager.setDefaultThinkingLevel(e),o&&(this.sessionManager.appendThinkingLevelChange(n),this._emit({type:"thinking_level_changed",level:n}),this._extensionRunner.emit({type:"thinking_level_select",level:n,previousLevel:i}))}cycleThinkingLevel(e={}){if(!this.supportsThinking())return;const t=this.getAvailableThinkingLevels(),n=(t.indexOf(this.thinkingLevel)+1)%t.length,i=t[n];return this.setThinkingLevel(i,e),i}getAvailableThinkingLevels(){return this.model?ie(this.model):[...Se]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return D(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??Ae}_clampThinkingLevel(e,t){return this.model?D(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,i,o,r,l){return we(e,t,s,n,i,o,this.thinkingLevel,this.agent.streamFunction,r,this.settingsManager.getRetrySettings(),this._summarizationRetryCallbacks({source:"compaction",reason:l}),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(z());const i=this.settingsManager.getCompactionSettings(n),{model:o,apiKey:r,headers:l,env:a}=await this._getSummarizationRequestAuth(n,this._compactionAbortController.signal),m=this.sessionManager.getBranch(),h=q(m,i);if(!h)throw m[m.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let u;if(this._extensionRunner.hasHandlers("session_before_compact")){const y=await this._extensionRunner.emit({type:"session_before_compact",preparation:h,branchEntries:m,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(y?.cancel)throw s=!0,new Error("Compaction cancelled");y?.compaction&&(u=y.compaction,t=!0)}let g,d,f,x,b;if(u)g=u.summary,d=u.firstKeptEntryId,f=u.tokensBefore,x=u.usage,b=u.details;else{const y=await this._runDefaultCompaction(h,o,r,l,e,this._compactionAbortController.signal,a,"manual");g=y.summary,d=y.firstKeptEntryId,f=y.tokensBefore,x=y.usage,b=y.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(g,d,f,b,t,x);const M=this.sessionManager.getEntries();this._refreshFinalizedContext();const p=J(this.sessionManager.buildSessionProjection().messages),R=M.find(y=>y.type==="compaction"&&y.summary===g);this._extensionRunner&&R&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:R,fromExtension:t,reason:"manual",willRetry:!1});const S={summary:g,firstKeptEntryId:d,tokensBefore:f,estimatedTokensAfter:p,usage:x,details:b};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:S,aborted:!1,willRetry:!1}),S}catch(n){const i=n instanceof Error?n.message:String(n),o=this._compactionAbortController.signal.aborted||s,r=o?void 0:`Compaction failed: ${i}`;throw this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:o,willRetry:!1,errorMessage:r}),await this._emitSessionCompactFailed({reason:"manual",errorMessage:r,aborted:o,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 i=this.model?.contextWindow??0,o=this.model&&e.provider===this.model.provider&&e.model===this.model.id,r=K(this.sessionManager.getBranch());if(r!==null&&e.timestamp<=new Date(r.timestamp).getTime())return!1;const a=this.sessionManager.buildSessionProjection(),m=this._findPersistedMessageEntryId(e),h=m===void 0||a.entries.some(w=>w.sourceEntry.id===m&&w.messages.some(C=>C.role==="assistant")),u=this.sessionManager.getBranch(),g=m?u.findIndex(w=>w.id===m):-1,d=g>=0?u.slice(g+1):[],f=d.some(w=>w.type==="context_edit"),x=d.filter(w=>w.type==="context_edit"&&w.targetId===m).at(-1),b=m===void 0||!d.some(w=>w.type==="compaction")&&x?.replacement!==null,M=h&&!f,p=e.stopReason==="error"&&N(e),R=o&&(p&&b||M&&N(e,i)),S=o&&h&&oe(e,this.model?this.settingsManager.getOutputTokenLimit(this.model.maxTokens):0);if(R||S){const w=e.stopReason!=="stop";if(!w)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const C=R?"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}return this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s),await this._runAutoCompaction("overflow",w)}let y;const v=a,T=v.entries.some(w=>w.sourceEntry.type==="context_edit"),_=e.usage?j(e.usage):0;if(T)y=k(v,u).tokens;else if(e.stopReason==="error"||_===0){const w=this.agent.state.messages,C=be(w);if(C.lastUsageIndex!==null){const U=w[C.lastUsageIndex];if(r&&U.role==="assistant"&&U.timestamp<=new Date(r.timestamp).getTime())return!1}y=C.tokens}else y=_;return H(y,i,n)?await this._runAutoCompaction("threshold",!1):!1}async _runAutoCompaction(e,t){const s=this.model,n=this.settingsManager.getCompactionSettings(s);let i,o=!1,r=!1,l=!1;try{if(!s)return!1;const a=this.sessionManager.getBranch(),m=q(a,n);if(!m)return!1;i=new AbortController,this._autoCompactionAbortController=i,o=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();const{model:h,apiKey:u,headers:g,env:d}=await this._getSummarizationRequestAuth(s,i.signal);i.signal.throwIfAborted();let f;if(this._extensionRunner.hasHandlers("session_before_compact")){const _=await this._extensionRunner.emit({type:"session_before_compact",preparation:m,branchEntries:a,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(_?.cancel)throw l=!0,new Error("Compaction cancelled");_?.compaction&&(f=_.compaction,r=!0)}i.signal.throwIfAborted();let x,b,M,p,R;if(f)x=f.summary,b=f.firstKeptEntryId,M=f.tokensBefore,p=f.usage,R=f.details;else{const _=await this._runDefaultCompaction(m,h,u,g,void 0,i.signal,d,e);x=_.summary,b=_.firstKeptEntryId,M=_.tokensBefore,p=_.usage,R=_.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(x,b,M,R,r,p);const S=this.sessionManager.getEntries();this._refreshFinalizedContext();const y=J(this.sessionManager.buildSessionProjection().messages),v=S.find(_=>_.type==="compaction"&&_.summary===x);this._extensionRunner&&v&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:v,fromExtension:r,reason:e,willRetry:t});const T={summary:x,firstKeptEntryId:b,tokensBefore:M,estimatedTokensAfter:y,usage:p,details:R};return this._emit({type:"compaction_end",reason:e,result:T,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(a){const m=a instanceof Error?a.message:"compaction failed",h=i?.signal.aborted===!0||l;if(o){const u=h?void 0:e==="overflow"?`Context overflow recovery failed: ${m}`:`Auto-compaction failed: ${m}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:h,willRetry:!1,errorMessage:u}),await this._emitSessionCompactFailed({reason:e,errorMessage:u,aborted:h,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(),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 i={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(i),this._rebuildSystemPrompt(this.getActiveToolNames())}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=t.extensionPath.startsWith("<")?void 0:te(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return e.startsWith("<")?`extension:${e.replace(/[<>]/g,"")}`:`extension:${ee(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRuntime.getModel(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=c(()=>{const s=e.getRegisteredCommands().map(o=>({name:o.invocationName,description:o.description,source:"extension",sourceInfo:o.sourceInfo})),n=this.promptTemplates.map(o=>({name:o.name,description:o.description,source:"prompt",sourceInfo:o.sourceInfo})),i=this._resourceLoader.getSkills().skills.map(o=>({name:`skill:${o.name}`,description:o.description,source:"skill",sourceInfo:o.sourceInfo}));return[...s,...n,...i]},"getCommands");e.bindCore({sendMessage:c((s,n)=>{this.sendCustomMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:i instanceof Error?i.message:String(i)})})},"sendMessage"),sendUserMessage:c((s,n)=>{this.sendUserMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:i instanceof Error?i.message:String(i)})})},"sendUserMessage"),appendEntry:c((s,n)=>{const i=this.sessionManager.appendCustomEntry(s,n),o=this.sessionManager.getEntry(i);o&&this._emit({type:"entry_appended",entry:o})},"appendEntry"),setSessionName:c(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:c(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:c((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:c(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:c(()=>this.getAllTools(),"getAllTools"),setActiveTools:c(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:c(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:c(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:c(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:c(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:c(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:c(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:c(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:c(()=>this.model,"getModel"),getScopedModels:c(()=>this._scopedModels,"getScopedModels"),isIdle:c(()=>this.isIdle,"isIdle"),isProjectTrusted:c(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:c(()=>this.agent.signal,"getSignal"),abort:c(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:c(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:c(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:c(()=>this.getContextUsage(),"getContextUsage"),compact:c(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const i=n instanceof Error?n:new Error(String(n));s?.onError?.(i)}})()},"compact"),getSystemPrompt:c(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:c(()=>this._baseSystemPromptOptions,"getSystemPromptOptions")},{registerProvider:c((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:c(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:c(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider")})}_refreshToolRegistry(e){const t=new Set(this._toolRegistry.keys()),s=this.getActiveToolNames(),n=this._allowedToolNames,i=c(d=>this.isToolAllowed(d),"isAllowedTool"),r=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:O(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>i(d.definition.name)),l=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>i(d)).map(([d,f])=>[d,{definition:f,sourceInfo:O(`<builtin:${d}>`,{source:"builtin"})}]));for(const d of r)l.set(d.definition.name,{definition:d.definition,sourceInfo:d.sourceInfo});this._toolDefinitions=l,this._toolPromptSnippets=new Map(Array.from(l.values()).map(({definition:d})=>{const f=this._normalizePromptSnippet(d.promptSnippet);return f?[d.name,f]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(l.values()).map(({definition:d})=>{const f=this._normalizePromptGuidelines(d.promptGuidelines);return f.length>0?[d.name,f]:void 0}).filter(d=>d!==void 0));const a=this._extensionRunner,m=$(r,a),h=$(Array.from(this._baseToolDefinitions.values()).filter(d=>i(d.name)).map(d=>({definition:d,sourceInfo:O(`<builtin:${d.name}>`,{source:"builtin"})})),a),u=new Map(h.map(d=>[d.name,d]));for(const d of m)u.set(d.name,d);this._toolRegistry=u;const g=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>i(d));if(n)for(const d of this._toolRegistry.keys())n.has(d)&&g.push(d);else if(e?.includeAllExtensionTools)for(const d of m)g.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())t.has(d)||g.push(d);this.setActiveToolsByName([...new Set(g)])}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();de(this.settingsManager.getShellEnvironmentPolicy());const i=je({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"}),o=new Ge({policy:i,onEscalation:this._sandboxOptions.onEscalation,onEvent:c(u=>this._emit(u),"onEvent"),scratchDir:c(()=>(this._sandboxScratch??=$e(),this._sandboxScratch),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=o,r?.dispose(),Ke(o),process.env[qe]=He(i),this._permissionRules=Ne(this.settingsManager.getPermissionRuleSources()),this._readGuard=Oe({cwd:this._cwd,rules:this._permissionRules,...i.level!=="off"?{protectedReads:ze(i,this._cwd).denyRead}:{}}),We(this._readGuard);const l=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([u,g])=>[u,st(g)])):et(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:o}});this._baseToolDefinitions=new Map(Object.entries(l).map(([u,g])=>[u,g])),this._baseToolsOverride||this._baseToolDefinitions.set("process",tt(this._cwd,this._backgroundProcesses,{sandboxed:o.active}));const a=this._resourceLoader.getExtensions();if(e.flagValues)for(const[u,g]of e.flagValues)a.runtime.flagValues.set(u,g);this._extensionRunner=new Ee(a.extensions,a.runtime,this._cwd,this.sessionManager,new ke(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const m=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],h=e.activeToolNames??m;this._refreshToolRegistry({activeToolNames:h,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await Pe(t,{type:"session_shutdown",reason:"reload"}),t.invalidate(),await this.settingsManager.reload(),this.syncQueueModesFromSettings(),ae(),await this._resourceLoader.reload(),this._buildRuntime({activeToolNames:this.getActiveToolNames(),flagValues:s,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await e?.beforeSessionStart?.(),await this._extensionRunner.emit({type:"session_start",reason:"reload"}),await this.extendResourcesFromExtensions("reload"))}_isRetryableError(e){return N(e,this.model?.contextWindow??0)?!1:re(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:c((t,s,n,i)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:i})},"onRetryScheduled"),onRetryAttemptStart:c(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:c(()=>{this._emit({type:"summarization_retry_finished"})},"onRetryFinished")}}_finishCancelledRetry(){if(this._retryAttempt===0)return;const e=this._retryAttempt;this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:e,finalError:"Retry cancelled"})}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=se(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await ge(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 i=this.settingsManager.getShellCommandPrefix(),o=this.settingsManager.getShellPath(),r=i?`${i}
|
|
15
|
-
${e}`:e;try{const
|
|
13
|
+
${n}`:a}catch(o){return this._extensionRunner.emitError({extensionPath:i.filePath,event:"skill_expansion",error:o instanceof Error?o.message:String(o)}),e}}async _queueUserInput(e,t,s,n){e.startsWith("/")&&this._throwIfExtensionCommand(e);const i=await this._runInputHandlers(e,t,n,this.isStreaming?s:void 0);if(!i)return;let o=this._expandSkillCommand(i.text);o=G(o,[...this.promptTemplates]),s==="steer"?await this._queueSteer(o,i.images):await this._queueFollowUp(o,i.images)}async steer(e,t,s){await this._queueUserInput(e,t,"steer",s?.source??"interactive")}async followUp(e,t,s){await this._queueUserInput(e,t,"followUp",s?.source??"interactive")}async _queueSteer(e,t){this._steeringMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.steer({role:"user",content:s,timestamp:Date.now()})}async _queueFollowUp(e,t){this._followUpMessages.push(e),this._emitQueueUpdate();const s=[{type:"text",text:e}];t&&s.push(...t),this.agent.followUp({role:"user",content:s,timestamp:Date.now()})}_throwIfExtensionCommand(e){const t=e.indexOf(" "),s=t===-1?e.slice(1):e.slice(1,t);if(this._extensionRunner.getCommand(s))throw new Error(`Extension command "/${s}" cannot be queued. Use prompt() or execute the command when not streaming.`)}async sendCustomMessage(e,t){const s={role:"custom",customType:e.customType,content:e.content??[],display:e.display,details:e.details,timestamp:Date.now()};if(t?.deliverAs==="nextTurn")this._pendingNextTurnMessages.push(s);else if(this.isStreaming&&t?.triggerTurn!==!1)t?.deliverAs==="followUp"?this.agent.followUp(s):this.agent.steer(s);else if(t?.triggerTurn){if(this._isEmittingAgentSettled){this._deferredSettledActions.push(async()=>await this._runAgentPrompt(s));return}await this._runAgentPrompt(s)}else this.isStreaming?this._pendingCustomMessages.push(s):this._appendCustomMessage(s)}_appendCustomMessage(e){this.sessionManager.appendCustomMessageEntry(e.customType,e.content,e.display,e.details),this._refreshFinalizedContext(),this._emit({type:"message_start",message:e}),this._emit({type:"message_end",message:e})}_flushPendingCustomMessages(){if(this._pendingCustomMessages.length===0)return;const e=this._pendingCustomMessages;this._pendingCustomMessages=[];for(const t of e)this._appendCustomMessage(t)}async sendUserMessage(e,t){let s,n;if(typeof e=="string")s=e;else{const i=[];n=[];for(const o of e)o.type==="text"?i.push(o.text):n.push(o);s=i.join(`
|
|
14
|
+
`),n.length===0&&(n=void 0)}await this.prompt(s,{expandPromptTemplates:t?.expandPromptTemplates??!1,streamingBehavior:t?.deliverAs,images:n,source:"extension"})}clearQueue(){const e=[...this._steeringMessages],t=[...this._followUpMessages];return this._steeringMessages=[],this._followUpMessages=[],this.agent.clearAllQueues(),this._emitQueueUpdate(),{steering:e,followUp:t}}get pendingMessageCount(){return this._steeringMessages.length+this._followUpMessages.length}getSteeringMessages(){return this._steeringMessages}getFollowUpMessages(){return this._followUpMessages}get resourceLoader(){return this._resourceLoader}async abort(){this._promptAbortGeneration++,this._isAgentRunActive&&(this._agentRunAbortRequested=!0),this.abortRetry(),this.abortCompaction(),this.abortBranchSummary(),this._isBeforeSettle&&(this._abortDuringBeforeSettle=!0),this.agent.abort(),await this.waitForIdle()}async waitForIdle(){this.isIdle||await this._getIdleWaitPromise()}async emitProviderAuthenticated(e,t){await this._extensionRunner.emit({type:"provider_authenticated",providerId:e,authType:t})}async _emitModelSelect(e,t,s){P(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(!Le(this.model))return;try{await this._modelRuntime.refresh({allowNetwork:!1})}catch{}const t=Be([...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=>P(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(h=>`${h.provider}\0${h.id}`)),n=this._scopedModels.filter(h=>s.has(`${h.model.provider}\0${h.model.id}`));if(n.length<=1)return;const i=this.model;let o=n.findIndex(h=>P(h.model,i));o===-1&&(o=0);const r=n.length,a=e==="forward"?(o+1)%r:(o-1+r)%r,l=n[a],u=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(u),await this._emitModelSelect(l.model,i,"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 i=s.findIndex(u=>P(u,n));i===-1&&(i=0);const o=s.length,r=e==="forward"?(i+1)%o:(i-1+o)%o,a=s[r],l=this._getThinkingLevelForModelSwitch(a);return this.agent.state.model=a,this.sessionManager.appendModelChange(a.provider,a.id),t.persist&&(this.settingsManager.setDefaultModelAndProvider(a.provider,a.id),this._addPersistedDefaultToNonEmptyScope(a)),this.setThinkingLevel(l),await this._emitModelSelect(a,n,"cycle"),{model:a,thinkingLevel:this.thinkingLevel,isScoped:!1}}setThinkingLevel(e,t={}){const s=this.getAvailableThinkingLevels(),n=s.includes(e)?e:this._clampThinkingLevel(e,s),i=this.agent.state.thinkingLevel,o=n!==i;this.agent.state.thinkingLevel=n,t.persist&&this.settingsManager.setDefaultThinkingLevel(e),o&&(this.sessionManager.appendThinkingLevelChange(n),this._emit({type:"thinking_level_changed",level:n}),this._extensionRunner.emit({type:"thinking_level_select",level:n,previousLevel:i}))}cycleThinkingLevel(e={}){if(!this.supportsThinking())return;const t=this.getAvailableThinkingLevels(),n=(t.indexOf(this.thinkingLevel)+1)%t.length,i=t[n];return this.setThinkingLevel(i,e),i}getAvailableThinkingLevels(){return this.model?ie(this.model):[...Se]}supportsThinking(){return!!this.model?.reasoning}getThinkingLevelForModel(e){return D(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??Ae}_clampThinkingLevel(e,t){return this.model?D(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,i,o,r,a){return we(e,t,s,n,i,o,this.thinkingLevel,this.agent.streamFunction,r,this.settingsManager.getRetrySettings(),this._summarizationRetryCallbacks({source:"compaction",reason:a}),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(z());const i=this.settingsManager.getCompactionSettings(n),{model:o,apiKey:r,headers:a,env:l}=await this._getSummarizationRequestAuth(n,this._compactionAbortController.signal),u=this.sessionManager.getBranch(),h=q(u,i);if(!h)throw u[u.length-1]?.type==="compaction"?new Error("Already compacted"):new Error("Nothing to compact (session too small)");let m;if(this._extensionRunner.hasHandlers("session_before_compact")){const _=await this._extensionRunner.emit({type:"session_before_compact",preparation:h,branchEntries:u,customInstructions:e,reason:"manual",willRetry:!1,signal:this._compactionAbortController.signal});if(_?.cancel)throw s=!0,new Error("Compaction cancelled");_?.compaction&&(m=_.compaction,t=!0)}let p,d,g,x,w;if(m)p=m.summary,d=m.firstKeptEntryId,g=m.tokensBefore,x=m.usage,w=m.details;else{const _=await this._runDefaultCompaction(h,o,r,a,e,this._compactionAbortController.signal,l,"manual");p=_.summary,d=_.firstKeptEntryId,g=_.tokensBefore,x=_.usage,w=_.details}if(this._compactionAbortController.signal.aborted)throw new Error("Compaction cancelled");this.sessionManager.appendCompaction(p,d,g,w,t,x);const A=this.sessionManager.getEntries();this._refreshFinalizedContext();const f=J(this.sessionManager.buildSessionProjection().messages),R=A.find(_=>_.type==="compaction"&&_.summary===p);this._extensionRunner&&R&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:R,fromExtension:t,reason:"manual",willRetry:!1});const b={summary:p,firstKeptEntryId:d,tokensBefore:g,estimatedTokensAfter:f,usage:x,details:w};return this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:b,aborted:!1,willRetry:!1}),b}catch(n){const i=n instanceof Error?n.message:String(n),o=this._compactionAbortController.signal.aborted||s,r=o?void 0:`Compaction failed: ${i}`;throw this._clearManualCompactionState(),this._emit({type:"compaction_end",reason:"manual",result:void 0,aborted:o,willRetry:!1,errorMessage:r}),await this._emitSessionCompactFailed({reason:"manual",errorMessage:r,aborted:o,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 i=this.model?.contextWindow??0,o=this.model&&e.provider===this.model.provider&&e.model===this.model.id,r=K(this.sessionManager.getBranch());if(r!==null&&e.timestamp<=new Date(r.timestamp).getTime())return!1;const l=this.sessionManager.buildSessionProjection(),u=this._findPersistedMessageEntryId(e),h=u===void 0||l.entries.some(M=>M.sourceEntry.id===u&&M.messages.some(C=>C.role==="assistant")),m=this.sessionManager.getBranch(),p=u?m.findIndex(M=>M.id===u):-1,d=p>=0?m.slice(p+1):[],g=d.some(M=>M.type==="context_edit"),x=d.filter(M=>M.type==="context_edit"&&M.targetId===u).at(-1),w=u===void 0||!d.some(M=>M.type==="compaction")&&x?.replacement!==null,A=h&&!g,f=e.stopReason==="error"&&N(e),R=o&&(f&&w||A&&N(e,i)),b=o&&h&&oe(e,this.model?this.settingsManager.getOutputTokenLimit(this.model.maxTokens):0);if(R||b){const M=e.stopReason!=="stop";if(!M)return await this._runAutoCompaction("overflow",!1);if(this._overflowRecoveryAttempted){const C=R?"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}return this._overflowRecoveryAttempted=!0,this._omitRecoveryAttempt(e,s),await this._runAutoCompaction("overflow",M)}let _;const v=l,T=v.entries.some(M=>M.sourceEntry.type==="context_edit"),y=e.usage?j(e.usage):0;if(T)_=k(v,m).tokens;else if(e.stopReason==="error"||y===0){const M=this.agent.state.messages,C=be(M);if(C.lastUsageIndex!==null){const U=M[C.lastUsageIndex];if(r&&U.role==="assistant"&&U.timestamp<=new Date(r.timestamp).getTime())return!1}_=C.tokens}else _=y;return H(_,i,n)?await this._runAutoCompaction("threshold",!1):!1}async _runAutoCompaction(e,t){const s=this.model,n=this.settingsManager.getCompactionSettings(s);let i,o=!1,r=!1,a=!1;try{if(!s)return!1;const l=this.sessionManager.getBranch(),u=q(l,n);if(!u)return!1;i=new AbortController,this._autoCompactionAbortController=i,o=!0,this._emit({type:"compaction_start",reason:e}),i.signal.throwIfAborted();const{model:h,apiKey:m,headers:p,env:d}=await this._getSummarizationRequestAuth(s,i.signal);i.signal.throwIfAborted();let g;if(this._extensionRunner.hasHandlers("session_before_compact")){const y=await this._extensionRunner.emit({type:"session_before_compact",preparation:u,branchEntries:l,customInstructions:void 0,reason:e,willRetry:t,signal:i.signal});if(y?.cancel)throw a=!0,new Error("Compaction cancelled");y?.compaction&&(g=y.compaction,r=!0)}i.signal.throwIfAborted();let x,w,A,f,R;if(g)x=g.summary,w=g.firstKeptEntryId,A=g.tokensBefore,f=g.usage,R=g.details;else{const y=await this._runDefaultCompaction(u,h,m,p,void 0,i.signal,d,e);x=y.summary,w=y.firstKeptEntryId,A=y.tokensBefore,f=y.usage,R=y.details}i.signal.throwIfAborted(),this.sessionManager.appendCompaction(x,w,A,R,r,f);const b=this.sessionManager.getEntries();this._refreshFinalizedContext();const _=J(this.sessionManager.buildSessionProjection().messages),v=b.find(y=>y.type==="compaction"&&y.summary===x);this._extensionRunner&&v&&await this._extensionRunner.emit({type:"session_compact",compactionEntry:v,fromExtension:r,reason:e,willRetry:t});const T={summary:x,firstKeptEntryId:w,tokensBefore:A,estimatedTokensAfter:_,usage:f,details:R};return this._emit({type:"compaction_end",reason:e,result:T,aborted:!1,willRetry:t}),t?!0:this.agent.hasQueuedMessages()}catch(l){const u=l instanceof Error?l.message:"compaction failed",h=i?.signal.aborted===!0||a;if(o){const m=h?void 0:e==="overflow"?`Context overflow recovery failed: ${u}`:`Auto-compaction failed: ${u}`;this._emit({type:"compaction_end",reason:e,result:void 0,aborted:h,willRetry:!1,errorMessage:m}),await this._emitSessionCompactFailed({reason:e,errorMessage:m,aborted:h,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(),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 i={skillPaths:this.buildExtensionResourcePaths(t),promptPaths:this.buildExtensionResourcePaths(s),themePaths:this.buildExtensionResourcePaths(n)};this._resourceLoader.extendResources(i),this._rebuildSystemPrompt(this.getActiveToolNames())}buildExtensionResourcePaths(e){return e.map(t=>{const s=this.getExtensionSourceLabel(t.extensionPath),n=t.extensionPath.startsWith("<")?void 0:te(t.extensionPath);return{path:t.path,metadata:{source:s,scope:"temporary",origin:"top-level",baseDir:n}}})}getExtensionSourceLabel(e){return e.startsWith("<")?`extension:${e.replace(/[<>]/g,"")}`:`extension:${ee(e).replace(/\.(ts|js)$/,"")}`}_applyExtensionBindings(e){e.setUIContext(this._extensionUIContext,this._extensionMode),e.bindCommandContext(this._extensionCommandContextActions),this._extensionErrorUnsubscriber?.(),this._extensionErrorUnsubscriber=this._extensionErrorListener?e.onError(this._extensionErrorListener):void 0}_refreshCurrentModelFromRegistry(){const e=this.model;if(!e)return;const t=this._modelRuntime.getModel(e.provider,e.id);!t||t===e||(this.agent.state.model=t)}_bindExtensionCore(e){const t=c(()=>{const s=e.getRegisteredCommands().map(o=>({name:o.invocationName,description:o.description,source:"extension",sourceInfo:o.sourceInfo})),n=this.promptTemplates.map(o=>({name:o.name,description:o.description,source:"prompt",sourceInfo:o.sourceInfo})),i=this._resourceLoader.getSkills().skills.map(o=>({name:`skill:${o.name}`,description:o.description,source:"skill",sourceInfo:o.sourceInfo}));return[...s,...n,...i]},"getCommands");e.bindCore({sendMessage:c((s,n)=>{this.sendCustomMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_message",error:i instanceof Error?i.message:String(i)})})},"sendMessage"),sendUserMessage:c((s,n)=>{this.sendUserMessage(s,n).catch(i=>{e.emitError({extensionPath:"<runtime>",event:"send_user_message",error:i instanceof Error?i.message:String(i)})})},"sendUserMessage"),appendEntry:c((s,n)=>{const i=this.sessionManager.appendCustomEntry(s,n),o=this.sessionManager.getEntry(i);o&&this._emit({type:"entry_appended",entry:o})},"appendEntry"),emitHostEvent:c((s,n)=>{this._emit({type:"extension_event",name:s,data:n??null})},"emitHostEvent"),setSessionName:c(s=>{this.setSessionName(s)},"setSessionName"),getSessionName:c(()=>this.sessionManager.getSessionName(),"getSessionName"),setLabel:c((s,n)=>{this.sessionManager.appendLabelChange(s,n)},"setLabel"),getActiveTools:c(()=>this.getActiveToolNames(),"getActiveTools"),getAllTools:c(()=>this.getAllTools(),"getAllTools"),setActiveTools:c(s=>this.setActiveToolsByName(s),"setActiveTools"),isToolAllowed:c(s=>this.isToolAllowed(s),"isToolAllowed"),getToolAllowlist:c(()=>this.getToolAllowlist(),"getToolAllowlist"),getToolDenylist:c(()=>this.getToolDenylist(),"getToolDenylist"),refreshTools:c(()=>this._refreshToolRegistry(),"refreshTools"),getCommands:t,setModel:c(async s=>this._modelRuntime.hasConfiguredAuth(s.provider)?(await this.setModel(s),!0):!1,"setModel"),getThinkingLevel:c(()=>this.thinkingLevel,"getThinkingLevel"),setThinkingLevel:c(s=>this.setThinkingLevel(s),"setThinkingLevel")},{getModel:c(()=>this.model,"getModel"),getScopedModels:c(()=>this._scopedModels,"getScopedModels"),isIdle:c(()=>this.isIdle,"isIdle"),isProjectTrusted:c(()=>this.settingsManager.isProjectTrusted(),"isProjectTrusted"),getSignal:c(()=>this.agent.signal,"getSignal"),abort:c(()=>{if(this._extensionAbortHandler){this._extensionAbortHandler();return}this.abort()},"abort"),hasPendingMessages:c(()=>this.pendingMessageCount>0,"hasPendingMessages"),shutdown:c(()=>{this._extensionShutdownHandler?.()},"shutdown"),getContextUsage:c(()=>this.getContextUsage(),"getContextUsage"),compact:c(s=>{(async()=>{try{const n=await this.compact(s?.customInstructions);s?.onComplete?.(n)}catch(n){const i=n instanceof Error?n:new Error(String(n));s?.onError?.(i)}})()},"compact"),getSystemPrompt:c(()=>this.systemPrompt,"getSystemPrompt"),getSystemPromptOptions:c(()=>this._baseSystemPromptOptions,"getSystemPromptOptions")},{registerProvider:c((s,n)=>{this._modelRuntime.registerProvider(s,n),this._refreshCurrentModelFromRegistry()},"registerProvider"),registerNativeProvider:c(s=>{this._modelRuntime.registerNativeProvider(s),this._refreshCurrentModelFromRegistry()},"registerNativeProvider"),unregisterProvider:c(s=>{this._modelRuntime.unregisterProvider(s),this._refreshCurrentModelFromRegistry()},"unregisterProvider")})}_refreshToolRegistry(e){const t=new Set(this._toolRegistry.keys()),s=this.getActiveToolNames(),n=this._allowedToolNames,i=c(d=>this.isToolAllowed(d),"isAllowedTool"),r=[...this._extensionRunner.getAllRegisteredTools(),...this._customTools.map(d=>({definition:d,sourceInfo:O(`<sdk:${d.name}>`,{source:"sdk"})}))].filter(d=>i(d.definition.name)),a=new Map(Array.from(this._baseToolDefinitions.entries()).filter(([d])=>i(d)).map(([d,g])=>[d,{definition:g,sourceInfo:O(`<builtin:${d}>`,{source:"builtin"})}]));for(const d of r)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 g=this._normalizePromptSnippet(d.promptSnippet);return g?[d.name,g]:void 0}).filter(d=>d!==void 0)),this._toolPromptGuidelines=new Map(Array.from(a.values()).map(({definition:d})=>{const g=this._normalizePromptGuidelines(d.promptGuidelines);return g.length>0?[d.name,g]:void 0}).filter(d=>d!==void 0));const l=this._extensionRunner,u=$(r,l),h=$(Array.from(this._baseToolDefinitions.values()).filter(d=>i(d.name)).map(d=>({definition:d,sourceInfo:O(`<builtin:${d.name}>`,{source:"builtin"})})),l),m=new Map(h.map(d=>[d.name,d]));for(const d of u)m.set(d.name,d);this._toolRegistry=m;const p=(e?.activeToolNames?[...e.activeToolNames]:[...s]).filter(d=>i(d));if(n)for(const d of this._toolRegistry.keys())n.has(d)&&p.push(d);else if(e?.includeAllExtensionTools)for(const d of u)p.push(d.name);else if(!e?.activeToolNames)for(const d of this._toolRegistry.keys())t.has(d)||p.push(d);this.setActiveToolsByName([...new Set(p)])}_buildRuntime(e){const t=this.settingsManager.getImageAutoResize(),s=this.settingsManager.getShellCommandPrefix(),n=this.settingsManager.getShellPath();de(this.settingsManager.getShellEnvironmentPolicy());const i=je({settings:this.settingsManager.getSandboxSettingsSources(),override:this._sandboxOptions,defaultLevel:this._sandboxOptions.defaultLevel??"off"}),o=new Ge({policy:i,onEscalation:this._sandboxOptions.onEscalation,onEvent:c(m=>this._emit(m),"onEvent"),scratchDir:c(()=>(this._sandboxScratch??=$e(),this._sandboxScratch),"scratchDir")}),r=this._shellSandbox;this._shellSandbox=o,r?.dispose(),Ke(o),process.env[qe]=He(i),this._permissionRules=Ne(this.settingsManager.getPermissionRuleSources()),this._readGuard=Oe({cwd:this._cwd,rules:this._permissionRules,...i.level!=="off"?{protectedReads:ze(i,this._cwd).denyRead}:{}}),We(this._readGuard);const a=this._baseToolsOverride?Object.fromEntries(Object.entries(this._baseToolsOverride).map(([m,p])=>[m,st(p)])):et(this._cwd,{read:{autoResizeImages:t},bash:{commandPrefix:s,shellPath:n,sandbox:o}});this._baseToolDefinitions=new Map(Object.entries(a).map(([m,p])=>[m,p])),this._baseToolsOverride||this._baseToolDefinitions.set("process",tt(this._cwd,this._backgroundProcesses,{sandboxed:o.active}));const l=this._resourceLoader.getExtensions();if(e.flagValues)for(const[m,p]of e.flagValues)l.runtime.flagValues.set(m,p);this._extensionRunner=new Ee(l.extensions,l.runtime,this._cwd,this.sessionManager,new ke(this._modelRuntime)),this._extensionRunnerRef&&(this._extensionRunnerRef.current=this._extensionRunner),this._bindExtensionCore(this._extensionRunner),this._applyExtensionBindings(this._extensionRunner);const u=this._baseToolsOverride?Object.keys(this._baseToolsOverride):["read","bash","edit","write"],h=e.activeToolNames??u;this._refreshToolRegistry({activeToolNames:h,includeAllExtensionTools:e.includeAllExtensionTools})}async reload(e){const t=this._extensionRunner,s=t.getFlagValues();await Pe(t,{type:"session_shutdown",reason:"reload"}),t.invalidate(),await this.settingsManager.reload(),this.syncQueueModesFromSettings(),ae(),await this._resourceLoader.reload(),this._buildRuntime({activeToolNames:this.getActiveToolNames(),flagValues:s,includeAllExtensionTools:!0}),(this._extensionUIContext||this._extensionCommandContextActions||this._extensionShutdownHandler||this._extensionErrorListener)&&(await e?.beforeSessionStart?.(),await this._extensionRunner.emit({type:"session_start",reason:"reload"}),await this.extendResourcesFromExtensions("reload"))}_isRetryableError(e){return N(e,this.model?.contextWindow??0)?!1:re(e)}_summarizationRetryCallbacks(e){return{onRetryScheduled:c((t,s,n,i)=>{this._emit({type:"summarization_retry_scheduled",attempt:t,maxAttempts:s,delayMs:n,errorMessage:i})},"onRetryScheduled"),onRetryAttemptStart:c(()=>{this._emit({type:"summarization_retry_attempt_start",...e})},"onRetryAttemptStart"),onRetryFinished:c(()=>{this._emit({type:"summarization_retry_finished"})},"onRetryFinished")}}_finishCancelledRetry(){if(this._retryAttempt===0)return;const e=this._retryAttempt;this._retryAttempt=0,this._emit({type:"auto_retry_end",success:!1,attempt:e,finalError:"Retry cancelled"})}async _prepareRetry(e){const t=this.settingsManager.getRetrySettings();if(!t.enabled)return!1;if(this._retryAttempt++,this._retryAttempt>t.maxRetries)return this._retryAttempt--,!1;const s=se(t,this._retryAttempt);this._emit({type:"auto_retry_start",attempt:this._retryAttempt,maxAttempts:t.maxRetries,delayMs:s,errorMessage:e.errorMessage||"Unknown error"}),this._omitRecoveryAttempt(e),this._retryAbortController=new AbortController;try{await ge(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 i=this.settingsManager.getShellCommandPrefix(),o=this.settingsManager.getShellPath(),r=i?`${i}
|
|
15
|
+
${e}`:e;try{const a=await _e(r,this.sessionManager.getCwd(),s?.operations??Ze({shellPath:o}),{onChunk:c(l=>{t?.(l),this._emit({type:"bash_execution_update",id:s?.id,delta:l})},"onChunk"),signal:n.signal});return this.recordBashResult(e,a,s),a}finally{this._bashAbortControllers.delete(n)}}recordBashResult(e,t,s){const n={role:"bashExecution",command:e,output:t.output,exitCode:t.exitCode,cancelled:t.cancelled,truncated:t.truncated,fullOutputPath:t.fullOutputPath,timestamp:Date.now(),excludeFromContext:s?.excludeFromContext};this.isStreaming?this._pendingBashMessages.push(n):(this.sessionManager.appendMessage(n),this._refreshFinalizedContext())}abortBash(){for(const e of[...this._bashAbortControllers])e.abort()}get isBashRunning(){return this._bashAbortControllers.size>0}get hasPendingBashMessages(){return this._pendingBashMessages.length>0}_flushPendingBashMessages(){if(this._pendingBashMessages.length!==0){for(const e of this._pendingBashMessages)this.sessionManager.appendMessage(e);this._pendingBashMessages=[],this._refreshFinalizedContext()}}setSessionName(e){this.sessionManager.appendSessionInfo(e);const t={type:"session_info_changed",name:this.sessionManager.getSessionName()};this._emit(t),this._extensionRunner.emit(t)}async navigateTree(e,t={}){if(this.isStreaming)throw new Error("Wait for the current response to finish before navigating the session tree.");if(this.isCompacting)throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");const s=this.sessionManager.getLeafId();if(e===s)return{cancelled:!1};if(t.summarize&&!this.model)throw new Error("No model available for summarization");const n=this.sessionManager.getEntry(e);if(!n)throw new Error(`Entry ${e} not found`);const{entries:i,commonAncestorId:o}=xe(this.sessionManager,s,e);let r=t.customInstructions,a=t.replaceInstructions,l=t.label;const u={targetId:e,oldLeafId:s,commonAncestorId:o,entriesToSummarize:i,userWantsSummary:t.summarize??!1,customInstructions:r,replaceInstructions:a,label:l};this._branchSummaryAbortController=new AbortController;try{let h,m=!1;if(this._extensionRunner.hasHandlers("session_before_tree")){const f=await this._extensionRunner.emit({type:"session_before_tree",preparation:u,signal:this._branchSummaryAbortController.signal});if(f?.cancel)return{cancelled:!0};f?.summary&&t.summarize&&(h=f.summary,m=!0),f?.customInstructions!==void 0&&(r=f.customInstructions),f?.replaceInstructions!==void 0&&(a=f.replaceInstructions),f?.label!==void 0&&(l=f.label)}let p,d,g;if(t.summarize&&i.length>0&&!h){const f=this.model,{model:R,apiKey:b,headers:_,env:v}=await this._getSummarizationRequestAuth(f),T=this.settingsManager.getBranchSummarySettings(),y=await Re(i,{model:R,apiKey:b,headers:_,env:v,signal:this._branchSummaryAbortController.signal,customInstructions:r,replaceInstructions:a,reserveTokens:T.reserveTokens,streamFn:this.agent.streamFunction,retry:this.settingsManager.getRetrySettings(),callbacks:this._summarizationRetryCallbacks({source:"branchSummary"})});if(y.aborted)return{cancelled:!0,aborted:!0};if(y.error)throw new Error(y.error);p=y.summary,g=y.usage,d={readFiles:y.readFiles||[],modifiedFiles:y.modifiedFiles||[]}}else h&&(p=h.summary,d=h.details,g=h.usage);let x,w;n.type==="message"&&n.message.role==="user"?(x=n.parentId,w=E(n.message.content,"")):n.type==="custom_message"?(x=n.parentId,w=E(n.content,"")):x=e;let A;if(p){const f=this.sessionManager.branchWithSummary(x,p,d,m,g);A=this.sessionManager.getEntry(f),l&&this.sessionManager.appendLabelChange(f,l)}else x===null?this.sessionManager.resetLeaf():this.sessionManager.branch(x);return l&&!p&&this.sessionManager.appendLabelChange(e,l),this._refreshFinalizedContext(),this._restoreToolsFromTranscript(),await this._extensionRunner.emit({type:"session_tree",newLeafId:this.sessionManager.getLeafId(),oldLeafId:s,summaryEntry:A,fromExtension:p?m:void 0}),{editorText:w,cancelled:!1,summaryEntry:A}}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=E(s.message.content,"");n&&t.push({entryId:s.id,text:n})}return t}getSessionStats(){let e=0,t=0,s=0,n=0,i=0;const o=nt();for(const r of this.sessionManager.getEntries()){if(r.type==="usage"?L(o,r.usage):(r.type==="branch_summary"||r.type==="compaction")&&r.usage&&L(o,r.usage),r.type!=="message")continue;n++;const a=r.message;if(a.role==="user")e++;else if(a.role==="toolResult")s++,a.usage&&L(o,a.usage);else if(a.role==="assistant"){t++;const l=a;Array.isArray(l.content)&&(i+=l.content.filter(u=>u.type==="toolCall").length),L(o,l.usage)}}return{sessionFile:this.sessionFile,sessionId:this.sessionId,userMessages:e,assistantMessages:t,toolCalls:i,toolResults:s,totalMessages:n,tokens:{input:o.input,output:o.output,cacheRead:o.cacheRead,cacheWrite:o.cacheWrite,total:o.input+o.output+o.cacheRead+o.cacheWrite},cost:o.cost,contextUsage:this.getContextUsage()}}getContextUsage(){const e=this.model;if(!e)return;const t=e.contextWindow??0;if(t<=0)return;const s=this.sessionManager.buildSessionProjection(),n=this.sessionManager.getBranch(),i=K(n);if(i){const a=new Set(s.entries.flatMap(h=>h.messages.some(m=>m.role==="assistant"&&m.stopReason!=="aborted"&&m.stopReason!=="error"&&j(m.usage)>0)?[h.sourceEntry.id]:[])),l=n.findIndex(h=>h.id===i.id);if(!n.slice(l+1).some(h=>a.has(h.id)))return{tokens:null,contextWindow:t,percent:null}}const o=k(s,n),r=o.tokens/t*100;return{tokens:o.tokens,contextWindow:t,percent:r}}async exportToHtml(e,t={}){const s=[t.themeName,this.settingsManager.getTheme()].find(i=>i!==void 0&&ce(i)!==void 0),n=Te({getToolDefinition:c(i=>this.getToolDefinition(i),"getToolDefinition"),theme:he,cwd:this.sessionManager.getCwd()});return await ve(this.sessionManager,this.state,{outputPath:e,themeName:s,toolRenderer:n})}exportToJsonl(e){return Qe(this.sessionManager,e)}async summarizeForBugReport(e){const t=this.model;if(!t)throw new Error("No model selected");const{model:s,apiKey:n,headers:i,env:o}=await this._getSummarizationRequestAuth(t);return ye({messages:this.messages,hint:e.hint,model:s,apiKey:n,headers:i,env:o,signal:e.signal,thinkingLevel:this.thinkingLevel,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{$t as AgentSession,Ht as parseSkillBlock};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
`))for(const n of $){const d=n.exec(s);d&&o.add(Number(d[1]))}return{ports:[...o].filter(s=>s>0&&s<65536),urls:[...e]}}f(M,"detectListening");function _(p){if(process.platform==="win32")return[];const t=
|
|
3
|
-
`)){const s=/^n.*:(\d+)$/.exec(e.trim());s&&o.add(Number(s[1]))}return[...o]}f(_,"listeningPortsOf");let D=0;class K{static{f(this,"BackgroundProcessManager")}entries=new Map;options;exitHandler=f(()=>this.killAllNow(),"exitHandler");exitHookInstalled=!1;constructor(t={}){this.options=t}get maxProcesses(){return this.options.maxProcesses??R}emit(t,o){this.options.onEvent?.({type:"background_process",event:t,process:this.snapshot(o)})}snapshot(t){return{...t.info,ports:[...t.info.ports],urls:[...t.info.urls]}}running(){return[...this.entries.values()].filter(t=>t.info.state==="running")}async start(t){if(this.running().length>=this.maxProcesses)throw new Error(`Too many background processes (limit ${this.maxProcesses}). Stop one with the process tool (action "stop") first.`);const o=
|
|
1
|
+
var k=Object.defineProperty;var f=(p,t)=>k(p,"name",{value:t,configurable:!0});import{spawn as P,spawnSync as B}from"node:child_process";import{closeSync as E,openSync as T,writeSync as A}from"node:fs";import{tmpdir as v}from"node:os";import{join as F}from"node:path";import{getShellConfig as y,getShellEnv as S,killProcessTree as m,trackDetachedChildPid as N,untrackDetachedChildPid as C}from"../utils/shell.js";const R=8,H=512*1024,I=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|[\w.-]+\.local)(?::(\d{2,5}))?(?:\/[^\s'"`)\]]*)?/gi,$=[/\b(?:listening|running|started|serving|available|ready)\b[^\n]*?\bport\s*:?\s*(\d{2,5})\b/i,/\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]):(\d{2,5})\b/i],O=/\x1b\[[0-9;]*[A-Za-z]/g;function M(p){const t=p.replace(O,""),o=new Set,e=new Set;for(const s of t.matchAll(I))e.add(s[0].replace(/[.,;]+$/,"")),s[1]&&o.add(Number(s[1]));for(const s of t.split(`
|
|
2
|
+
`))for(const n of $){const d=n.exec(s);d&&o.add(Number(d[1]))}return{ports:[...o].filter(s=>s>0&&s<65536),urls:[...e]}}f(M,"detectListening");function _(p){if(process.platform==="win32")return[];const t=B("lsof",["-nP","-a","-iTCP","-sTCP:LISTEN","-g",String(p),"-Fn"],{encoding:"utf8",timeout:2e3});if(t.status!==0||!t.stdout)return[];const o=new Set;for(const e of t.stdout.split(`
|
|
3
|
+
`)){const s=/^n.*:(\d+)$/.exec(e.trim());s&&o.add(Number(s[1]))}return[...o]}f(_,"listeningPortsOf");let D=0;class K{static{f(this,"BackgroundProcessManager")}entries=new Map;options;exitHandler=f(()=>this.killAllNow(),"exitHandler");exitHookInstalled=!1;constructor(t={}){this.options=t}get maxProcesses(){return this.options.maxProcesses??R}emit(t,o){this.options.onEvent?.({type:"background_process",event:t,process:this.snapshot(o)})}snapshot(t){return{...t.info,ports:[...t.info.ports],urls:[...t.info.urls]}}running(){return[...this.entries.values()].filter(t=>t.info.state==="running")}async start(t){if(this.running().length>=this.maxProcesses)throw new Error(`Too many background processes (limit ${this.maxProcesses}). Stop one with the process tool (action "stop") first.`);const o=y(this.options.shellPath?.()),e=this.options.sandbox?.();let s;e?.active&&(s=await e.prepare({command:t.command,cwd:t.cwd,shell:o.shell,env:S(),toolCallId:t.toolCallId,toolName:"process",escalation:t.escalation,background:!0,ctx:t.ctx}));const n=`bg${++D}`,d=F(v(),`dal-bg-${process.pid}-${n}.log`),c=o.commandTransport==="stdin",l=s?.command??t.command;let w,r;try{w=T(d,"w"),r=P(o.shell,c?o.args:[...o.args,l],{cwd:t.cwd,detached:process.platform!=="win32",env:S(),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0})}catch(a){throw await s?.finish(0,""),a}c&&(r.stdin?.on("error",()=>{}),r.stdin?.end(l)),r.pid&&N(r.pid),this.exitHookInstalled||(process.on("exit",this.exitHandler),this.exitHookInstalled=!0);let g;const i={info:{id:n,...t.name?{name:t.name}:{},command:t.command,cwd:t.cwd,...r.pid?{pid:r.pid}:{},state:"running",startedAt:Date.now(),ports:[],urls:[],sandboxed:s?.sandboxed===!0,portsReachableFromHost:!(s?.sandboxed&&process.platform==="linux"),logFile:d,outputBytes:0},child:r,chunks:[],bufferedBytes:0,droppedBytes:0,readOffset:0,logFd:w,prepared:s,exited:new Promise(a=>{g=a})};this.entries.set(n,i);const b=f(a=>{this.append(i,a);const u=M(a.toString("utf8"));let x=!1;for(const h of u.ports)i.info.ports.includes(h)||(i.info.ports.push(h),x=!0);for(const h of u.urls)i.info.urls.includes(h)||(i.info.urls.push(h),x=!0);x&&this.emit("port",i)},"onData");return r.stdout?.on("data",b),r.stderr?.on("data",b),r.once("error",a=>{this.append(i,Buffer.from(`
|
|
4
4
|
[failed to start: ${a.message}]
|
|
5
|
-
`)),this.onExit(i,null,null,"failed").then(g)}),r.once("close",(a,u)=>{this.onExit(i,a,u,i.info.state==="stopped"?"stopped":"exited").then(g)}),this.emit("started",i),this.snapshot(i)}append(t,o){if(t.info.outputBytes+=o.length,t.logFd!==void 0)try{
|
|
5
|
+
`)),this.onExit(i,null,null,"failed").then(g)}),r.once("close",(a,u)=>{this.onExit(i,a,u,i.info.state==="stopped"?"stopped":"exited").then(g)}),this.emit("started",i),this.snapshot(i)}append(t,o){if(t.info.outputBytes+=o.length,t.logFd!==void 0)try{A(t.logFd,o)}catch{}for(t.chunks.push(o),t.bufferedBytes+=o.length;t.bufferedBytes>H&&t.chunks.length>1;){const e=t.chunks.shift();t.bufferedBytes-=e.length,t.droppedBytes+=e.length}}async onExit(t,o,e,s){if(t.info.endedAt===void 0){if(t.info.endedAt=Date.now(),t.info.state=s,t.info.exitCode=o,t.info.signal=e,t.child?.pid&&C(t.child.pid),t.logFd!==void 0){try{E(t.logFd)}catch{}t.logFd=void 0}if(t.prepared){const n=await t.prepared.finish(s==="stopped"?0:o,Buffer.concat(t.chunks).toString("utf8"));n&&(t.info.denial=n)}this.emit(s==="stopped"?"stopped":"exited",t)}}entry(t){const o=this.entries.get(t);if(!o){const e=[...this.entries.keys()].join(", ")||"none";throw new Error(`No background process "${t}" (known: ${e}).`)}return o}read(t,o={}){const e=this.entry(t),s=Buffer.concat(e.chunks),n=e.droppedBytes;let d,c=!1;if(o.tail!==void 0){const l=s.toString("utf8").split(`
|
|
6
6
|
`);l.at(-1)===""&&l.pop(),c=l.length>o.tail||e.droppedBytes>0,d=l.slice(-Math.max(0,o.tail)).join(`
|
|
7
7
|
`)}else{const l=Math.max(e.readOffset,n);c=e.readOffset<n,d=s.subarray(l-n).toString("utf8"),e.readOffset=n+s.length}return{text:d,truncated:c,info:this.snapshot(e)}}status(t){const o=this.entry(t);if(o.info.state==="running"&&o.info.pid&&o.info.portsReachableFromHost){let e=!1;for(const s of _(o.info.pid))o.info.ports.includes(s)||(o.info.ports.push(s),e=!0);e&&this.emit("port",o)}return this.snapshot(o)}list(){return[...this.entries.values()].map(t=>this.snapshot(t))}async stop(t,o=3e3){const e=this.entry(t);if(e.info.state!=="running"||!e.child?.pid)return this.snapshot(e);e.info.state="stopped";const s=e.child.pid;if(process.platform==="win32")m(s);else try{process.kill(-s,"SIGTERM")}catch{m(s)}const n=setTimeout(()=>m(s),o);return await e.exited,clearTimeout(n),this.snapshot(e)}async stopAll(){await Promise.all(this.running().map(t=>this.stop(t.info.id,1e3))),process.removeListener("exit",this.exitHandler),this.exitHookInstalled=!1}killAllNow(){for(const t of this.running())t.child?.pid&&m(t.child.pid)}}export{K as BackgroundProcessManager,R as MAX_BACKGROUND_PROCESSES,M as detectListening};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var V=Object.defineProperty;var i=(e,r)=>V(e,"name",{value:r,configurable:!0});import*as y from"node:fs";import{createRequire as $}from"node:module";import*as g from"node:path";import{fileURLToPath as b}from"node:url";import{CONFIG_DIR_NAME as B,getAgentDir as _,isBunBinary as C,isBundledNode as O}from"../../config.js";import{resolvePath as v}from"../../utils/paths.js";import{createEventBus as J}from"../event-bus.js";import{execCommand as W}from"../exec.js";import{findNearestPiManifest as q,getExtensionApiMismatchError as G,readPiManifest as H}from"../pi-manifest.js";import{createSyntheticSourceInfo as X}from"../source-info.js";import{time as R}from"../timings.js";import{applyPermissionSurface as K}from"./permission-surface.js";const M=$(import.meta.url),Q=Symbol.for("dalcode.extensions.apiDecorator"),Y="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,Z=!C&&g.extname(b(import.meta.url))===".ts",j=C||Y||O;let I;function ee(){return I??=(j?import("./jiti-static-loader.js"):import("./jiti-loader.js")).then(e=>e.createJiti),I}i(ee,"getCreateJiti");let N;function L(){return N??=import("./virtual-modules.js").then(e=>e.VIRTUAL_MODULES),N}i(L,"getVirtualModules");let S=null;function te(){if(S)return S;const e=g.dirname(b(import.meta.url)),r=g.resolve(e,"../..","index.js"),u=M.resolve("typebox"),d=M.resolve("typebox/compile"),c=M.resolve("typebox/value"),a=g.resolve(e,"../../../../"),o=i((s,h)=>{const x=g.join(a,s);return y.existsSync(x)?x:b(import.meta.resolve(h))},"resolveWorkspaceOrImport"),l=r,n=o("agent/dist/index.js","@earendil-works/pi-agent-core"),p=o("tui/dist/index.js","@earendil-works/pi-tui"),f=o("ai/dist/compat.js","@earendil-works/pi-ai/compat"),m=o("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),t=o("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return S={"@earendil-works/pi-coding-agent":l,"@earendil-works/pi-agent-core":n,"@earendil-works/pi-tui":p,"@earendil-works/pi-ai/providers/all":t,"@earendil-works/pi-ai/compat":f,"@earendil-works/pi-ai/oauth":m,"@earendil-works/pi-ai":f,"@mariozechner/pi-coding-agent":l,"@mariozechner/pi-agent-core":n,"@mariozechner/pi-tui":p,"@mariozechner/pi-ai/providers/all":t,"@mariozechner/pi-ai/compat":f,"@mariozechner/pi-ai/oauth":m,"@mariozechner/pi-ai":f,typebox:u,"typebox/compile":d,"typebox/value":c,"@sinclair/typebox":u,"@sinclair/typebox/compile":d,"@sinclair/typebox/value":c},S}i(te,"getAliases");let E,A=0;const T=new Map;function re(){T.clear(),E=void 0,A++}i(re,"clearExtensionCache");function se(e){const r=v(e);return E!==void 0&&E!==r&&re(),E=r,{cwd:r,generation:A}}i(se,"useExtensionCacheCwd");function ne(){const e=i(()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},"notInitialized"),r={},u=new Set,c={sendMessage:e,sendUserMessage:e,appendEntry:e,setSessionName:e,getSessionName:e,setLabel:e,getActiveTools:e,getAllTools:e,setActiveTools:e,isToolAllowed:e,getToolAllowlist:e,refreshTools:i(()=>{},"refreshTools"),getCommands:e,setModel:i(()=>Promise.reject(new Error("Extension runtime not initialized")),"setModel"),getThinkingLevel:e,setThinkingLevel:e,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],assertActive:i(()=>{if(r.staleMessage)throw new Error(r.staleMessage)},"assertActive"),invalidate:i(a=>{if(!r.staleMessage){r.staleMessage=a??"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().";for(const o of u)o();u.clear()}},"invalidate"),trackEventBusSubscription:i(a=>{let o=!0;const l=i(()=>{o&&(o=!1,u.delete(l),a())},"trackedUnsubscribe");return u.add(l),l},"trackEventBusSubscription"),registerProvider:i((a,o,l="<unknown>")=>{c.pendingProviderRegistrations.push({name:a,config:o,extensionPath:l})},"registerProvider"),registerNativeProvider:i((a,o="<unknown>")=>{c.pendingNativeProviderRegistrations.push({provider:a,extensionPath:o})},"registerNativeProvider"),unregisterProvider:i(a=>{c.pendingProviderRegistrations=c.pendingProviderRegistrations.filter(o=>o.name!==a),c.pendingNativeProviderRegistrations=c.pendingNativeProviderRegistrations.filter(o=>o.provider.id!==a)},"unregisterProvider")};return c}i(ne,"createExtensionRuntime");function oe(e,r,u,d){const c=new Map,a=[],o=[];let l="loading";const n=i(()=>{if(l==="failed")throw new Error(`Extension "${e.path}" failed to load and its API is no longer active.`);r.assertActive()},"assertActive"),p=i(t=>{l==="loading"?a.push(t):t()},"applyRuntimeChange"),f=i(()=>{c.clear(),a.length=0,o.length=0},"clearPending");return{api:{on(t,s){n();const h=i((...w)=>s(...w),"registeredHandler"),x=e.handlers.get(t)??[];return x.push(h),e.handlers.set(t,x),()=>{const w=e.handlers.get(t);if(!w)return;const P=w.indexOf(h);P!==-1&&(w.splice(P,1),w.length===0&&e.handlers.delete(t))}},registerTool(t){if(n(),typeof t.parameters!="object"||t.parameters===null||Array.isArray(t.parameters))throw new Error(`Tool "${t.name}" registered by extension "${e.path}" must define an object parameter schema.`);e.tools.set(t.name,{definition:t,sourceInfo:e.sourceInfo}),r.refreshTools()},registerCommand(t,s){n(),e.commands.set(t,{name:t,sourceInfo:e.sourceInfo,...s})},registerShortcut(t,s){n(),e.shortcuts.set(t,{shortcut:t,extensionPath:e.path,...s})},registerFlag(t,s){if(n(),s.default!==void 0&&typeof s.default!==s.type)throw new Error(`Invalid default for flag "${t}": expected ${s.type}, got ${typeof s.default}`);e.flags.set(t,{name:t,extensionPath:e.path,...s}),s.default!==void 0&&!r.flagValues.has(t)&&(l==="loading"?c.has(t)||c.set(t,s.default):r.flagValues.set(t,s.default))},registerMessageRenderer(t,s){n(),e.messageRenderers.set(t,s)},registerMarkdownTransformer(t){n(),e.markdownTransformer=t},registerEntryRenderer(t,s){n(),e.entryRenderers??=new Map,e.entryRenderers.set(t,s)},getFlag(t){if(n(),!!e.flags.has(t))return r.flagValues.has(t)?r.flagValues.get(t):c.get(t)},sendMessage(t,s){n(),r.sendMessage(t,s)},sendUserMessage(t,s){n(),r.sendUserMessage(t,s)},appendEntry(t,s){n(),r.appendEntry(t,s)},setSessionName(t){n(),r.setSessionName(t)},getSessionName(){return n(),r.getSessionName()},setLabel(t,s){n(),r.setLabel(t,s)},exec(t,s,h){return n(),W(t,s,h?.cwd??u,h)},getActiveTools(){return n(),r.getActiveTools()},getAllTools(){return n(),r.getAllTools()},setActiveTools(t){n(),r.setActiveTools(t)},isToolAllowed(t){return n(),r.isToolAllowed(t)},getToolAllowlist(){return n(),r.getToolAllowlist()},getToolDenylist(){return n(),r.getToolDenylist?.()},getCommands(){return n(),r.getCommands()},setModel(t){return n(),r.setModel(t)},getThinkingLevel(){return n(),r.getThinkingLevel()},setThinkingLevel(t){n(),r.setThinkingLevel(t)},registerModelPickerEntry(t,s){n(),e.modelPickerEntries??=new Map,e.modelPickerEntries.set(t,{...s,id:t,extensionPath:e.path})},registerProvider(t,s){if(n(),typeof t=="string"){if(!s)throw new Error("Provider config is required when registering by name");p(()=>r.registerProvider(t,s,e.path));return}p(()=>r.registerNativeProvider(t,e.path))},unregisterProvider(t){n(),p(()=>r.unregisterProvider(t,e.path))},events:{emit(t,s){n(),d.emit(t,s)},on(t,s){n();const h=r.trackEventBusSubscription(d.on(t,s));return l==="loading"&&o.push(h),h}}},commit:i(()=>{if(l==="loading"){r.assertActive();for(const[t,s]of c)r.flagValues.has(t)||r.flagValues.set(t,s);for(const t of a)t();l="active",f()}},"commit"),discard:i(()=>{if(l==="loading"){l="failed";for(const t of o)t();f()}},"discard")}}i(oe,"createExtensionAPI");function D(e){return e!==void 0&&E===e.cwd&&A===e.generation}i(D,"isCurrentCacheToken");async function ie(e,r){if(D(r)){const l=T.get(e);if(l)return l}const u=await ee(),d=j?{virtualModules:await L(),tryNative:!1}:Z?{virtualModules:await L(),tsconfigPaths:!0}:{alias:te()},o=await u(import.meta.url,{moduleCache:!1,...d}).import(e,{default:!0});if(typeof o=="function")return D(r)&&T.set(e,o),o}i(ie,"loadExtensionModule");function ae(e,r){const u=e.startsWith("<")&&e.endsWith(">")?e.slice(1,-1).split(":")[0]||"temporary":"local",d=e.startsWith("<")?void 0:g.dirname(r);return{path:e,resolvedPath:r,sourceInfo:X(e,{source:u,baseDir:d}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}i(ae,"createExtension");async function z(e,r,u,d,c,a,o){const l=ae(r,u),n=oe(l,a,d,c),p=globalThis[Q],f=typeof p=="function"?p(n.api,{extensionPath:r,resolvedPath:u}):n.api;try{await e(K(f,o)),n.commit()}catch(m){throw n.discard(),m}return R(`${r} factory`,"extensions"),l}i(z,"initializeExtension");async function ce(e,r,u,d,c){const a=v(e,r,{normalizeUnicodeSpaces:!0});try{const o=q(a),l=G(o?.manifest);if(l)return{extension:null,error:l};const n=await ie(a,c);return R(`${e} module import`,"extensions"),n?{extension:await z(n,e,a,r,u,d,o?.manifest.permissions),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${e}`}}catch(o){return{extension:null,error:`Failed to load extension: ${o instanceof Error?o.message:String(o)}`}}}i(ce,"loadExtension");async function Se(e,r,u,d,c="<inline>"){const a=v(r);return z(e,c,c,a,u,d)}i(Se,"loadExtensionFromFactory");async function F(e,r,u,d,c=!1){const a=[],o=[],l=c?se(r):void 0,n=l?.cwd??v(r),p=u??J(),f=d??ne();for(const m of e){const{extension:t,error:s}=await ce(m,n,p,f,l);if(s){o.push({path:m,error:s});continue}t&&a.push(t)}return{extensions:a,errors:o,runtime:f}}i(F,"loadExtensionsInternal");async function le(e,r,u,d){return F(e,r,u,d)}i(le,"loadExtensions");async function be(e,r,u,d){return F(e,r,u,d,!0)}i(be,"loadExtensionsCached");function de(e){return e.endsWith(".ts")||e.endsWith(".js")}i(de,"isExtensionFile");function U(e){const r=g.join(e,"package.json");if(y.existsSync(r)){const c=H(r);if(c?.extensions?.length){const a=[];for(const o of c.extensions){const l=g.resolve(e,o);y.existsSync(l)&&a.push(l)}if(a.length>0)return a}}const u=g.join(e,"index.ts"),d=g.join(e,"index.js");return y.existsSync(u)?[u]:y.existsSync(d)?[d]:null}i(U,"resolveExtensionEntries");function k(e){if(!y.existsSync(e))return[];const r=[];try{const u=y.readdirSync(e,{withFileTypes:!0});for(const d of u){const c=g.join(e,d.name);if((d.isFile()||d.isSymbolicLink())&&de(d.name)){r.push(c);continue}if(d.isDirectory()||d.isSymbolicLink()){const a=U(c);a&&r.push(...a)}}}catch{return[]}return r}i(k,"discoverExtensionsInDir");async function Me(e,r,u=_(),d){const c=v(r),a=v(u),o=[],l=new Set,n=i(m=>{for(const t of m){const s=g.resolve(t);l.has(s)||(l.add(s),o.push(t))}},"addPaths"),p=g.join(c,B,"extensions");n(k(p));const f=g.join(a,"extensions");n(k(f));for(const m of e){const t=v(m,c,{normalizeUnicodeSpaces:!0});if(y.existsSync(t)&&y.statSync(t).isDirectory()){const s=U(t);if(s){n(s);continue}n(k(t));continue}n([t])}return le(o,c,d)}i(Me,"discoverAndLoadExtensions");export{Q as EXTENSION_API_DECORATOR_SLOT,re as clearExtensionCache,ne as createExtensionRuntime,Me as discoverAndLoadExtensions,Se as loadExtensionFromFactory,le as loadExtensions,be as loadExtensionsCached};
|
|
1
|
+
var V=Object.defineProperty;var i=(t,r)=>V(t,"name",{value:r,configurable:!0});import*as v from"node:fs";import{createRequire as $}from"node:module";import*as g from"node:path";import{fileURLToPath as b}from"node:url";import{CONFIG_DIR_NAME as B,getAgentDir as _,isBunBinary as C,isBundledNode as O}from"../../config.js";import{resolvePath as y}from"../../utils/paths.js";import{createEventBus as J}from"../event-bus.js";import{execCommand as W}from"../exec.js";import{findNearestPiManifest as H,getExtensionApiMismatchError as q,readPiManifest as G}from"../pi-manifest.js";import{createSyntheticSourceInfo as X}from"../source-info.js";import{time as R}from"../timings.js";import{applyPermissionSurface as K}from"./permission-surface.js";const M=$(import.meta.url),Q=Symbol.for("dalcode.extensions.apiDecorator"),Y="sea"in process.features&&process.features.sea===!0||process.getBuiltinModule("node:sea")?.isSea()===!0,Z=!C&&g.extname(b(import.meta.url))===".ts",j=C||Y||O;let I;function ee(){return I??=(j?import("./jiti-static-loader.js"):import("./jiti-loader.js")).then(t=>t.createJiti),I}i(ee,"getCreateJiti");let N;function L(){return N??=import("./virtual-modules.js").then(t=>t.VIRTUAL_MODULES),N}i(L,"getVirtualModules");let S=null;function te(){if(S)return S;const t=g.dirname(b(import.meta.url)),r=g.resolve(t,"../..","index.js"),u=M.resolve("typebox"),d=M.resolve("typebox/compile"),c=M.resolve("typebox/value"),a=g.resolve(t,"../../../../"),o=i((s,h)=>{const x=g.join(a,s);return v.existsSync(x)?x:b(import.meta.resolve(h))},"resolveWorkspaceOrImport"),l=r,n=o("agent/dist/index.js","@earendil-works/pi-agent-core"),p=o("tui/dist/index.js","@earendil-works/pi-tui"),f=o("ai/dist/compat.js","@earendil-works/pi-ai/compat"),m=o("ai/dist/oauth.js","@earendil-works/pi-ai/oauth"),e=o("ai/dist/providers/all.js","@earendil-works/pi-ai/providers/all");return S={"@earendil-works/pi-coding-agent":l,"@earendil-works/pi-agent-core":n,"@earendil-works/pi-tui":p,"@earendil-works/pi-ai/providers/all":e,"@earendil-works/pi-ai/compat":f,"@earendil-works/pi-ai/oauth":m,"@earendil-works/pi-ai":f,"@mariozechner/pi-coding-agent":l,"@mariozechner/pi-agent-core":n,"@mariozechner/pi-tui":p,"@mariozechner/pi-ai/providers/all":e,"@mariozechner/pi-ai/compat":f,"@mariozechner/pi-ai/oauth":m,"@mariozechner/pi-ai":f,typebox:u,"typebox/compile":d,"typebox/value":c,"@sinclair/typebox":u,"@sinclair/typebox/compile":d,"@sinclair/typebox/value":c},S}i(te,"getAliases");let E,A=0;const T=new Map;function re(){T.clear(),E=void 0,A++}i(re,"clearExtensionCache");function se(t){const r=y(t);return E!==void 0&&E!==r&&re(),E=r,{cwd:r,generation:A}}i(se,"useExtensionCacheCwd");function ne(){const t=i(()=>{throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.")},"notInitialized"),r={},u=new Set,c={sendMessage:t,sendUserMessage:t,appendEntry:t,emitHostEvent:i(()=>{},"emitHostEvent"),setSessionName:t,getSessionName:t,setLabel:t,getActiveTools:t,getAllTools:t,setActiveTools:t,isToolAllowed:t,getToolAllowlist:t,refreshTools:i(()=>{},"refreshTools"),getCommands:t,setModel:i(()=>Promise.reject(new Error("Extension runtime not initialized")),"setModel"),getThinkingLevel:t,setThinkingLevel:t,flagValues:new Map,pendingProviderRegistrations:[],pendingNativeProviderRegistrations:[],assertActive:i(()=>{if(r.staleMessage)throw new Error(r.staleMessage)},"assertActive"),invalidate:i(a=>{if(!r.staleMessage){r.staleMessage=a??"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().";for(const o of u)o();u.clear()}},"invalidate"),trackEventBusSubscription:i(a=>{let o=!0;const l=i(()=>{o&&(o=!1,u.delete(l),a())},"trackedUnsubscribe");return u.add(l),l},"trackEventBusSubscription"),registerProvider:i((a,o,l="<unknown>")=>{c.pendingProviderRegistrations.push({name:a,config:o,extensionPath:l})},"registerProvider"),registerNativeProvider:i((a,o="<unknown>")=>{c.pendingNativeProviderRegistrations.push({provider:a,extensionPath:o})},"registerNativeProvider"),unregisterProvider:i(a=>{c.pendingProviderRegistrations=c.pendingProviderRegistrations.filter(o=>o.name!==a),c.pendingNativeProviderRegistrations=c.pendingNativeProviderRegistrations.filter(o=>o.provider.id!==a)},"unregisterProvider")};return c}i(ne,"createExtensionRuntime");function oe(t,r,u,d){const c=new Map,a=[],o=[];let l="loading";const n=i(()=>{if(l==="failed")throw new Error(`Extension "${t.path}" failed to load and its API is no longer active.`);r.assertActive()},"assertActive"),p=i(e=>{l==="loading"?a.push(e):e()},"applyRuntimeChange"),f=i(()=>{c.clear(),a.length=0,o.length=0},"clearPending");return{api:{on(e,s){n();const h=i((...w)=>s(...w),"registeredHandler"),x=t.handlers.get(e)??[];return x.push(h),t.handlers.set(e,x),()=>{const w=t.handlers.get(e);if(!w)return;const P=w.indexOf(h);P!==-1&&(w.splice(P,1),w.length===0&&t.handlers.delete(e))}},registerTool(e){if(n(),typeof e.parameters!="object"||e.parameters===null||Array.isArray(e.parameters))throw new Error(`Tool "${e.name}" registered by extension "${t.path}" must define an object parameter schema.`);t.tools.set(e.name,{definition:e,sourceInfo:t.sourceInfo}),r.refreshTools()},registerCommand(e,s){n(),t.commands.set(e,{name:e,sourceInfo:t.sourceInfo,...s})},registerShortcut(e,s){n(),t.shortcuts.set(e,{shortcut:e,extensionPath:t.path,...s})},registerFlag(e,s){if(n(),s.default!==void 0&&typeof s.default!==s.type)throw new Error(`Invalid default for flag "${e}": expected ${s.type}, got ${typeof s.default}`);t.flags.set(e,{name:e,extensionPath:t.path,...s}),s.default!==void 0&&!r.flagValues.has(e)&&(l==="loading"?c.has(e)||c.set(e,s.default):r.flagValues.set(e,s.default))},registerMessageRenderer(e,s){n(),t.messageRenderers.set(e,s)},registerMarkdownTransformer(e){n(),t.markdownTransformer=e},registerEntryRenderer(e,s){n(),t.entryRenderers??=new Map,t.entryRenderers.set(e,s)},getFlag(e){if(n(),!!t.flags.has(e))return r.flagValues.has(e)?r.flagValues.get(e):c.get(e)},sendMessage(e,s){n(),r.sendMessage(e,s)},sendUserMessage(e,s){n(),r.sendUserMessage(e,s)},appendEntry(e,s){n(),r.appendEntry(e,s)},emitHostEvent(e,s){n(),r.emitHostEvent?.(e,s)},setSessionName(e){n(),r.setSessionName(e)},getSessionName(){return n(),r.getSessionName()},setLabel(e,s){n(),r.setLabel(e,s)},exec(e,s,h){return n(),W(e,s,h?.cwd??u,h)},getActiveTools(){return n(),r.getActiveTools()},getAllTools(){return n(),r.getAllTools()},setActiveTools(e){n(),r.setActiveTools(e)},isToolAllowed(e){return n(),r.isToolAllowed(e)},getToolAllowlist(){return n(),r.getToolAllowlist()},getToolDenylist(){return n(),r.getToolDenylist?.()},getCommands(){return n(),r.getCommands()},setModel(e){return n(),r.setModel(e)},getThinkingLevel(){return n(),r.getThinkingLevel()},setThinkingLevel(e){n(),r.setThinkingLevel(e)},registerModelPickerEntry(e,s){n(),t.modelPickerEntries??=new Map,t.modelPickerEntries.set(e,{...s,id:e,extensionPath:t.path})},registerProvider(e,s){if(n(),typeof e=="string"){if(!s)throw new Error("Provider config is required when registering by name");p(()=>r.registerProvider(e,s,t.path));return}p(()=>r.registerNativeProvider(e,t.path))},unregisterProvider(e){n(),p(()=>r.unregisterProvider(e,t.path))},events:{emit(e,s){n(),d.emit(e,s)},on(e,s){n();const h=r.trackEventBusSubscription(d.on(e,s));return l==="loading"&&o.push(h),h}}},commit:i(()=>{if(l==="loading"){r.assertActive();for(const[e,s]of c)r.flagValues.has(e)||r.flagValues.set(e,s);for(const e of a)e();l="active",f()}},"commit"),discard:i(()=>{if(l==="loading"){l="failed";for(const e of o)e();f()}},"discard")}}i(oe,"createExtensionAPI");function D(t){return t!==void 0&&E===t.cwd&&A===t.generation}i(D,"isCurrentCacheToken");async function ie(t,r){if(D(r)){const l=T.get(t);if(l)return l}const u=await ee(),d=j?{virtualModules:await L(),tryNative:!1}:Z?{virtualModules:await L(),tsconfigPaths:!0}:{alias:te()},o=await u(import.meta.url,{moduleCache:!1,...d}).import(t,{default:!0});if(typeof o=="function")return D(r)&&T.set(t,o),o}i(ie,"loadExtensionModule");function ae(t,r){const u=t.startsWith("<")&&t.endsWith(">")?t.slice(1,-1).split(":")[0]||"temporary":"local",d=t.startsWith("<")?void 0:g.dirname(r);return{path:t,resolvedPath:r,sourceInfo:X(t,{source:u,baseDir:d}),handlers:new Map,tools:new Map,messageRenderers:new Map,entryRenderers:new Map,commands:new Map,flags:new Map,shortcuts:new Map}}i(ae,"createExtension");async function z(t,r,u,d,c,a,o){const l=ae(r,u),n=oe(l,a,d,c),p=globalThis[Q],f=typeof p=="function"?p(n.api,{extensionPath:r,resolvedPath:u}):n.api;try{await t(K(f,o)),n.commit()}catch(m){throw n.discard(),m}return R(`${r} factory`,"extensions"),l}i(z,"initializeExtension");async function ce(t,r,u,d,c){const a=y(t,r,{normalizeUnicodeSpaces:!0});try{const o=H(a),l=q(o?.manifest);if(l)return{extension:null,error:l};const n=await ie(a,c);return R(`${t} module import`,"extensions"),n?{extension:await z(n,t,a,r,u,d,o?.manifest.permissions),error:null}:{extension:null,error:`Extension does not export a valid factory function: ${t}`}}catch(o){return{extension:null,error:`Failed to load extension: ${o instanceof Error?o.message:String(o)}`}}}i(ce,"loadExtension");async function Se(t,r,u,d,c="<inline>"){const a=y(r);return z(t,c,c,a,u,d)}i(Se,"loadExtensionFromFactory");async function F(t,r,u,d,c=!1){const a=[],o=[],l=c?se(r):void 0,n=l?.cwd??y(r),p=u??J(),f=d??ne();for(const m of t){const{extension:e,error:s}=await ce(m,n,p,f,l);if(s){o.push({path:m,error:s});continue}e&&a.push(e)}return{extensions:a,errors:o,runtime:f}}i(F,"loadExtensionsInternal");async function le(t,r,u,d){return F(t,r,u,d)}i(le,"loadExtensions");async function be(t,r,u,d){return F(t,r,u,d,!0)}i(be,"loadExtensionsCached");function de(t){return t.endsWith(".ts")||t.endsWith(".js")}i(de,"isExtensionFile");function U(t){const r=g.join(t,"package.json");if(v.existsSync(r)){const c=G(r);if(c?.extensions?.length){const a=[];for(const o of c.extensions){const l=g.resolve(t,o);v.existsSync(l)&&a.push(l)}if(a.length>0)return a}}const u=g.join(t,"index.ts"),d=g.join(t,"index.js");return v.existsSync(u)?[u]:v.existsSync(d)?[d]:null}i(U,"resolveExtensionEntries");function k(t){if(!v.existsSync(t))return[];const r=[];try{const u=v.readdirSync(t,{withFileTypes:!0});for(const d of u){const c=g.join(t,d.name);if((d.isFile()||d.isSymbolicLink())&&de(d.name)){r.push(c);continue}if(d.isDirectory()||d.isSymbolicLink()){const a=U(c);a&&r.push(...a)}}}catch{return[]}return r}i(k,"discoverExtensionsInDir");async function Me(t,r,u=_(),d){const c=y(r),a=y(u),o=[],l=new Set,n=i(m=>{for(const e of m){const s=g.resolve(e);l.has(s)||(l.add(s),o.push(e))}},"addPaths"),p=g.join(c,B,"extensions");n(k(p));const f=g.join(a,"extensions");n(k(f));for(const m of t){const e=y(m,c,{normalizeUnicodeSpaces:!0});if(v.existsSync(e)&&v.statSync(e).isDirectory()){const s=U(e);if(s){n(s);continue}n(k(e));continue}n([e])}return le(o,c,d)}i(Me,"discoverAndLoadExtensions");export{Q as EXTENSION_API_DECORATOR_SLOT,re as clearExtensionCache,ne as createExtensionRuntime,Me as discoverAndLoadExtensions,Se as loadExtensionFromFactory,le as loadExtensions,be as loadExtensionsCached};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g=Object.defineProperty;var o=(e,s)=>g(e,"name",{value:s,configurable:!0});const a={tools:["registerTool","getActiveTools","getAllTools","setActiveTools","isToolAllowed","getToolAllowlist","getToolDenylist"],commands:["registerCommand","registerShortcut","registerFlag","getFlag","getCommands"],session:["sendMessage","sendUserMessage","appendEntry","setSessionName","getSessionName","setLabel"],providers:["registerProvider","unregisterProvider","setModel","getThinkingLevel","setThinkingLevel","registerModelPickerEntry"],subprocess:["exec"]};function c(e,s){return`Extension did not declare pi.permissions "${e}"; ${s} is unavailable.`}o(c,"deniedPermissionMessage");function u(e,s){if(s===void 0)return e;const i=new Set(s),t={...e};for(const[n,l]of Object.entries(a))if(!i.has(n))for(const r of l){const d=o(()=>{throw new Error(c(n,String(r)))},"denied");t[r]=d}return t}o(u,"applyPermissionSurface");export{u as applyPermissionSurface,c as deniedPermissionMessage};
|
|
1
|
+
var g=Object.defineProperty;var o=(e,s)=>g(e,"name",{value:s,configurable:!0});const a={tools:["registerTool","getActiveTools","getAllTools","setActiveTools","isToolAllowed","getToolAllowlist","getToolDenylist"],commands:["registerCommand","registerShortcut","registerFlag","getFlag","getCommands"],session:["sendMessage","sendUserMessage","appendEntry","emitHostEvent","setSessionName","getSessionName","setLabel"],providers:["registerProvider","unregisterProvider","setModel","getThinkingLevel","setThinkingLevel","registerModelPickerEntry"],subprocess:["exec"]};function c(e,s){return`Extension did not declare pi.permissions "${e}"; ${s} is unavailable.`}o(c,"deniedPermissionMessage");function u(e,s){if(s===void 0)return e;const i=new Set(s),t={...e};for(const[n,l]of Object.entries(a))if(!i.has(n))for(const r of l){const d=o(()=>{throw new Error(c(n,String(r)))},"denied");t[r]=d}return t}o(u,"applyPermissionSurface");export{u as applyPermissionSurface,c as deniedPermissionMessage};
|