@oh-my-pi/pi-coding-agent 17.0.8 → 17.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (340) hide show
  1. package/CHANGELOG.md +87 -1
  2. package/README.md +1 -1
  3. package/dist/cli.js +5495 -5021
  4. package/dist/types/async/job-manager.d.ts +37 -1
  5. package/dist/types/cli/args.d.ts +2 -0
  6. package/dist/types/cli/bench-cli.d.ts +41 -0
  7. package/dist/types/commands/bench.d.ts +15 -3
  8. package/dist/types/commands/launch.d.ts +4 -0
  9. package/dist/types/config/__tests__/model-registry.test.d.ts +1 -0
  10. package/dist/types/config/model-registry.d.ts +30 -1
  11. package/dist/types/config/models-config-schema.d.ts +18 -6
  12. package/dist/types/config/models-config.d.ts +14 -5
  13. package/dist/types/config/provider-globals.d.ts +2 -2
  14. package/dist/types/config/service-tier.d.ts +5 -1
  15. package/dist/types/config/settings-schema.d.ts +350 -50
  16. package/dist/types/config/settings.d.ts +7 -0
  17. package/dist/types/dap/client.d.ts +20 -0
  18. package/dist/types/exec/bash-executor.d.ts +38 -0
  19. package/dist/types/exec/direnv.d.ts +33 -0
  20. package/dist/types/export/html/args.d.ts +15 -0
  21. package/dist/types/export/html/index.d.ts +11 -26
  22. package/dist/types/export/html/web-palette.d.ts +55 -116
  23. package/dist/types/extensibility/extensions/loader.d.ts +3 -0
  24. package/dist/types/extensibility/extensions/types.d.ts +17 -2
  25. package/dist/types/extensibility/legacy-pi-coding-agent-shim.d.ts +1 -0
  26. package/dist/types/extensibility/legacy-pi-tui-shim.d.ts +10 -0
  27. package/dist/types/extensibility/plugins/legacy-pi-compat.d.ts +14 -1
  28. package/dist/types/internal-urls/registry-helpers.d.ts +11 -0
  29. package/dist/types/live/controller.d.ts +40 -0
  30. package/dist/types/live/protocol.d.ts +85 -0
  31. package/dist/types/live/protocol.test.d.ts +1 -0
  32. package/dist/types/live/transport.d.ts +48 -0
  33. package/dist/types/live/visualizer.d.ts +33 -0
  34. package/dist/types/lsp/client.d.ts +18 -1
  35. package/dist/types/mcp/config-writer.test.d.ts +1 -0
  36. package/dist/types/mcp/manager.d.ts +6 -2
  37. package/dist/types/mcp/oauth-discovery.d.ts +2 -0
  38. package/dist/types/mcp/render.d.ts +2 -2
  39. package/dist/types/mcp/smithery-auth.d.ts +1 -1
  40. package/dist/types/mcp/smithery-auth.test.d.ts +1 -0
  41. package/dist/types/mcp/tool-bridge.d.ts +7 -3
  42. package/dist/types/mcp/types.d.ts +6 -0
  43. package/dist/types/memory-backend/tool-names.d.ts +2 -0
  44. package/dist/types/modes/components/login-dialog.d.ts +2 -2
  45. package/dist/types/modes/components/oauth-selector.d.ts +8 -0
  46. package/dist/types/modes/components/plan-review-overlay.d.ts +26 -0
  47. package/dist/types/modes/components/settings-defs.d.ts +8 -1
  48. package/dist/types/modes/components/status-line/component.jj-cache.test.d.ts +1 -0
  49. package/dist/types/modes/components/tool-execution.d.ts +9 -1
  50. package/dist/types/modes/controllers/command-controller.d.ts +1 -1
  51. package/dist/types/modes/controllers/event-controller.d.ts +6 -1
  52. package/dist/types/modes/controllers/live-command-controller.d.ts +14 -0
  53. package/dist/types/modes/controllers/mcp-command-controller.d.ts +3 -0
  54. package/dist/types/modes/interactive-mode.d.ts +5 -0
  55. package/dist/types/modes/rpc/rpc-client.d.ts +10 -1
  56. package/dist/types/modes/rpc/rpc-frame.d.ts +16 -0
  57. package/dist/types/modes/rpc/rpc-messages.d.ts +26 -0
  58. package/dist/types/modes/rpc/rpc-types.d.ts +40 -0
  59. package/dist/types/modes/setup-wizard/scenes/sign-in.d.ts +1 -1
  60. package/dist/types/modes/setup-wizard/scenes/types.d.ts +9 -1
  61. package/dist/types/modes/setup-wizard/scenes/web-search.d.ts +1 -1
  62. package/dist/types/modes/theme/theme.d.ts +1 -1
  63. package/dist/types/modes/types.d.ts +3 -1
  64. package/dist/types/modes/utils/context-usage.d.ts +12 -2
  65. package/dist/types/plan-mode/plan-files.d.ts +10 -0
  66. package/dist/types/registry/agent-lifecycle.d.ts +21 -9
  67. package/dist/types/registry/agent-registry.d.ts +11 -4
  68. package/dist/types/sdk.d.ts +15 -1
  69. package/dist/types/secrets/index.d.ts +15 -2
  70. package/dist/types/secrets/obfuscator.d.ts +113 -15
  71. package/dist/types/session/acp-permission-gate.d.ts +19 -0
  72. package/dist/types/session/agent-session-events.d.ts +84 -0
  73. package/dist/types/session/agent-session-types.d.ts +314 -0
  74. package/dist/types/session/agent-session.d.ts +120 -750
  75. package/dist/types/session/async-job-delivery.d.ts +28 -0
  76. package/dist/types/session/bash-runner.d.ts +75 -0
  77. package/dist/types/session/blob-store.d.ts +11 -1
  78. package/dist/types/session/blob-store.test.d.ts +1 -0
  79. package/dist/types/session/checkpoint-entries.d.ts +28 -0
  80. package/dist/types/session/eval-runner.d.ts +49 -0
  81. package/dist/types/session/irc-bridge.d.ts +46 -0
  82. package/dist/types/session/messages.d.ts +22 -0
  83. package/dist/types/session/model-controls.d.ts +180 -0
  84. package/dist/types/session/prewalk.d.ts +46 -0
  85. package/dist/types/session/queued-messages.d.ts +22 -0
  86. package/dist/types/session/redis-session-storage.d.ts +1 -0
  87. package/dist/types/session/retry-fallback-chains.d.ts +74 -0
  88. package/dist/types/session/role-models.d.ts +15 -0
  89. package/dist/types/session/session-advisors.d.ts +228 -0
  90. package/dist/types/session/session-entries.d.ts +8 -0
  91. package/dist/types/session/session-handoff.d.ts +70 -0
  92. package/dist/types/session/session-history-format.d.ts +6 -1
  93. package/dist/types/session/session-loader.d.ts +6 -4
  94. package/dist/types/session/session-maintenance.d.ts +246 -0
  95. package/dist/types/session/session-manager.d.ts +41 -0
  96. package/dist/types/session/session-memory.d.ts +56 -0
  97. package/dist/types/session/session-provider-boundary.d.ts +62 -0
  98. package/dist/types/session/session-stats.d.ts +48 -0
  99. package/dist/types/session/session-tools.d.ts +143 -0
  100. package/dist/types/session/session-workspace.d.ts +32 -0
  101. package/dist/types/session/stream-guards.d.ts +44 -0
  102. package/dist/types/session/todo-tracker.d.ts +56 -0
  103. package/dist/types/session/ttsr-coordinator.d.ts +51 -0
  104. package/dist/types/session/turn-recovery.d.ts +225 -0
  105. package/dist/types/system-prompt.d.ts +2 -0
  106. package/dist/types/task/executor.d.ts +4 -1
  107. package/dist/types/task/output-manager.d.ts +3 -1
  108. package/dist/types/task/types.d.ts +14 -0
  109. package/dist/types/tools/approval.d.ts +1 -0
  110. package/dist/types/tools/browser/launch.d.ts +5 -0
  111. package/dist/types/tools/hub/jobs.d.ts +1 -1
  112. package/dist/types/tools/image-gen.d.ts +4 -4
  113. package/dist/types/tools/image-providers.d.ts +38 -0
  114. package/dist/types/tools/index.d.ts +8 -0
  115. package/dist/types/tools/path-utils.d.ts +8 -0
  116. package/dist/types/tools/report-tool-issue.d.ts +24 -9
  117. package/dist/types/tools/todo.d.ts +10 -4
  118. package/dist/types/tools/xdev.d.ts +5 -1
  119. package/dist/types/tts/streaming-player.d.ts +14 -0
  120. package/dist/types/tts/vocalizer.d.ts +5 -0
  121. package/dist/types/utils/jj.d.ts +29 -0
  122. package/dist/types/utils/lang-from-path.d.ts +1 -0
  123. package/dist/types/utils/title-generator.d.ts +30 -0
  124. package/dist/types/vibe/runtime.d.ts +36 -8
  125. package/dist/types/web/search/index.d.ts +1 -1
  126. package/dist/types/web/search/provider.d.ts +15 -5
  127. package/dist/types/web/search/providers/firecrawl.d.ts +9 -0
  128. package/dist/types/web/search/types.d.ts +95 -1
  129. package/package.json +13 -12
  130. package/scripts/generate-share-viewer.ts +4 -6
  131. package/scripts/legacy-pi-virtual-module.ts +1 -1
  132. package/src/advisor/__tests__/advisor.test.ts +643 -0
  133. package/src/advisor/runtime.ts +144 -43
  134. package/src/async/job-manager.ts +90 -2
  135. package/src/cli/args.ts +2 -0
  136. package/src/cli/auth-gateway-cli.ts +18 -3
  137. package/src/cli/bench-cli.ts +395 -29
  138. package/src/cli/flag-tables.ts +3 -0
  139. package/src/cli/gc-cli.ts +2 -2
  140. package/src/cli/grievances-cli.ts +2 -2
  141. package/src/cli/usage-cli.ts +11 -2
  142. package/src/collab/host.ts +3 -2
  143. package/src/commands/bench.ts +18 -4
  144. package/src/commands/launch.ts +4 -0
  145. package/src/config/__tests__/model-registry.test.ts +147 -0
  146. package/src/config/model-registry.ts +50 -2
  147. package/src/config/model-resolver.ts +0 -1
  148. package/src/config/models-config-schema.ts +15 -4
  149. package/src/config/provider-globals.ts +9 -9
  150. package/src/config/service-tier.ts +26 -1
  151. package/src/config/settings-schema.ts +250 -54
  152. package/src/config/settings.ts +81 -2
  153. package/src/dap/client.ts +37 -4
  154. package/src/edit/index.ts +49 -12
  155. package/src/eval/py/executor.ts +103 -33
  156. package/src/exec/bash-executor.ts +89 -6
  157. package/src/exec/direnv.ts +145 -0
  158. package/src/export/html/args.ts +20 -0
  159. package/src/export/html/index.ts +45 -47
  160. package/src/export/html/template.css +19 -1
  161. package/src/export/html/template.html +6 -0
  162. package/src/export/html/template.js +21 -0
  163. package/src/export/html/tool-views.generated.js +31 -31
  164. package/src/export/html/web-palette.ts +116 -132
  165. package/src/export/share.ts +249 -49
  166. package/src/extensibility/extensions/loader.ts +29 -1
  167. package/src/extensibility/extensions/runner.ts +6 -0
  168. package/src/extensibility/extensions/types.ts +33 -2
  169. package/src/extensibility/legacy-pi-coding-agent-shim.ts +1 -0
  170. package/src/extensibility/legacy-pi-tui-shim.ts +10 -0
  171. package/src/extensibility/plugins/legacy-pi-compat.ts +870 -311
  172. package/src/hindsight/state.ts +64 -6
  173. package/src/internal-urls/local-protocol.ts +2 -1
  174. package/src/internal-urls/memory-protocol.ts +2 -2
  175. package/src/internal-urls/registry-helpers.ts +40 -0
  176. package/src/internal-urls/skill-protocol.ts +2 -2
  177. package/src/internal-urls/ssh-protocol.ts +2 -1
  178. package/src/internal-urls/vault-protocol.ts +2 -1
  179. package/src/live/audio-worklet.txt +59 -0
  180. package/src/live/browser-runtime.txt +221 -0
  181. package/src/live/controller.ts +464 -0
  182. package/src/live/prompts/agent-final-message.md +3 -0
  183. package/src/live/prompts/live-instructions.md +23 -0
  184. package/src/live/protocol.test.ts +140 -0
  185. package/src/live/protocol.ts +233 -0
  186. package/src/live/transport.ts +490 -0
  187. package/src/live/visualizer.ts +234 -0
  188. package/src/lsp/client.ts +52 -9
  189. package/src/lsp/clients/biome-client.ts +3 -4
  190. package/src/lsp/index.ts +44 -11
  191. package/src/main.ts +9 -1
  192. package/src/mcp/config-writer.test.ts +43 -0
  193. package/src/mcp/config-writer.ts +109 -82
  194. package/src/mcp/manager.ts +39 -8
  195. package/src/mcp/oauth-discovery.ts +10 -2
  196. package/src/mcp/render.ts +94 -35
  197. package/src/mcp/smithery-auth.test.ts +29 -0
  198. package/src/mcp/smithery-auth.ts +3 -2
  199. package/src/mcp/tool-bridge.ts +107 -11
  200. package/src/mcp/types.ts +7 -0
  201. package/src/memories/index.ts +40 -20
  202. package/src/memory-backend/tool-names.ts +2 -0
  203. package/src/mnemopi/backend.ts +24 -7
  204. package/src/modes/acp/acp-agent.ts +56 -10
  205. package/src/modes/acp/acp-event-mapper.ts +8 -1
  206. package/src/modes/components/agent-hub.ts +27 -10
  207. package/src/modes/components/login-dialog.ts +14 -4
  208. package/src/modes/components/oauth-selector.ts +24 -7
  209. package/src/modes/components/plan-review-overlay.ts +350 -35
  210. package/src/modes/components/settings-defs.ts +28 -3
  211. package/src/modes/components/settings-selector.ts +178 -6
  212. package/src/modes/components/status-line/component.jj-cache.test.ts +229 -0
  213. package/src/modes/components/status-line/component.ts +123 -2
  214. package/src/modes/components/tool-execution.test.ts +63 -2
  215. package/src/modes/components/tool-execution.ts +11 -2
  216. package/src/modes/controllers/command-controller.ts +70 -22
  217. package/src/modes/controllers/event-controller.ts +111 -16
  218. package/src/modes/controllers/extension-ui-controller.test.ts +1 -0
  219. package/src/modes/controllers/extension-ui-controller.ts +20 -4
  220. package/src/modes/controllers/live-command-controller.ts +178 -0
  221. package/src/modes/controllers/mcp-command-controller.ts +80 -41
  222. package/src/modes/controllers/omfg-controller.ts +44 -40
  223. package/src/modes/controllers/selector-controller.ts +18 -10
  224. package/src/modes/controllers/session-focus-controller.ts +6 -1
  225. package/src/modes/interactive-mode.ts +160 -38
  226. package/src/modes/rpc/rpc-client.ts +94 -3
  227. package/src/modes/rpc/rpc-frame.ts +164 -4
  228. package/src/modes/rpc/rpc-messages.ts +127 -0
  229. package/src/modes/rpc/rpc-mode.ts +79 -7
  230. package/src/modes/rpc/rpc-types.ts +34 -2
  231. package/src/modes/runtime-init.ts +2 -0
  232. package/src/modes/setup-wizard/scenes/model.ts +5 -7
  233. package/src/modes/setup-wizard/scenes/providers.ts +3 -2
  234. package/src/modes/setup-wizard/scenes/sign-in.ts +8 -2
  235. package/src/modes/setup-wizard/scenes/theme.ts +13 -3
  236. package/src/modes/setup-wizard/scenes/types.ts +9 -1
  237. package/src/modes/setup-wizard/scenes/web-search.ts +23 -10
  238. package/src/modes/setup-wizard/wizard-overlay.ts +1 -1
  239. package/src/modes/theme/theme.ts +1 -1
  240. package/src/modes/types.ts +3 -1
  241. package/src/modes/utils/context-usage.ts +23 -7
  242. package/src/modes/utils/ui-helpers.ts +10 -5
  243. package/src/plan-mode/plan-files.ts +40 -0
  244. package/src/prompts/bench/cache-prefix-chunk.md +1 -0
  245. package/src/prompts/bench/cache-prefix.md +3 -0
  246. package/src/prompts/bench/cache-suffix.md +1 -0
  247. package/src/prompts/goals/guided-goal-system.md +24 -3
  248. package/src/prompts/system/custom-system-prompt.md +1 -1
  249. package/src/prompts/system/project-prompt.md +8 -1
  250. package/src/prompts/system/subagent-async-pending.md +6 -0
  251. package/src/prompts/system/system-prompt.md +1 -1
  252. package/src/prompts/system/workflow-notice.md +48 -40
  253. package/src/prompts/system/xdev-mount-notice.md +4 -0
  254. package/src/prompts/tools/task.md +12 -2
  255. package/src/prompts/tools/todo.md +3 -1
  256. package/src/registry/agent-lifecycle.ts +116 -46
  257. package/src/registry/agent-registry.ts +35 -8
  258. package/src/registry/persisted-agents.ts +26 -2
  259. package/src/sdk.ts +255 -139
  260. package/src/secrets/index.ts +127 -4
  261. package/src/secrets/obfuscator.ts +2328 -105
  262. package/src/session/acp-permission-gate.ts +165 -0
  263. package/src/session/agent-session-error-log.test.ts +1 -1
  264. package/src/session/agent-session-events.ts +66 -0
  265. package/src/session/agent-session-types.ts +334 -0
  266. package/src/session/agent-session.ts +1910 -12213
  267. package/src/session/artifacts.ts +6 -5
  268. package/src/session/async-job-delivery.ts +74 -0
  269. package/src/session/bash-runner.ts +326 -0
  270. package/src/session/blob-store.test.ts +56 -0
  271. package/src/session/blob-store.ts +18 -2
  272. package/src/session/checkpoint-entries.ts +81 -0
  273. package/src/session/eval-runner.ts +212 -0
  274. package/src/session/indexed-session-storage.ts +9 -2
  275. package/src/session/irc-bridge.ts +203 -0
  276. package/src/session/messages.ts +263 -1
  277. package/src/session/model-controls.ts +714 -0
  278. package/src/session/prewalk.ts +252 -0
  279. package/src/session/queued-messages.ts +93 -0
  280. package/src/session/redis-session-storage.ts +51 -11
  281. package/src/session/retry-fallback-chains.ts +455 -0
  282. package/src/session/role-models.ts +85 -0
  283. package/src/session/session-advisors.ts +1679 -0
  284. package/src/session/session-context.test.ts +224 -1
  285. package/src/session/session-context.ts +47 -5
  286. package/src/session/session-entries.ts +8 -0
  287. package/src/session/session-handoff.ts +308 -0
  288. package/src/session/session-history-format.ts +20 -9
  289. package/src/session/session-loader.ts +10 -51
  290. package/src/session/session-maintenance.ts +2983 -0
  291. package/src/session/session-manager.ts +390 -30
  292. package/src/session/session-memory.ts +222 -0
  293. package/src/session/session-provider-boundary.ts +307 -0
  294. package/src/session/session-stats.ts +293 -0
  295. package/src/session/session-tools.ts +943 -0
  296. package/src/session/session-workspace.ts +53 -0
  297. package/src/session/stream-guards.ts +417 -0
  298. package/src/session/todo-tracker.ts +380 -0
  299. package/src/session/ttsr-coordinator.ts +496 -0
  300. package/src/session/turn-recovery.ts +1629 -0
  301. package/src/slash-commands/builtin-registry.ts +92 -11
  302. package/src/slash-commands/helpers/usage-report.ts +25 -4
  303. package/src/system-prompt.ts +41 -17
  304. package/src/task/executor.ts +288 -70
  305. package/src/task/index.ts +148 -111
  306. package/src/task/output-manager.ts +25 -3
  307. package/src/task/persisted-revive.ts +4 -3
  308. package/src/task/structured-subagent.ts +4 -1
  309. package/src/task/types.ts +16 -0
  310. package/src/tools/approval.ts +55 -10
  311. package/src/tools/bash-interactive.ts +26 -0
  312. package/src/tools/bash-skill-urls.ts +28 -2
  313. package/src/tools/bash.ts +339 -123
  314. package/src/tools/browser/launch.ts +9 -1
  315. package/src/tools/browser/tab-supervisor.ts +8 -5
  316. package/src/tools/browser.ts +94 -47
  317. package/src/tools/hub/index.ts +1 -1
  318. package/src/tools/hub/jobs.ts +67 -8
  319. package/src/tools/image-gen.ts +20 -28
  320. package/src/tools/image-providers.ts +50 -0
  321. package/src/tools/index.ts +12 -0
  322. package/src/tools/path-utils.ts +49 -2
  323. package/src/tools/read.ts +156 -88
  324. package/src/tools/renderers.ts +7 -1
  325. package/src/tools/report-tool-issue.ts +79 -28
  326. package/src/tools/todo.ts +101 -11
  327. package/src/tools/vibe.ts +1 -2
  328. package/src/tools/write.ts +51 -1
  329. package/src/tools/xdev.ts +67 -3
  330. package/src/tts/streaming-player.ts +62 -4
  331. package/src/tts/vocalizer.ts +18 -1
  332. package/src/utils/jj.ts +125 -4
  333. package/src/utils/lang-from-path.ts +7 -0
  334. package/src/utils/title-generator.ts +137 -1
  335. package/src/vibe/runtime.ts +852 -72
  336. package/src/web/search/index.ts +3 -6
  337. package/src/web/search/provider.ts +31 -16
  338. package/src/web/search/providers/firecrawl.ts +46 -13
  339. package/src/web/search/providers/xai.ts +7 -1
  340. package/src/web/search/types.ts +8 -1
@@ -0,0 +1,943 @@
1
+ import type { Agent, AgentTool } from "@oh-my-pi/pi-agent-core";
2
+ import type { Model } from "@oh-my-pi/pi-ai";
3
+ import { logger, prompt, stringProperty } from "@oh-my-pi/pi-utils";
4
+ import { reset as resetCapabilities } from "../capability";
5
+ import type { ModelRegistry } from "../config/model-registry";
6
+ import { formatModelString } from "../config/model-resolver";
7
+ import type { Settings, SkillsSettings } from "../config/settings";
8
+ import type { CustomTool, CustomToolContext } from "../extensibility/custom-tools/types";
9
+ import { CustomToolAdapter } from "../extensibility/custom-tools/wrapper";
10
+ import type { ExtensionRunner } from "../extensibility/extensions";
11
+ import { ExtensionToolWrapper } from "../extensibility/extensions/wrapper";
12
+ import { loadSkills, type Skill, type SkillWarning, setActiveSkills } from "../extensibility/skills";
13
+ import type { LocalProtocolOptions } from "../internal-urls";
14
+ import { resolveMemoryBackend } from "../memory-backend/resolve";
15
+ import { MEMORY_BACKEND_TOOL_NAMES } from "../memory-backend/tool-names";
16
+ import type { MemoryBackendStartOptions } from "../memory-backend/types";
17
+ import xdevMountNoticePrompt from "../prompts/system/xdev-mount-notice.md" with { type: "text" };
18
+ import { usesCodexTaskPrompt } from "../task/prompt-policy";
19
+ import { isMCPToolName, normalizeToolNames } from "../tools/builtin-names";
20
+ import { wrapToolWithMetaNotice } from "../tools/output-meta";
21
+ import { ToolAbortError, ToolError } from "../tools/tool-errors";
22
+ import { isMountableUnderXdev, type XdevRegistry } from "../tools/xdev";
23
+ import { type EditMode, resolveEditMode } from "../utils/edit-mode";
24
+ import { formatLocalCalendarDate } from "../utils/local-date";
25
+ import {
26
+ extractPermissionLocations,
27
+ getPermissionIntent,
28
+ PERMISSION_OPTIONS,
29
+ PERMISSION_OPTIONS_BY_ID,
30
+ PERMISSION_REQUIRED_TOOLS,
31
+ } from "./acp-permission-gate";
32
+ import type { ClientBridge, ClientBridgePermissionOutcome } from "./client-bridge";
33
+ import type { CustomMessage } from "./messages";
34
+ import type { SessionManager } from "./session-manager";
35
+
36
+ /** Capabilities borrowed from the owning AgentSession. */
37
+ export interface SessionToolsHost {
38
+ agent: Agent;
39
+ sessionManager: SessionManager;
40
+ settings: Settings;
41
+ modelRegistry: ModelRegistry;
42
+ extensionRunner(): ExtensionRunner | undefined;
43
+ clientBridge(): ClientBridge | undefined;
44
+ agentKind(): "main" | "sub";
45
+ isDisposed(): boolean;
46
+ isStreaming(): boolean;
47
+ queuedMessageCount(): number;
48
+ planModeEnabled(): boolean;
49
+ model(): Model | undefined;
50
+ memoryBackendSession(): MemoryBackendStartOptions["session"];
51
+ clearInheritedProviderPromptCacheKey(): void;
52
+ clearMemoryPromotionSnapshot(): void;
53
+ captureMemoryPromotionSnapshot(prompt: string[]): void;
54
+ emitNotice(level: "info" | "warning" | "error", message: string, source?: string): void;
55
+ notifyCommandMetadataChanged(): void;
56
+ localProtocolOptions(): LocalProtocolOptions;
57
+ }
58
+
59
+ interface SessionToolsOptions {
60
+ autoApprove?: boolean;
61
+ toolRegistry?: Map<string, AgentTool>;
62
+ createVibeTools?: () => AgentTool[];
63
+ builtInToolNames?: Iterable<string>;
64
+ presentationPinnedToolNames?: ReadonlySet<string>;
65
+ ensureWriteRegistered?: () => Promise<boolean>;
66
+ rebuildSystemPrompt?: (toolNames: string[], tools: Map<string, AgentTool>) => Promise<{ systemPrompt: string[] }>;
67
+ getLocalCalendarDate?: () => string;
68
+ getMcpServerInstructions?: () => Map<string, string> | undefined;
69
+ xdevRegistry?: XdevRegistry;
70
+ initialMountedXdevToolNames?: string[];
71
+ setActiveToolNames?: (names: Iterable<string>) => void;
72
+ baseSystemPrompt: string[];
73
+ skills?: Skill[];
74
+ skillWarnings?: SkillWarning[];
75
+ skillsSettings?: SkillsSettings;
76
+ skillsReloadable?: boolean;
77
+ }
78
+
79
+ const XDEV_MOUNT_NOTICE_MESSAGE_TYPE = "xdev-mount-notice";
80
+
81
+ /** Owns tool registration, presentation, prompt rebuilding, skills, and permissions. */
82
+ export class SessionTools {
83
+ readonly #host: SessionToolsHost;
84
+ #autoApprove: boolean;
85
+ #toolRegistry: Map<string, AgentTool>;
86
+ #createVibeTools: (() => AgentTool[]) | undefined;
87
+ #installedVibeToolNames = new Set<string>();
88
+ #builtInToolNames: Set<string>;
89
+ #rpcHostToolNames = new Set<string>();
90
+ #xdevRegistry: XdevRegistry | undefined;
91
+ #mountedXdevToolNames: Set<string>;
92
+ #pendingXdevMountDelta: { added: Set<string>; removed: Set<string> } | undefined;
93
+ #presentationPinnedToolNames: ReadonlySet<string> | undefined;
94
+ #runtimeSelectedToolNames: ReadonlySet<string> | undefined;
95
+ #baseSystemPrompt: string[];
96
+ #lastAppliedToolSignature: string | undefined;
97
+ #promptModelKey: string | undefined;
98
+ #rebuildSystemPrompt: SessionToolsOptions["rebuildSystemPrompt"];
99
+ #getLocalCalendarDate: () => string;
100
+ #getMcpServerInstructions: SessionToolsOptions["getMcpServerInstructions"];
101
+ #setActiveToolNames: SessionToolsOptions["setActiveToolNames"];
102
+ #ensureWriteRegistered: SessionToolsOptions["ensureWriteRegistered"];
103
+ #skills: Skill[];
104
+ #skillWarnings: SkillWarning[];
105
+ #skillsSettings: SkillsSettings | undefined;
106
+ #skillsReloadable: boolean;
107
+ #acpPermissionDecisions = new Map<string, "allow_always" | "reject_always">();
108
+
109
+ constructor(host: SessionToolsHost, options: SessionToolsOptions) {
110
+ this.#host = host;
111
+ this.#autoApprove = options.autoApprove === true;
112
+ this.#toolRegistry = options.toolRegistry ?? new Map();
113
+ this.#createVibeTools = options.createVibeTools;
114
+ this.#builtInToolNames = new Set(options.builtInToolNames ?? []);
115
+ this.#presentationPinnedToolNames = options.presentationPinnedToolNames;
116
+ this.#ensureWriteRegistered = options.ensureWriteRegistered;
117
+ this.#rebuildSystemPrompt = options.rebuildSystemPrompt;
118
+ this.#getLocalCalendarDate = options.getLocalCalendarDate ?? formatLocalCalendarDate;
119
+ this.#getMcpServerInstructions = options.getMcpServerInstructions;
120
+ this.#xdevRegistry = options.xdevRegistry;
121
+ this.#mountedXdevToolNames = new Set(options.initialMountedXdevToolNames ?? []);
122
+ this.#setActiveToolNames = options.setActiveToolNames;
123
+ this.#baseSystemPrompt = options.baseSystemPrompt;
124
+ this.#skills = options.skills ?? [];
125
+ this.#skillWarnings = options.skillWarnings ?? [];
126
+ this.#skillsSettings = options.skillsSettings;
127
+ this.#skillsReloadable = options.skillsReloadable ?? true;
128
+ this.#promptModelKey = this.#currentPromptModelKey();
129
+ }
130
+
131
+ /** Mutable registry shared with controller hosts that inspect available tools. */
132
+ get registry(): Map<string, AgentTool> {
133
+ return this.#toolRegistry;
134
+ }
135
+
136
+ /** Current stable base system prompt. */
137
+ get baseSystemPrompt(): string[] {
138
+ return this.#baseSystemPrompt;
139
+ }
140
+
141
+ /** Replaces the controller-owned base prompt without applying it to the agent. */
142
+ setBaseSystemPrompt(prompt: string[]): void {
143
+ this.#baseSystemPrompt = prompt;
144
+ }
145
+
146
+ /** Skills currently rendered into the system prompt. */
147
+ get skills(): Skill[] {
148
+ return this.#skills;
149
+ }
150
+
151
+ /** Diagnostics produced while loading the current skills. */
152
+ get skillWarnings(): SkillWarning[] {
153
+ return this.#skillWarnings;
154
+ }
155
+
156
+ /** Settings snapshot used for the current skill discovery. */
157
+ get skillsSettings(): SkillsSettings | undefined {
158
+ return this.#skillsSettings;
159
+ }
160
+
161
+ /** Drops cached per-session ACP `allow_always`/`reject_always` decisions. */
162
+ clearAcpPermissionDecisions(): void {
163
+ this.#acpPermissionDecisions.clear();
164
+ }
165
+
166
+ /** Re-wraps active and mounted tools after the ACP client changes. */
167
+ refreshAcpPermissionGates(): void {
168
+ this.#acpPermissionDecisions.clear();
169
+ const activeTools = this.getActiveToolNames()
170
+ .map(name => this.#toolRegistry.get(name))
171
+ .filter((tool): tool is AgentTool => tool !== undefined)
172
+ .map(tool => this.#wrapToolForAcpPermission(tool));
173
+ this.#host.agent.setTools(activeTools);
174
+ const mountedTools = [...this.#mountedXdevToolNames]
175
+ .map(name => this.#toolRegistry.get(name))
176
+ .filter((tool): tool is AgentTool => tool !== undefined)
177
+ .map(tool => this.#wrapToolForAcpPermission(tool));
178
+ this.#xdevRegistry?.reconcile(mountedTools);
179
+ }
180
+
181
+ #getActiveNonMCPToolNames(): string[] {
182
+ return this.getEnabledToolNames().filter(name => !isMCPToolName(name) && this.#toolRegistry.has(name));
183
+ }
184
+
185
+ /** Names of tools currently exposed at the top level. */
186
+ getActiveToolNames(): string[] {
187
+ return this.#host.agent.state.tools.map(t => t.name);
188
+ }
189
+
190
+ /** Enabled top-level and discoverable tool names. */
191
+ getEnabledToolNames(): string[] {
192
+ if (this.#mountedXdevToolNames.size === 0) return this.getActiveToolNames();
193
+ return [...this.getActiveToolNames(), ...this.#mountedXdevToolNames];
194
+ }
195
+
196
+ /** Names of dynamic tools mounted under `xd://`. */
197
+ getMountedXdevToolNames(): string[] {
198
+ return [...this.#mountedXdevToolNames];
199
+ }
200
+
201
+ /** Whether the edit tool is registered. */
202
+ get hasEditTool(): boolean {
203
+ return this.#toolRegistry.has("edit");
204
+ }
205
+
206
+ /** Looks up a registered tool by name. */
207
+ getToolByName(name: string): AgentTool | undefined {
208
+ return this.#toolRegistry.get(name);
209
+ }
210
+
211
+ /** Whether a registry entry came from a built-in factory. */
212
+ hasBuiltInTool(name: string): boolean {
213
+ return this.#builtInToolNames.has(name);
214
+ }
215
+
216
+ /** Names of every registered tool. */
217
+ getAllToolNames(): string[] {
218
+ return Array.from(this.#toolRegistry.keys());
219
+ }
220
+
221
+ #wrapRuntimeTool(tool: AgentTool): AgentTool {
222
+ const wrapped = wrapToolWithMetaNotice(tool);
223
+ const extensionRunner = this.#host.extensionRunner();
224
+ return extensionRunner ? new ExtensionToolWrapper(wrapped, extensionRunner) : wrapped;
225
+ }
226
+
227
+ /** Installs and activates the ephemeral vibe tool set. */
228
+ async activateVibeTools(baseToolNames: string[]): Promise<void> {
229
+ const createVibeTools = this.#createVibeTools;
230
+ if (!createVibeTools) {
231
+ throw new Error("Vibe tools are unavailable in this session.");
232
+ }
233
+
234
+ const tools = createVibeTools();
235
+ const vibeToolNames = tools.map(tool => tool.name);
236
+ if (new Set(vibeToolNames).size !== vibeToolNames.length) {
237
+ throw new Error("Vibe tool names must be unique.");
238
+ }
239
+
240
+ for (const tool of tools) {
241
+ if (this.#toolRegistry.has(tool.name)) continue;
242
+ this.#toolRegistry.set(tool.name, this.#wrapRuntimeTool(tool));
243
+ this.#builtInToolNames.add(tool.name);
244
+ this.#installedVibeToolNames.add(tool.name);
245
+ }
246
+
247
+ await this.applyActiveToolsByName([...new Set([...baseToolNames, ...vibeToolNames])]);
248
+ }
249
+
250
+ /** Uninstalls vibe tools and activates the replacement set. */
251
+ async deactivateVibeTools(nextToolNames: string[]): Promise<void> {
252
+ this.#uninstallVibeTools();
253
+ await this.applyActiveToolsByName(nextToolNames);
254
+ }
255
+
256
+ /** Removes vibe tools without restoring a source-session snapshot. */
257
+ async removeVibeToolsPreservingActive(): Promise<void> {
258
+ const removed = new Set(this.#installedVibeToolNames);
259
+ this.#uninstallVibeTools();
260
+ const nextActive = this.getActiveToolNames().filter(name => !removed.has(name));
261
+ await this.applyActiveToolsByName(nextActive);
262
+ }
263
+
264
+ #uninstallVibeTools(): void {
265
+ for (const name of this.#installedVibeToolNames) {
266
+ this.#toolRegistry.delete(name);
267
+ this.#builtInToolNames.delete(name);
268
+ }
269
+ this.#installedVibeToolNames.clear();
270
+ }
271
+
272
+ #getEditModeSession() {
273
+ return {
274
+ settings: this.#host.settings,
275
+ getActiveModelString: () => {
276
+ const model = this.#host.model();
277
+ return model ? formatModelString(model) : undefined;
278
+ },
279
+ } as const;
280
+ }
281
+
282
+ /** Resolves the edit mode for the active model and settings. */
283
+ resolveActiveEditMode(): EditMode {
284
+ return resolveEditMode(this.#getEditModeSession());
285
+ }
286
+
287
+ #currentPromptModelKey(): string | undefined {
288
+ const activeModel = this.#host.model();
289
+ const model = activeModel ? formatModelString(activeModel) : undefined;
290
+ if (!model || this.#host.settings.get("includeModelInPrompt")) return model;
291
+ return usesCodexTaskPrompt(model) ? "task-policy:gpt-5.6" : "task-policy:default";
292
+ }
293
+
294
+ /** Rebuilds model-dependent tool prompts after a model change. */
295
+ async syncAfterModelChange(previousEditMode: EditMode): Promise<void> {
296
+ const currentEditMode = this.resolveActiveEditMode();
297
+ const editModeChanged = previousEditMode !== currentEditMode && this.getActiveToolNames().includes("edit");
298
+ // The system prompt selects model-specific policy even when it does not display the model id.
299
+ const modelChanged = this.#currentPromptModelKey() !== this.#promptModelKey;
300
+ if (editModeChanged || modelChanged) {
301
+ await this.refreshBaseSystemPrompt();
302
+ }
303
+ }
304
+
305
+ /** Enabled MCP tools in their current presentation partition. */
306
+ getSelectedMCPToolNames(): string[] {
307
+ // Every connected MCP tool is enabled; presentation (top-level vs xd://) is
308
+ // decided by loadMode. Return the enabled MCP tools in the current set.
309
+ return this.getEnabledToolNames().filter(name => isMCPToolName(name) && this.#toolRegistry.has(name));
310
+ }
311
+
312
+ /**
313
+ * Wrap a tool with a permission-gate proxy when an ACP client is connected.
314
+ * Only wraps tools whose name is in PERMISSION_REQUIRED_TOOLS and only when
315
+ * the bridge exposes `requestPermission`. No-ops for all other cases.
316
+ *
317
+ * When the user has explicitly opted into `yolo` / auto-approve behavior (via
318
+ * the SDK/CLI `autoApprove` flag or a configured `tools.approvalMode: yolo`),
319
+ * skips the gate unless the per-tool policy explicitly requires a prompt or
320
+ * deny. The schema default is also `yolo`, so an explicit configuration or
321
+ * explicit session flag is required: default-config ACP sessions keep the
322
+ * client-side permission gate.
323
+ */
324
+ #wrapToolForAcpPermission<T extends AgentTool>(tool: T): T {
325
+ const bridge = this.#host.clientBridge();
326
+ // Match the capability+method gating pattern used by read/write/bash.
327
+ if (!bridge?.capabilities.requestPermission || !bridge.requestPermission) return tool;
328
+ if (PERMISSION_REQUIRED_TOOLS[tool.name] !== true) return tool;
329
+ // Skip the gate only on explicit yolo opt-in; honour per-tool policies
330
+ // that require a prompt or deny (matching the normal approval wrapper).
331
+ if (this.#isExplicitAutoApproveMode()) {
332
+ const userPolicies = (this.#host.settings.get("tools.approval") ?? {}) as Record<string, unknown>;
333
+ const toolPolicy = userPolicies[tool.name];
334
+ if (!toolPolicy || toolPolicy === "allow") return tool;
335
+ }
336
+ return new Proxy(tool, {
337
+ get: (target, prop) => {
338
+ if (prop !== "execute") return target[prop as keyof T];
339
+ return async (
340
+ toolCallId: string,
341
+ args: unknown,
342
+ signal: AbortSignal | undefined,
343
+ onUpdate: never,
344
+ ctx: never,
345
+ ) => {
346
+ const permissionIntent = getPermissionIntent(target.name, args);
347
+ if (!permissionIntent) {
348
+ return await target.execute(toolCallId, args as never, signal, onUpdate, ctx);
349
+ }
350
+ const command =
351
+ target.name === "bash" && args && typeof args === "object" && !Array.isArray(args)
352
+ ? stringProperty(args, "command")
353
+ : undefined;
354
+ const commandContent = command
355
+ ? [{ type: "content" as const, content: { type: "text" as const, text: `$ ${command}` } }]
356
+ : undefined;
357
+ // Short-circuit on persisted decisions.
358
+ const persisted = this.#acpPermissionDecisions.get(permissionIntent.cacheKey);
359
+ if (persisted === "allow_always") {
360
+ return await target.execute(toolCallId, args as never, signal, onUpdate, ctx);
361
+ }
362
+ if (persisted === "reject_always") {
363
+ throw new ToolError(`Tool call rejected by user (preference)`);
364
+ }
365
+ if (signal?.aborted) {
366
+ throw new ToolAbortError("Permission request cancelled");
367
+ }
368
+ type PermissionRaceResult =
369
+ | { kind: "permission"; outcome: ClientBridgePermissionOutcome }
370
+ | { kind: "aborted" };
371
+ const { promise: abortPromise, resolve: resolveAbort } = Promise.withResolvers<PermissionRaceResult>();
372
+ const onAbort = () => resolveAbort({ kind: "aborted" });
373
+ signal?.addEventListener("abort", onAbort, { once: true });
374
+ let raced: PermissionRaceResult;
375
+ try {
376
+ const permissionPromise = bridge.requestPermission!(
377
+ {
378
+ toolCallId,
379
+ toolName: target.name,
380
+ title: permissionIntent.title,
381
+ ...(target.name === "bash" ? { kind: "execute" } : {}),
382
+ status: "pending",
383
+ rawInput: args,
384
+ ...(commandContent ? { content: commandContent } : {}),
385
+ locations: extractPermissionLocations(
386
+ args,
387
+ this.#host.sessionManager.getCwd(),
388
+ permissionIntent.paths,
389
+ ),
390
+ },
391
+ PERMISSION_OPTIONS,
392
+ signal,
393
+ ).then(outcome => ({ kind: "permission" as const, outcome }));
394
+ raced = await Promise.race([permissionPromise, abortPromise]);
395
+ } finally {
396
+ signal?.removeEventListener("abort", onAbort);
397
+ }
398
+ if (raced.kind === "aborted" || signal?.aborted) {
399
+ throw new ToolAbortError("Permission request cancelled");
400
+ }
401
+ const outcome = raced.outcome;
402
+ if (outcome.outcome === "cancelled") {
403
+ throw new ToolAbortError("Permission request cancelled");
404
+ }
405
+ const selectedOption = PERMISSION_OPTIONS_BY_ID.get(outcome.optionId);
406
+ if (!selectedOption) {
407
+ throw new ToolError(`Tool permission response used unknown option ID: ${outcome.optionId}`);
408
+ }
409
+ if (selectedOption.kind === "allow_always") {
410
+ this.#acpPermissionDecisions.set(permissionIntent.cacheKey, "allow_always");
411
+ } else if (selectedOption.kind === "reject_always") {
412
+ this.#acpPermissionDecisions.set(permissionIntent.cacheKey, "reject_always");
413
+ }
414
+ if (selectedOption.kind === "reject_once" || selectedOption.kind === "reject_always") {
415
+ throw new ToolError(`Tool call rejected by user (${target.name})`);
416
+ }
417
+ return await target.execute(toolCallId, args as never, signal, onUpdate, ctx);
418
+ };
419
+ },
420
+ }) as T;
421
+ }
422
+
423
+ #isExplicitAutoApproveMode(): boolean {
424
+ return (
425
+ this.#autoApprove ||
426
+ (this.#host.settings.isConfigured("tools.approvalMode") &&
427
+ this.#host.settings.get("tools.approvalMode") === "yolo")
428
+ );
429
+ }
430
+
431
+ /** Applies an enabled tool set and reconciles its `xd://` partition. */
432
+ async applyActiveToolsByName(toolNames: string[]): Promise<void> {
433
+ toolNames = normalizeToolNames(toolNames);
434
+ const selectedTools = toolNames.flatMap(name => {
435
+ const tool = this.#toolRegistry.get(name);
436
+ return tool ? [{ name, tool }] : [];
437
+ });
438
+ const xdevReadAvailable = this.#builtInToolNames.has("read") && selectedTools.some(({ name }) => name === "read");
439
+ const isPresentationPinned = (name: string): boolean =>
440
+ this.#presentationPinnedToolNames?.has(name) === true || this.#runtimeSelectedToolNames?.has(name) === true;
441
+ const mountCandidates = selectedTools.filter(
442
+ ({ name, tool }) =>
443
+ this.#xdevRegistry !== undefined &&
444
+ xdevReadAvailable &&
445
+ !isPresentationPinned(name) &&
446
+ isMountableUnderXdev(tool),
447
+ );
448
+
449
+ let builtInWriteAvailable = this.#builtInToolNames.has("write");
450
+ if (mountCandidates.length > 0 && !builtInWriteAvailable) {
451
+ builtInWriteAvailable = (await this.#ensureWriteRegistered?.()) === true;
452
+ if (builtInWriteAvailable) this.#builtInToolNames.add("write");
453
+ }
454
+ const mountNames = builtInWriteAvailable ? new Set(mountCandidates.map(({ name }) => name)) : new Set<string>();
455
+ const tools: AgentTool[] = [];
456
+ const validToolNames: string[] = [];
457
+ const mountedTools: AgentTool[] = [];
458
+ for (const { name, tool } of selectedTools) {
459
+ if (mountNames.has(name)) {
460
+ mountedTools.push(this.#wrapToolForAcpPermission(tool));
461
+ } else {
462
+ tools.push(this.#wrapToolForAcpPermission(tool));
463
+ validToolNames.push(name);
464
+ }
465
+ }
466
+
467
+ const pinnedWrite = isPresentationPinned("write");
468
+ const activeDeferrableTool = tools.some(tool => tool.deferrable === true);
469
+ const transportNeeded = mountedTools.length > 0 || activeDeferrableTool || this.#host.planModeEnabled();
470
+ if (transportNeeded && !builtInWriteAvailable) {
471
+ builtInWriteAvailable = (await this.#ensureWriteRegistered?.()) === true;
472
+ if (builtInWriteAvailable) this.#builtInToolNames.add("write");
473
+ }
474
+ if (transportNeeded && builtInWriteAvailable) {
475
+ const write = this.#toolRegistry.get("write");
476
+ if (write && !validToolNames.includes("write")) {
477
+ tools.push(this.#wrapToolForAcpPermission(write));
478
+ validToolNames.push("write");
479
+ }
480
+ } else if (
481
+ !pinnedWrite &&
482
+ (this.#presentationPinnedToolNames !== undefined || this.#runtimeSelectedToolNames !== undefined)
483
+ ) {
484
+ const writeNameIndex = validToolNames.indexOf("write");
485
+ if (writeNameIndex >= 0 && this.#builtInToolNames.has("write")) validToolNames.splice(writeNameIndex, 1);
486
+ const writeToolIndex = tools.findIndex(tool => tool.name === "write" && this.#builtInToolNames.has("write"));
487
+ if (writeToolIndex >= 0) tools.splice(writeToolIndex, 1);
488
+ }
489
+
490
+ const previousMounted = this.#mountedXdevToolNames;
491
+ const previousMountedTools = [...previousMounted].flatMap(name => {
492
+ const tool = this.#xdevRegistry?.get(name);
493
+ return tool ? [tool] : [];
494
+ });
495
+ const previousActiveToolNames = this.getActiveToolNames();
496
+ this.#mountedXdevToolNames = new Set(mountedTools.map(tool => tool.name));
497
+ this.#xdevRegistry?.reconcile(mountedTools);
498
+ this.#setActiveToolNames?.(validToolNames);
499
+
500
+ let rebuiltSystemPrompt: string[] | undefined;
501
+ let rebuiltSignature: string | undefined;
502
+ try {
503
+ if (this.#rebuildSystemPrompt) {
504
+ const signature = this.#computeAppliedToolSignature(validToolNames, tools);
505
+ if (signature !== this.#lastAppliedToolSignature) {
506
+ const built = await this.#rebuildSystemPrompt(validToolNames, this.#toolRegistry);
507
+ rebuiltSystemPrompt = built.systemPrompt;
508
+ rebuiltSignature = signature;
509
+ }
510
+ }
511
+ } catch (error) {
512
+ this.#mountedXdevToolNames = previousMounted;
513
+ this.#xdevRegistry?.reconcile(previousMountedTools);
514
+ this.#setActiveToolNames?.(previousActiveToolNames);
515
+ throw error;
516
+ }
517
+
518
+ this.#notifyXdevMountDelta(previousMounted);
519
+ this.#host.agent.setTools(tools);
520
+ if (rebuiltSystemPrompt && rebuiltSignature) {
521
+ if (this.#lastAppliedToolSignature !== undefined) this.#host.clearInheritedProviderPromptCacheKey();
522
+ this.#baseSystemPrompt = rebuiltSystemPrompt;
523
+ this.#host.clearMemoryPromotionSnapshot();
524
+ this.#host.agent.setSystemPrompt(this.#baseSystemPrompt);
525
+ this.#lastAppliedToolSignature = rebuiltSignature;
526
+ this.#promptModelKey = this.#currentPromptModelKey();
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Record a mid-session `xd://` mount delta for the model without rewriting
532
+ * the system prompt: the prompt (and its provider cache prefix) stays
533
+ * byte-stable across MCP connects and disconnects. The delta is NOT steered
534
+ * immediately — a steered notice landing at a run's stop boundary (or while
535
+ * the session is idle) forces an unsolicited extra assistant turn — it is
536
+ * coalesced into {@link #pendingXdevMountDelta} and rides along with the
537
+ * next prompt (docs + schema stay one `read xd://<tool>` away). The full
538
+ * docs join the system prompt opportunistically on the next unrelated
539
+ * rebuild.
540
+ */
541
+ #notifyXdevMountDelta(previousMounted: ReadonlySet<string>): void {
542
+ const registry = this.#xdevRegistry;
543
+ if (!registry) return;
544
+ const current = this.#mountedXdevToolNames;
545
+ const addedNames = [...current].filter(name => !previousMounted.has(name));
546
+ const removedNames = [...previousMounted].filter(name => !current.has(name));
547
+ if (addedNames.length === 0 && removedNames.length === 0) return;
548
+ // Coalesce against the unannounced delta: an unmount cancels a pending
549
+ // mount the model never learned about, and a remount cancels a pending
550
+ // unmount.
551
+ const pending = this.#pendingXdevMountDelta ?? { added: new Set<string>(), removed: new Set<string>() };
552
+ for (const name of addedNames) {
553
+ if (!pending.removed.delete(name)) pending.added.add(name);
554
+ }
555
+ for (const name of removedNames) {
556
+ if (!pending.added.delete(name)) pending.removed.add(name);
557
+ }
558
+ this.#pendingXdevMountDelta = pending.added.size > 0 || pending.removed.size > 0 ? pending : undefined;
559
+ if (this.#host.settings.get("startup.quiet")) return;
560
+ const parts: string[] = [];
561
+ if (addedNames.length > 0) parts.push(`mounted ${addedNames.join(", ")}`);
562
+ if (removedNames.length > 0) parts.push(`unmounted ${removedNames.join(", ")}`);
563
+ this.#host.emitNotice("info", `xd://: ${parts.join("; ")}`, "xdev");
564
+ }
565
+
566
+ /** Consumes the hidden notice for unannounced `xd://` mount changes. */
567
+ takePendingXdevMountNotice(): CustomMessage | undefined {
568
+ const pending = this.#pendingXdevMountDelta;
569
+ if (!pending) return undefined;
570
+ this.#pendingXdevMountDelta = undefined;
571
+ const summaries = new Map(this.#xdevRegistry?.entries().map(entry => [entry.name, entry.summary]) ?? []);
572
+ const added = [...pending.added].map(name => ({ name, summary: summaries.get(name) ?? "" }));
573
+ const removed = [...pending.removed].map(name => ({ name }));
574
+ const docs = this.#xdevRegistry?.docsFor(
575
+ pending.added,
576
+ this.#host.settings.get("tools.xdevDocs"),
577
+ this.#host.settings.get("tools.xdevInlineDevices"),
578
+ );
579
+ return {
580
+ role: "custom",
581
+ customType: XDEV_MOUNT_NOTICE_MESSAGE_TYPE,
582
+ content: prompt.render(xdevMountNoticePrompt, { added, removed, docs }),
583
+ attribution: "agent",
584
+ display: false,
585
+ timestamp: Date.now(),
586
+ };
587
+ }
588
+
589
+ /** Rediscovers reloadable skills and refreshes prompt metadata. */
590
+ async refreshSkills(): Promise<void> {
591
+ if (!this.#skillsReloadable) {
592
+ return;
593
+ }
594
+
595
+ resetCapabilities();
596
+ const skillsSettings = this.#host.settings.getGroup("skills");
597
+ const discovered = await loadSkills({
598
+ ...skillsSettings,
599
+ cwd: this.#host.sessionManager.getCwd(),
600
+ disabledExtensions: this.#host.settings.get("disabledExtensions") ?? [],
601
+ });
602
+ this.#skills = discovered.skills;
603
+ this.#skillWarnings = discovered.warnings;
604
+ this.#skillsSettings = skillsSettings;
605
+
606
+ if (this.#host.agentKind() === "main") {
607
+ setActiveSkills(this.#skills);
608
+ }
609
+ await this.refreshBaseSystemPrompt();
610
+ this.#host.notifyCommandMetadataChanged();
611
+ }
612
+
613
+ /** Selects enabled tools, ignoring names absent from the registry. */
614
+ async setActiveToolsByName(toolNames: string[]): Promise<void> {
615
+ const normalized = normalizeToolNames(toolNames);
616
+ // Transport-write eligibility keys off the *current* active set: an ordinary
617
+ // selection change should not demote `write` unless it is already active.
618
+ await this.#applyToolPresentation(
619
+ normalized,
620
+ this.#mountedXdevToolNames,
621
+ this.getActiveToolNames().includes("write"),
622
+ );
623
+ }
624
+
625
+ /**
626
+ * Restore an enabled tool set with its exact top-level versus `xd://` partition.
627
+ *
628
+ * Both inputs are required because {@link setActiveToolsByName} only receives the
629
+ * enabled name list and classifies mounts from the current `#mountedXdevToolNames`.
630
+ * Rollback/restore callers must pass the snapshotted mounted subset so names that
631
+ * were top-level stay pinned (`#runtimeSelectedToolNames`) and names that were under
632
+ * `xd://` remain mount-eligible, even when the live mount set has drifted.
633
+ *
634
+ * Names outside `mountedToolNames` are pinned top-level for this application;
635
+ * names in the mounted subset remain eligible for xdev mounting. Delegates the
636
+ * actual apply through {@link applyActiveToolsByName} and restores the prior runtime
637
+ * selection if that apply throws.
638
+ */
639
+ async setActiveToolPresentation(toolNames: string[], mountedToolNames: string[]): Promise<void> {
640
+ const normalized = normalizeToolNames(toolNames);
641
+ // Restoration targets a snapshot, so write eligibility comes from the
642
+ // *target* set rather than whatever happens to be active mid-rollback.
643
+ await this.#applyToolPresentation(
644
+ normalized,
645
+ new Set(normalizeToolNames(mountedToolNames)),
646
+ normalized.includes("write"),
647
+ );
648
+ }
649
+
650
+ /**
651
+ * Shared body for {@link setActiveToolsByName} and {@link setActiveToolPresentation}:
652
+ * pins non-mounted names as the runtime selection (holding `write` back when it is
653
+ * transport-only) and applies the set, rolling the selection back if apply throws.
654
+ */
655
+ async #applyToolPresentation(
656
+ normalized: string[],
657
+ mounted: ReadonlySet<string>,
658
+ writeSelected: boolean,
659
+ ): Promise<void> {
660
+ const transportWriteActive =
661
+ writeSelected &&
662
+ this.#builtInToolNames.has("write") &&
663
+ this.#presentationPinnedToolNames?.has("write") !== true &&
664
+ this.#runtimeSelectedToolNames?.has("write") !== true &&
665
+ (mounted.size > 0 || this.#host.planModeEnabled());
666
+ const previousRuntimeSelectedToolNames = this.#runtimeSelectedToolNames;
667
+ this.#runtimeSelectedToolNames = new Set(
668
+ normalized.filter(name => !mounted.has(name) && !(name === "write" && transportWriteActive)),
669
+ );
670
+ try {
671
+ await this.applyActiveToolsByName(normalized);
672
+ } catch (error) {
673
+ this.#runtimeSelectedToolNames = previousRuntimeSelectedToolNames;
674
+ throw error;
675
+ }
676
+ }
677
+
678
+ /** Replaces memory-backend tools while preserving unrelated selections. */
679
+ async replaceMemoryTools(tools: AgentTool[]): Promise<void> {
680
+ const removed = new Set<string>(MEMORY_BACKEND_TOOL_NAMES.filter(name => this.#builtInToolNames.has(name)));
681
+ const nextActive = this.getEnabledToolNames().filter(name => !removed.has(name));
682
+ for (const name of removed) {
683
+ this.#toolRegistry.delete(name);
684
+ this.#builtInToolNames.delete(name);
685
+ }
686
+
687
+ for (const tool of tools) {
688
+ if (!MEMORY_BACKEND_TOOL_NAMES.some(name => name === tool.name) || this.#toolRegistry.has(tool.name)) {
689
+ continue;
690
+ }
691
+ const wrapped = this.#wrapRuntimeTool(tool);
692
+ this.#toolRegistry.set(wrapped.name, wrapped);
693
+ this.#builtInToolNames.add(wrapped.name);
694
+ nextActive.push(wrapped.name);
695
+ }
696
+ await this.applyActiveToolsByName([...new Set(nextActive)]);
697
+ }
698
+
699
+ /** Rebuilds the stable base prompt for the current tools and model. */
700
+ async refreshBaseSystemPrompt(): Promise<void> {
701
+ if (this.#host.isDisposed() || !this.#rebuildSystemPrompt) return;
702
+ const activeToolNames = this.getActiveToolNames();
703
+ this.#setActiveToolNames?.(activeToolNames);
704
+ const previousBaseSystemPrompt = this.#baseSystemPrompt;
705
+ const built = await this.#rebuildSystemPrompt(activeToolNames, this.#toolRegistry);
706
+ if (this.#host.isDisposed()) return;
707
+ this.#baseSystemPrompt = built.systemPrompt;
708
+ this.#host.clearMemoryPromotionSnapshot();
709
+ if (
710
+ previousBaseSystemPrompt.length !== this.#baseSystemPrompt.length ||
711
+ previousBaseSystemPrompt.some((part, index) => part !== this.#baseSystemPrompt[index])
712
+ ) {
713
+ this.#host.clearInheritedProviderPromptCacheKey();
714
+ }
715
+ this.#host.agent.setSystemPrompt(this.#baseSystemPrompt);
716
+ this.#promptModelKey = this.#currentPromptModelKey();
717
+ // Refresh the cached signature so a subsequent `applyActiveToolsByName` with
718
+ // the same tool set does not re-rebuild on top of the explicit refresh we
719
+ // just performed (and conversely, a different set forces a fresh rebuild).
720
+ const activeTools = activeToolNames
721
+ .map(name => this.#toolRegistry.get(name))
722
+ .filter((tool): tool is AgentTool => tool != null);
723
+ this.#lastAppliedToolSignature = this.#computeAppliedToolSignature(activeToolNames, activeTools);
724
+ }
725
+
726
+ /** Applies one-turn memory prompt injection before an agent run. */
727
+ async buildSystemPromptForAgentStart(promptText: string): Promise<string[]> {
728
+ const backend = await resolveMemoryBackend(this.#host.settings);
729
+ if (!backend.beforeAgentStartPrompt) return this.#baseSystemPrompt;
730
+
731
+ try {
732
+ const injected = await backend.beforeAgentStartPrompt(this.#host.memoryBackendSession(), promptText);
733
+ if (!injected) return this.#baseSystemPrompt;
734
+
735
+ const previousBaseSystemPrompt = this.#baseSystemPrompt;
736
+ try {
737
+ await this.refreshBaseSystemPrompt();
738
+ } catch (refreshErr) {
739
+ logger.debug("Memory backend prompt refresh after beforeAgentStartPrompt failed", {
740
+ backend: backend.id,
741
+ error: String(refreshErr),
742
+ });
743
+ }
744
+
745
+ if (
746
+ this.#baseSystemPrompt.length !== previousBaseSystemPrompt.length ||
747
+ this.#baseSystemPrompt.some((part, index) => part !== previousBaseSystemPrompt[index])
748
+ ) {
749
+ return this.#baseSystemPrompt;
750
+ }
751
+
752
+ this.#host.captureMemoryPromotionSnapshot(previousBaseSystemPrompt);
753
+ const stablePrompt = [...previousBaseSystemPrompt, injected];
754
+ this.#baseSystemPrompt = stablePrompt;
755
+ this.#host.agent.setSystemPrompt(stablePrompt);
756
+ return stablePrompt;
757
+ } catch (err) {
758
+ logger.debug("Memory backend beforeAgentStartPrompt failed", {
759
+ backend: backend.id,
760
+ error: String(err),
761
+ });
762
+ return this.#baseSystemPrompt;
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Compose a stable signature for the inputs that `rebuildSystemPrompt` reads.
768
+ * Two calls producing identical signatures are guaranteed to produce identical
769
+ * system prompt bytes, so the rebuild can be skipped.
770
+ *
771
+ * The signature covers:
772
+ * 1. Active tool names in order (the prompt renders them in this order).
773
+ * 2. Active tool labels, descriptions, and wire-visible names — all are
774
+ * rendered into the prompt body (see `system-prompt.md` `{{label}}: \`{{name}}\``
775
+ * and `toolPromptNames` in `buildSystemPrompt`). The wire name comes from
776
+ * `tool.customWireName` and overrides the internal name on the model wire
777
+ * (e.g. `edit` exposes itself as `apply_patch` to GPT-5 in apply_patch mode);
778
+ * a stale wire name would desync prompt guidance from actual tool routing.
779
+ * 3. When MCP discovery is on, every registry tool's name+label+description+
780
+ * customWireName, since `rebuildSystemPrompt` summarizes discoverable MCP
781
+ * tools that are not in the active set.
782
+ * 4. MCP server instructions text (per server), since `rebuildSystemPrompt`
783
+ * embeds these in the appended prompt under "## MCP Server Instructions".
784
+ * A server upgrade can change instructions while keeping tools identical.
785
+ *
786
+ * Settings-driven tool metadata is covered automatically: built-in tools that
787
+ * depend on settings expose `description`/`label` via getters (see `TaskTool`,
788
+ * `SearchToolBm25Tool`, `EditTool`), and the signature reads them live on every
789
+ * call - so a settings flip that mutates the rendered string differs the signature
790
+ * the next time {@link applyActiveToolsByName} runs. Do not refactor `describeTool`
791
+ * to cache per-tool strings without preserving this property.
792
+ *
793
+ * Inputs NOT covered: tool input schemas; memory instructions read from disk;
794
+ * and SDK-init-time closure constants in `sdk.ts` (`inlineToolDescriptors`,
795
+ * `eagerTasks`, `intentField`, `mcpDiscoveryEnabled`, `secretsEnabled`). The
796
+ * closure-captured ones cannot change at runtime regardless of skip behavior.
797
+ * For everything else, callers must explicitly call {@link refreshBaseSystemPrompt}
798
+ * after side-effecting changes; see the memory hooks and {@link syncAfterModelChange}.
799
+ *
800
+ * The current calendar date IS covered (appended as a segment) because
801
+ * `buildSystemPrompt` injects it into the prompt body (`Today is '{{date}}'`).
802
+ * Without this, a session spanning midnight with only tool-stable MCP
803
+ * reconnects would keep yesterday's date indefinitely.
804
+ */
805
+ #computeAppliedToolSignature(toolNames: string[], tools: AgentTool[]): string {
806
+ // Order-preserving join: any reorder must produce a different signature so
807
+ // the rebuild fires and the new tool list reaches the API.
808
+ const nameSegment = toolNames.join("\u0001");
809
+ const describeTool = (tool: AgentTool): string =>
810
+ `${tool.name}=${tool.label ?? ""}|${tool.description ?? ""}|${tool.customWireName ?? ""}`;
811
+ const descriptionSegment = tools.map(describeTool).join("\u0002");
812
+ let instructionsSegment = "";
813
+ const serverInstructions = this.#getMcpServerInstructions?.();
814
+ if (serverInstructions && serverInstructions.size > 0) {
815
+ // Sort by server name so transport flap order does not perturb the signature.
816
+ const entries: string[] = [];
817
+ for (const [server, instructions] of serverInstructions) {
818
+ entries.push(`${server}=${instructions}`);
819
+ }
820
+ entries.sort();
821
+ instructionsSegment = entries.join("\u0006");
822
+ }
823
+ // The xd:// device inventory is deliberately NOT part of the signature:
824
+ // a mount/unmount announces itself via `#notifyXdevMountDelta` instead of
825
+ // rewriting the system prompt, so MCP connects/disconnects keep the
826
+ // prompt (and its provider cache prefix) byte-stable. Rebuilds triggered
827
+ // by other inputs pick up the current device docs opportunistically.
828
+ const date = this.#getLocalCalendarDate();
829
+ return `${nameSegment}\u0003${descriptionSegment}\u0007${instructionsSegment}|${date}`;
830
+ }
831
+
832
+ /**
833
+ * Replace MCP tools in the registry and enable them immediately. Every
834
+ * connected MCP tool becomes available (mounted under `xd://` when that
835
+ * transport is active, else top-level). Lets `/mcp add/remove/reauth` take
836
+ * effect without restarting the session.
837
+ */
838
+ async refreshMCPTools(mcpTools: CustomTool[]): Promise<void> {
839
+ const existingNames = Array.from(this.#toolRegistry.keys());
840
+ const previousMcpTools = new Map(
841
+ existingNames.flatMap(name => {
842
+ const tool = this.#toolRegistry.get(name);
843
+ return isMCPToolName(name) && tool ? [[name, tool] as const] : [];
844
+ }),
845
+ );
846
+ for (const name of existingNames) {
847
+ if (isMCPToolName(name)) {
848
+ this.#toolRegistry.delete(name);
849
+ }
850
+ }
851
+
852
+ const getCustomToolContext = (): CustomToolContext => ({
853
+ sessionManager: this.#host.sessionManager,
854
+ modelRegistry: this.#host.modelRegistry,
855
+ model: this.#host.model(),
856
+ isIdle: () => !this.#host.isStreaming(),
857
+ hasQueuedMessages: () => this.#host.queuedMessageCount() > 0,
858
+ abort: () => {
859
+ this.#host.agent.abort();
860
+ },
861
+ settings: this.#host.settings,
862
+ localProtocolOptions: this.#host.localProtocolOptions(),
863
+ });
864
+
865
+ const extensionRunner = this.#host.extensionRunner();
866
+ for (const customTool of mcpTools) {
867
+ const wrapped = wrapToolWithMetaNotice(CustomToolAdapter.wrap(customTool, getCustomToolContext) as AgentTool);
868
+ const finalTool = (
869
+ extensionRunner ? new ExtensionToolWrapper(wrapped, extensionRunner) : wrapped
870
+ ) as AgentTool;
871
+ this.#toolRegistry.set(finalTool.name, finalTool);
872
+ }
873
+
874
+ // Every connected MCP tool is selected; centralized repartitioning owns
875
+ // presentation pins and write-transport activation/removal.
876
+ const nextActive = [...new Set([...this.#getActiveNonMCPToolNames(), ...mcpTools.map(tool => tool.name)])];
877
+ try {
878
+ await this.applyActiveToolsByName(nextActive);
879
+ } catch (error) {
880
+ for (const name of this.#toolRegistry.keys()) {
881
+ if (isMCPToolName(name)) this.#toolRegistry.delete(name);
882
+ }
883
+ for (const [name, tool] of previousMcpTools) this.#toolRegistry.set(name, tool);
884
+ throw error;
885
+ }
886
+ }
887
+
888
+ /** Replaces RPC host-owned tools and refreshes the active set before the next model call. */
889
+ async refreshRpcHostTools(rpcTools: AgentTool[]): Promise<void> {
890
+ const nextToolNames = rpcTools.map(tool => tool.name);
891
+ const uniqueToolNames = new Set(nextToolNames);
892
+ if (uniqueToolNames.size !== nextToolNames.length) {
893
+ throw new Error("RPC host tool names must be unique");
894
+ }
895
+
896
+ for (const name of uniqueToolNames) {
897
+ if (this.#toolRegistry.has(name) && !this.#rpcHostToolNames.has(name)) {
898
+ throw new Error(`RPC host tool "${name}" conflicts with an existing tool`);
899
+ }
900
+ }
901
+
902
+ const previousRpcHostToolNames = new Set(this.#rpcHostToolNames);
903
+ const previousActiveToolNames = this.getEnabledToolNames();
904
+ const previousRpcHostTools = new Map(
905
+ [...previousRpcHostToolNames].flatMap(name => {
906
+ const tool = this.#toolRegistry.get(name);
907
+ return tool ? [[name, tool] as const] : [];
908
+ }),
909
+ );
910
+ for (const name of previousRpcHostToolNames) {
911
+ this.#toolRegistry.delete(name);
912
+ }
913
+ this.#rpcHostToolNames.clear();
914
+
915
+ const extensionRunner = this.#host.extensionRunner();
916
+ for (const tool of rpcTools) {
917
+ const metaWrapped = wrapToolWithMetaNotice(tool);
918
+ const finalTool = (
919
+ extensionRunner ? new ExtensionToolWrapper(metaWrapped, extensionRunner) : metaWrapped
920
+ ) as AgentTool;
921
+ this.#toolRegistry.set(finalTool.name, finalTool);
922
+ this.#rpcHostToolNames.add(finalTool.name);
923
+ }
924
+
925
+ const activeNonRpcToolNames = previousActiveToolNames.filter(name => !previousRpcHostToolNames.has(name));
926
+ const preservedRpcToolNames = previousActiveToolNames.filter(
927
+ name => previousRpcHostToolNames.has(name) && this.#rpcHostToolNames.has(name),
928
+ );
929
+ const autoActivatedRpcToolNames = rpcTools
930
+ .filter(tool => !tool.hidden && !previousRpcHostToolNames.has(tool.name))
931
+ .map(tool => tool.name);
932
+ try {
933
+ await this.applyActiveToolsByName(
934
+ Array.from(new Set([...activeNonRpcToolNames, ...preservedRpcToolNames, ...autoActivatedRpcToolNames])),
935
+ );
936
+ } catch (error) {
937
+ for (const name of this.#rpcHostToolNames) this.#toolRegistry.delete(name);
938
+ this.#rpcHostToolNames = previousRpcHostToolNames;
939
+ for (const [name, tool] of previousRpcHostTools) this.#toolRegistry.set(name, tool);
940
+ throw error;
941
+ }
942
+ }
943
+ }