@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,2019 @@
1
+ /**
2
+ * BYOK (Bring Your Own Key) provider — talks to Anthropic's API directly
3
+ * using @anthropic-ai/sdk and a user-supplied API key. No `claude` binary,
4
+ * no Agent SDK wrapper, no OAuth. chroxy IS the agent.
5
+ *
6
+ * Motivation + scope: docs/decisions/2026-05-byok-provider-scope.md
7
+ * Audit: docs/audit-results/clarp-proxy-provider-viability/
8
+ *
9
+ * PR 2 (this file) adds tool execution: when the model emits a tool_use
10
+ * block, chroxy gates it through PermissionManager, dispatches to a local
11
+ * executor (byok-tool-executor.js), feeds the tool_result back, and loops
12
+ * until the model stops calling tools. Built-in tools: Read, Write, Edit,
13
+ * Bash, Glob, Grep (see byok-tools.js). MCP / Task / WebFetch are deferred
14
+ * to follow-ups #4048-#4051.
15
+ */
16
+
17
+ import Anthropic, { APIUserAbortError } from '@anthropic-ai/sdk'
18
+ import { join } from 'path'
19
+ import { homedir } from 'os'
20
+ import { BaseSession, buildBaseSessionOpts } from './base-session.js'
21
+ import { PermissionManager, wirePermissionManager } from './permission-manager.js'
22
+ import { createLogger } from './logger.js'
23
+ import { isOperatorTimeoutInRange } from './duration.js'
24
+ import {
25
+ ALLOWED_MODEL_IDS,
26
+ getModelPricing,
27
+ computePromptCostUsd,
28
+ } from './models.js'
29
+ import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
30
+ import { resolveAnthropicApiKey, maskApiKey } from './byok-credentials.js'
31
+ import { BILLING_CLASSES } from './billing-class.js'
32
+ import { translateSdkEvent } from './byok-event-translator.js'
33
+ import { BUILTIN_TOOLS, TASK_PERMISSION_MODE_LIST, TASK_PERMISSION_MODE_RANK } from './byok-tools.js'
34
+ import { executeBuiltinTool } from './byok-tool-executor.js'
35
+ import { loadClaudeMcpConfig, toMcpServerMetadata } from './byok-mcp-config.js'
36
+ import { MCPFleet, MCP_TOOL_PREFIX } from './byok-mcp-fleet.js'
37
+ import { getSubagentProfile, SUBAGENT_PROFILE_NAMES } from './byok-subagent-profiles.js'
38
+
39
+ const log = createLogger('byok-session')
40
+
41
+ // Default per-turn token cap. Mirrors what the spike used; the SDK accepts
42
+ // up to 200k for Opus 4.7. 64k is generous for typical chroxy turns and
43
+ // the model stops at end_turn long before this in practice.
44
+ const DEFAULT_MAX_TOKENS = 64000
45
+
46
+ // Hard cap on history length to prevent unbounded growth. Each entry is
47
+ // a Claude API message ({ role, content }). At 50 turns we're well within
48
+ // any model's context window before the SDK does its own pruning.
49
+ const MAX_HISTORY_TURNS = 50
50
+
51
+ // Safety cap on tool-use rounds within a single user turn. The model can
52
+ // legitimately need 5-10 tool calls for a complex task; 25 is a generous
53
+ // ceiling that still catches infinite loops if the model misbehaves.
54
+ // Hitting the cap surfaces a clear error to the model rather than running
55
+ // up an unbounded API bill.
56
+ const MAX_TOOL_ROUNDS = 25
57
+
58
+ // TTL for the per-session realpath cache used by validatePathWithinCwd
59
+ // in the tool executor. The cwd shouldn't change mid-session, but caching
60
+ // for 30s strikes a balance between safety (re-stat to catch a swap) and
61
+ // performance (don't re-realpath the same cwd on every file op).
62
+ const CWD_CACHE_TTL_MS = 30_000
63
+
64
+ export class ClaudeByokSession extends BaseSession {
65
+ // #5858: Claude-family flag — single source of truth for isClaudeProvider().
66
+ // DockerByokSession (docker-byok) extends this and correctly inherits it.
67
+ // NOTE: non-Claude providers that ALSO extend this for the agent loop
68
+ // (DeepSeekSession, OllamaSession, AnthropicCompatibleSession) MUST override
69
+ // `static claudeFamily = false` — their model ids validate strictly.
70
+ static claudeFamily = true
71
+
72
+ static get displayLabel() {
73
+ return 'Claude (API key — BYOK)'
74
+ }
75
+
76
+ static get dataDir() {
77
+ // BYOK does NOT depend on ~/.claude — no claude binary, no OAuth.
78
+ // Returning null tells getProviderDataDirs() to skip this provider
79
+ // when collecting workspace data dirs (#2965). Setting to home would
80
+ // pull every user dotfile into conversation-scanner's scope.
81
+ return null
82
+ }
83
+
84
+ static get capabilities() {
85
+ return {
86
+ // PR 2: tool execution enabled with permission gating via
87
+ // PermissionManager (same machinery as claude-sdk).
88
+ permissions: true,
89
+ inProcessPermissions: true,
90
+ modelSwitch: true,
91
+ permissionModeSwitch: true,
92
+ planMode: false,
93
+ // Still no cross-restart resume. _history is in-memory; #4047
94
+ // tracks a follow-up to persist + resume.
95
+ resume: false,
96
+ terminal: false,
97
+ // Thinking config supported by the SDK but not wired through the
98
+ // chroxy UI yet — leave off until the toggle lands.
99
+ thinkingLevel: false,
100
+ streaming: true,
101
+ // We rebuild the system prompt on every turn from
102
+ // _buildSystemPrompt(), so an activate/deactivate of a skill
103
+ // takes effect on the next user message. Same property as the
104
+ // SDK provider.
105
+ skillToggle: true,
106
+ }
107
+ }
108
+
109
+ static get customEvents() {
110
+ // tool_start / tool_result / tool_input_delta are surfaced per turn
111
+ // for the dashboard's tool-call bubble UI. permission_request /
112
+ // user_question / permission_resolved are re-emitted from
113
+ // PermissionManager and already known to the SessionManager
114
+ // forwarding pipeline, but list them here so the capability matrix
115
+ // reflects reality. tool_input_delta (#4080) MUST be in this list —
116
+ // session-manager.js:_wireSessionEvents reads `customEvents` to
117
+ // build the TRANSIENT_EVENTS set it bridges to `session_event`
118
+ // listeners; without it the emit fires on the local EventEmitter
119
+ // and never reaches ws-forwarding.
120
+ //
121
+ // #4049: agent_spawned / agent_completed are part of the built-in
122
+ // transient set in session-manager.js (so they already flow without
123
+ // being listed), but pin them here so the capability matrix /
124
+ // dashboard introspection reflect that this provider emits them
125
+ // when the Task tool dispatches a subagent.
126
+ //
127
+ // #5016: `agent_event` carries the child Task subagent's intermediate
128
+ // wire events (tool_start / tool_input_delta / tool_result /
129
+ // stream_delta) tagged with the parent `toolUseId` so the dashboard
130
+ // can render the child's progress as nested sub-bubbles under the
131
+ // parent's Task tool_call. The child's `result` is intentionally NOT
132
+ // forwarded — usage/cost folds into the parent's per-turn
133
+ // accumulator and the final summary text becomes the parent's
134
+ // Task tool_result content; replaying it as a nested event would
135
+ // double-render the same content.
136
+ return ['tool_start', 'tool_result', 'tool_input_delta', 'agent_spawned', 'agent_completed', 'agent_event']
137
+ }
138
+
139
+ /**
140
+ * Preflight check for `chroxy doctor`. Unlike claude-cli/claude-sdk,
141
+ * BYOK has NO binary dependency — pure HTTPS to api.anthropic.com.
142
+ * Required credential is the API key.
143
+ */
144
+ static get preflight() {
145
+ return {
146
+ label: 'Claude (BYOK)',
147
+ credentials: {
148
+ envVars: ['ANTHROPIC_API_KEY'],
149
+ hint: `set ANTHROPIC_API_KEY or save it in ${join(homedir(), '.chroxy', 'credentials.json')} (mode 0600)`,
150
+ optional: false,
151
+ },
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Resolve runtime auth state for the dashboard (#4769).
157
+ *
158
+ * BYOK checks ANTHROPIC_API_KEY env AND the ~/.chroxy/credentials.json
159
+ * file (mode 0600 enforced by the resolver). Both paths surface as
160
+ * source: 'env' because the dashboard's SettingsPanel tone legend only
161
+ * knows about 'oauth'|'env'|'missing'|'none' (SettingsPanel.tsx:316-320);
162
+ * the `detail` string disambiguates which path supplied the key.
163
+ *
164
+ * @param {NodeJS.ProcessEnv} env
165
+ * @param {{ cachedResolveCredentialFile: Function }} helpers
166
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string, billingClass:string}}
167
+ */
168
+ static resolveAuth(env, helpers) {
169
+ const credSpec = this.preflight.credentials
170
+ const envVars = credSpec.envVars
171
+ const hint = credSpec.hint || `set ${envVars.join(' or ')}`
172
+ const resolved = helpers.cachedResolveCredentialFile(
173
+ 'byok',
174
+ env.ANTHROPIC_API_KEY,
175
+ resolveAnthropicApiKey,
176
+ )
177
+ if (resolved.key) {
178
+ return {
179
+ ready: true,
180
+ source: 'env',
181
+ envVar: resolved.source === 'env' ? 'ANTHROPIC_API_KEY' : null,
182
+ envVars,
183
+ hint: '',
184
+ detail: `Anthropic API (${resolved.source === 'env' ? 'ANTHROPIC_API_KEY set' : '~/.chroxy/credentials.json'} — per-token billing)`,
185
+ // BYOK is always your own key, per-token — api-key in both eras
186
+ // (#5629 leaves this UNCHANGED).
187
+ billingClass: BILLING_CLASSES.API_KEY,
188
+ }
189
+ }
190
+ return {
191
+ ready: false,
192
+ source: 'none',
193
+ envVar: null,
194
+ envVars,
195
+ hint,
196
+ detail: `Anthropic API (${resolved.reason})`,
197
+ billingClass: BILLING_CLASSES.API_KEY,
198
+ }
199
+ }
200
+
201
+ static getFallbackModels() {
202
+ return CLAUDE_FALLBACK_MODELS
203
+ }
204
+
205
+ static getAllowedModels() {
206
+ return [...ALLOWED_MODEL_IDS]
207
+ }
208
+
209
+ /**
210
+ * Model registry hook. BYOK accepts any Anthropic model id the API
211
+ * accepts; reuse claude-* metadata since the ids are the same shape.
212
+ * Delegates to the shared claudeModelMetadata() helper (#6201 OCP).
213
+ */
214
+ static getModelMetadata(modelId) {
215
+ return claudeModelMetadata(modelId)
216
+ }
217
+
218
+ /**
219
+ * @param {object} [opts]
220
+ * @param {string} [opts.cwd] Working directory for tool execution.
221
+ * @param {string} [opts.model] Anthropic model id; falls back to `claude-opus-4-8`.
222
+ * @param {string} [opts.mcpConfigPath] Path to a Claude-style MCP config (default: `~/.claude.json` or `$CHROXY_CLAUDE_CONFIG`).
223
+ * Canonical name (#4449). Only the `mcpServers` block is read — the rest of the
224
+ * file is ignored. A previous `opts.claudeConfigPath` alias was removed because
225
+ * it was unused at every call site and added no semantics over `mcpConfigPath`:
226
+ * only the MCP portion of the file is consumed by this session, so a single
227
+ * "where does the MCP config live" knob is sufficient. Wider Claude-config
228
+ * overrides (system prompt, settings) can be added as distinct named opts when
229
+ * any of them are actually used.
230
+ * @param {number} [opts.mcpToolCallTimeoutMs] Per-tools/call timeout; null/undefined = MCPClient default (30s).
231
+ */
232
+ constructor(opts = {}) {
233
+ super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-byok' }))
234
+ // Anthropic SDK client; lazily instantiated in start() so unit tests
235
+ // can stub it via this._client = ... before start().
236
+ this._client = null
237
+ // In-memory conversation history. Each entry is a Claude API message
238
+ // ({ role: 'user'|'assistant', content: <string|array> }). The SDK
239
+ // accepts either shape for user/assistant turns.
240
+ this._history = []
241
+ // AbortController for the active stream so interrupt() can cancel.
242
+ this._abortController = null
243
+
244
+ // PermissionManager + event re-emission via the shared wiring (P2-9) so the
245
+ // dashboard / mobile permission UI and the audit log work uniformly across
246
+ // providers. ByokSession passes no pause/resume hooks (no result-timeout).
247
+ this._permissions = new PermissionManager({ log })
248
+ wirePermissionManager(this, this._permissions)
249
+
250
+ // Realpath cache used by the tool executor's path-safety check. One
251
+ // cache per session — fresh sessions don't reuse a stale cwd.
252
+ this._cwdRealCache = new Map()
253
+
254
+ // #4051: Per-session TodoWrite list. Keyed by todo id; the executor
255
+ // merges partial updates into this map so the model can update one
256
+ // item without re-listing the rest. Explicitly cleared in destroy()
257
+ // (#4137) so the Map doesn't survive if anything outside the session
258
+ // holds a closure capturing it.
259
+ this._todos = new Map()
260
+
261
+ // #4085: Per-session set of model ids we've already logged a
262
+ // "no pricing entry" warn for. Without this, a tool-heavy 50-turn
263
+ // session on an unknown model logs 50 identical warns — noise that
264
+ // drowns out signal. The set lives until destroy() (the session
265
+ // goes away). setModel() does NOT clear entries: a user switching
266
+ // unknown → known just stops adding; switching unknown → different-
267
+ // unknown adds a new entry (one warn for the new one). The
268
+ // semantically-correct invariant is "one warn per (session, model)
269
+ // pair" — not "one warn per current model."
270
+ this._pricingWarnedModels = new Set()
271
+
272
+ // #4080: Per-stream index→toolUseId map. Populated on
273
+ // `content_block_start` with `block.type === 'tool_use'` (where the
274
+ // SDK emits both the block index and the tool_use id) and queried on
275
+ // `tool_input_delta`, which only carries the index. Entry is deleted
276
+ // on `content_block_stop` so the map stays small even on multi-tool
277
+ // turns. The full map is cleared after the for-await loop in case
278
+ // the stream terminated without emitting a final stop for every
279
+ // block — kept inside the session (not the translator) per #4059's
280
+ // boundary call: the translator stays pure, stateful tracking lives
281
+ // here.
282
+ this._streamingIndexToToolUseId = new Map()
283
+
284
+ // #4080: toolUseIds whose permission_request is currently pending.
285
+ // Populated when this session re-emits permission_request (line
286
+ // ~165), drained on permission_resolved (line ~167). Consulted on
287
+ // tool_input_delta — if the same toolUseId already has a pending
288
+ // permission prompt, suppress the delta so the dashboard tool-call
289
+ // bubble doesn't flicker between "running…" and a partial-input
290
+ // preview while the user is deciding. (In the current single-round
291
+ // BYOK flow this is defensive: permission requests fire AFTER the
292
+ // stream ends, so a delta cannot race with a pending permission for
293
+ // the SAME toolUseId within one round. The check exists so a future
294
+ // mid-stream permission gate — or a permission carried across
295
+ // rounds for the same toolUseId — can't accidentally flicker the
296
+ // UI.) The PermissionManager keys its pending map by requestId, not
297
+ // toolUseId, so we maintain a separate Set on the session.
298
+ this._pendingPermissionToolUseIds = new Set()
299
+
300
+ // #4049: active subagent sessions spawned by the Task tool, keyed by
301
+ // toolUseId. interrupt() iterates this map to cascade the abort
302
+ // signal to every child; destroy() does the same to tear down each
303
+ // child's resources (PermissionManager, listeners, MCP fleet) so a
304
+ // long-running parent with many delegated tasks doesn't leak state.
305
+ // Each subagent is itself a full ClaudeByokSession and owns its own
306
+ // _subagentSessions map — nested Task → Task is naturally supported.
307
+ this._subagentSessions = new Map()
308
+
309
+ // #5056: routing table for subagent permission responses. When a Task
310
+ // subagent fires a permission_request (e.g. an MCP tool under approve
311
+ // mode), the pending entry lives in the CHILD's PermissionManager —
312
+ // not the parent's. The dashboard, however, only knows the parent
313
+ // session id (ws-permissions resolves against the parent), so a tap
314
+ // Approve/Deny lands on `parent.respondToPermission(requestId, ...)`.
315
+ // This map records `childRequestId -> childSession` while the prompt
316
+ // is outstanding so the parent can forward the response to the child
317
+ // whose PermissionManager actually holds it. Entries are added when
318
+ // the child's permission_request is relayed upward and removed on
319
+ // permission_resolved (or when the child is torn down), so a stale
320
+ // requestId can never resolve past its lifetime.
321
+ this._subagentPermissionRouting = new Map()
322
+
323
+ // #4049: per-turn accumulators for subagent (Task tool) usage + cost.
324
+ // Folded into the parent's result.usage / result.cost just before
325
+ // the result event fires so cost attribution stays on the user-
326
+ // facing session (acceptance criteria: "child tokens attributed to
327
+ // the parent session"). Reset in _finishTurn() on every exit path
328
+ // — success, error, abort — so a stale parent's totals can never
329
+ // leak into a future turn.
330
+ this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
331
+ this._subagentCostThisTurn = 0
332
+
333
+ // #5018: per-session built-in tool allowlist. Set by _executeTaskTool
334
+ // ONLY on child sessions spawned with a `subagent_type` profile that
335
+ // carries a restricted `toolSet`. When null (the default / unrestricted
336
+ // case), `_buildTools()` short-circuits the filter so non-subagent
337
+ // sessions and general-purpose subagents pay no observable cost.
338
+ this._allowedBuiltinToolNames = null
339
+
340
+ // #4076: MCP config discovery. Parses ~/.claude.json (or an
341
+ // override) for the `mcpServers` block. Parse-only at this stage —
342
+ // no child spawn, no tool wiring — those land in #4077/#4078/#4079.
343
+ // Malformed configs log a single warn per server and produce an
344
+ // empty list, so a corrupt user config can't take down session start.
345
+ //
346
+ // #4449: `mcpConfigPath` is the only supported override. The
347
+ // earlier `opts.claudeConfigPath` alias was redundant — this
348
+ // session only reads the `mcpServers` block, so a separate
349
+ // "whole Claude config" knob added no behavior over
350
+ // `mcpConfigPath` and had no callers. See constructor JSDoc.
351
+ const mcpConfig = loadClaudeMcpConfig(opts.mcpConfigPath)
352
+ for (const warning of mcpConfig.warnings) {
353
+ log.warn(`BYOK MCP config: ${warning}`)
354
+ }
355
+ this._mcpServerConfigs = mcpConfig.servers
356
+ this.mcpServers = Object.freeze(mcpConfig.servers.map(toMcpServerMetadata))
357
+ // #4077: MCPFleet is lazy — created in start() only if servers exist.
358
+ // Held here so destroy() can tear down even if start() never ran.
359
+ this._mcpFleet = null
360
+ // #5019: when a Task subagent borrows the parent's MCP fleet (the
361
+ // default behaviour for nested tool use — avoids per-spawn MCP
362
+ // child-process startup cost), it points _mcpFleet at the parent's
363
+ // already-running fleet and flips this flag to false. destroy() then
364
+ // skips fleet.destroy() so the parent's MCP children aren't killed
365
+ // when the subagent finishes. The parent always owns its own fleet.
366
+ this._ownsMcpFleet = true
367
+ // #4482: per-call MCP tools/call timeout (ms). null = use byok-mcp-client's
368
+ // DEFAULT_TOOL_CALL_TIMEOUT_MS (30s) via the destructured default in
369
+ // MCPFleet.callTool. Forwarded from session-manager via providerOpts →
370
+ // opts.mcpToolCallTimeoutMs. Same defensive guard as resultTimeoutMs:
371
+ // non-finite / non-positive (NaN, Infinity, 0, -1, strings) falls back
372
+ // to null because setTimeout coerces those to 0 ms and every MCP tool
373
+ // would look broken.
374
+ // #4517: ceiling check via `isOperatorTimeoutInRange` (same as the three
375
+ // sibling timeouts in #4509) — defends per-session BYOK assignment
376
+ // against an over-24h value that would survive session-manager (e.g.
377
+ // an embedder constructing ClaudeByokSession directly with a typoed opt).
378
+ this._mcpToolCallTimeoutMs =
379
+ isOperatorTimeoutInRange(opts.mcpToolCallTimeoutMs, { name: 'mcpToolCallTimeoutMs', log })
380
+ ? opts.mcpToolCallTimeoutMs
381
+ : null
382
+ // #4456: wall-clock cap on fleet.start(). null = use the fleet's
383
+ // DEFAULT_FLEET_START_CAP_MS (1500ms). Same defensive guard pattern
384
+ // as _mcpToolCallTimeoutMs.
385
+ this._mcpStartCapMs =
386
+ Number.isFinite(opts.mcpStartCapMs) && opts.mcpStartCapMs > 0
387
+ ? opts.mcpStartCapMs
388
+ : null
389
+ }
390
+
391
+ // Subclass seams (#4656 — DeepSeek). Overriding these four lets a
392
+ // sibling provider (DeepSeek's Anthropic-compatible endpoint, any
393
+ // other future Anthropic-compatible service) reuse this entire agent
394
+ // loop by swapping credentials, base URL, default model, and pricing
395
+ // table — no fork, no re-implementation of the streaming + tool +
396
+ // permission + MCP machinery.
397
+ get _defaultModel() {
398
+ return 'claude-opus-4-8'
399
+ }
400
+
401
+ _resolveCredentials() {
402
+ return resolveAnthropicApiKey()
403
+ }
404
+
405
+ _buildClient(apiKey) {
406
+ return new Anthropic({ apiKey })
407
+ }
408
+
409
+ _getPricing(model) {
410
+ return getModelPricing(model)
411
+ }
412
+
413
+ async start() {
414
+ if (this._client === null) {
415
+ // Spike (BYOK direct) confirmed the SDK's standard constructor
416
+ // works fine; baseURL defaults to api.anthropic.com.
417
+ const resolved = this._resolveCredentials()
418
+ if (!resolved.key) {
419
+ // Use the subclass's preflight label (or provider id) so the
420
+ // toast / error feed names the right provider. Pre-#4656 this
421
+ // was hardcoded "BYOK" — DeepSeek would inherit the misleading
422
+ // "BYOK credentials not found" string. Keep "BYOK" as the last
423
+ // resort in case a subclass declares neither preflight nor
424
+ // provider.
425
+ const label = this.constructor.preflight?.label || this._provider || 'BYOK'
426
+ this.emit('error', { message: `${label} credentials not found — ${resolved.reason}` })
427
+ return
428
+ }
429
+ this._apiKeySource = resolved.source
430
+ // Mask in logs — full key never appears on disk. logger.js redactor
431
+ // catches Bearer / sk-ant patterns as a defense in depth. The
432
+ // `this._provider` label keeps the line accurate when a subclass
433
+ // (#4656 — DeepSeek) reuses this start() through the four seams.
434
+ log.info(`${this._provider || 'BYOK'} session ready — key source=${this._apiKeySource} key=${maskApiKey(resolved.key)} model=${this.model || 'default'}`)
435
+ this._client = this._buildClient(resolved.key)
436
+ }
437
+
438
+ // #4077: spawn MCP children lazily on first start(). Errors during
439
+ // handshake are non-fatal — the dead client just contributes zero
440
+ // tools, identical to a server missing from config. We deliberately
441
+ // wait for fleet.start() so this.mcpServers + tools list are stable
442
+ // by the time we emit 'ready'.
443
+ if (this._mcpServerConfigs.length > 0 && this._mcpFleet === null) {
444
+ // #4457: pass the session's PermissionManager so the fleet can
445
+ // emit a trust prompt for new (name, command, args[0]) tuples.
446
+ // Tuples already trusted in ~/.chroxy/mcp-trust.json spawn directly
447
+ // with no prompt; denied tuples set state=DEAD without spawning.
448
+ // #4456: forward startCapMs override so operators can tune the
449
+ // session-start wall-clock cap. Passing undefined lets the fleet's
450
+ // constructor default (DEFAULT_FLEET_START_CAP_MS) win — exactly
451
+ // what we want when no override is in play.
452
+ const fleetOpts = { log, permissionManager: this._permissions }
453
+ if (this._mcpStartCapMs !== null) fleetOpts.startCapMs = this._mcpStartCapMs
454
+ this._mcpFleet = new MCPFleet(this._mcpServerConfigs, fleetOpts)
455
+ await this._mcpFleet.start()
456
+ }
457
+
458
+ this._processReady = true
459
+ this.emit('ready', { sessionId: null, model: this.model, tools: [] })
460
+ }
461
+
462
+ async sendMessage(prompt, attachments, _options = {}) {
463
+ if (this._isBusy) {
464
+ this.emit('error', { message: 'Already processing a message' })
465
+ return
466
+ }
467
+ if (this._destroying || !this._processReady || !this._client) {
468
+ this.emit('error', { message: 'Session not ready' })
469
+ return
470
+ }
471
+
472
+ this._isBusy = true
473
+ this._messageCounter += 1
474
+ const messageId = `${this._messageIdPrefix}-${this._messageCounter}`
475
+ this._currentMessageId = messageId
476
+ this._abortController = new AbortController()
477
+ const turnStartedAt = Date.now()
478
+
479
+ // Attachments — PR 2 still keeps these as a warn until Read can
480
+ // pick up materialised files. Tracked separately; not blocking.
481
+ if (Array.isArray(attachments) && attachments.length > 0) {
482
+ this.emit('error', {
483
+ messageId,
484
+ message: `BYOK provider does not yet materialise attachments (${attachments.length} dropped). Track follow-up: file-via-Read tool flow.`,
485
+ })
486
+ }
487
+
488
+ // Build the user message. On the very first turn, prepend any skills
489
+ // text from BaseSession._buildPrependPrompt(). Subsequent turns are
490
+ // plain prompt text — skills that targeted `system` ride on the
491
+ // rebuilt systemPrompt instead.
492
+ let userText = typeof prompt === 'string' ? prompt : String(prompt ?? '')
493
+ if (this._history.length === 0) {
494
+ const prepend = typeof this._buildPrependPrompt === 'function'
495
+ ? this._buildPrependPrompt()
496
+ : ''
497
+ if (prepend) {
498
+ userText = `${prepend}\n\n---\n\n${userText}`
499
+ }
500
+ }
501
+ this._history.push({ role: 'user', content: userText })
502
+
503
+ // Trim history if it grew past the cap. We drop from the head but
504
+ // keep pairs intact (user + assistant) so the wire never sees a
505
+ // half-turn opening.
506
+ while (this._history.length > MAX_HISTORY_TURNS * 2) {
507
+ this._history.splice(0, 2)
508
+ }
509
+
510
+ const systemPrompt = typeof this._buildSystemPrompt === 'function'
511
+ ? this._buildSystemPrompt()
512
+ : ''
513
+
514
+ this.emit('stream_start', { messageId })
515
+
516
+ // Agent loop. Each iteration:
517
+ // 1. Stream the next assistant turn (text + possibly tool_use blocks)
518
+ // 2. If the turn ended with stop_reason !== 'tool_use', break.
519
+ // 3. Otherwise, execute each tool_use block locally (with permission
520
+ // gating) and push a user message of tool_result blocks.
521
+ // 4. Loop back to (1).
522
+ // Bounded by MAX_TOOL_ROUNDS to catch infinite-loop misbehavior.
523
+
524
+ // Accumulate usage + cost across every agent-loop round so the result
525
+ // event reflects the WHOLE turn, not just the last round. Each round is
526
+ // a separate billable API request; without accumulation a 5-round
527
+ // tool-use turn reports only 1/5th of the actual cost (#4056).
528
+ const turnUsage = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
529
+ let turnCost = 0
530
+ // #5630: computePromptCostUsd now returns `null` (not 0) when pricing is
531
+ // unknown. Adding `null` to turnCost would make it NaN, so we guard every
532
+ // add and track whether ANY round produced a known cost. If no round did
533
+ // (pricing unknown for the model all turn), we emit `cost: null` so the
534
+ // dashboard shows "n/a" rather than a misleading $0.00 — distinct from a
535
+ // genuine zero-cost turn.
536
+ let turnCostKnown = false
537
+ const pricingModel = this.model || this._defaultModel
538
+ const pricing = this._getPricing(pricingModel)
539
+ if (!pricing && !this._pricingWarnedModels.has(pricingModel)) {
540
+ // #4085: warn at most once per (session, model) — not once per turn.
541
+ this._pricingWarnedModels.add(pricingModel)
542
+ log.warn(`no pricing entry for model=${pricingModel}; result.cost will be 0 — update CLAUDE_PRICING_USD_PER_MTOK in models.js`)
543
+ }
544
+ let lastStopReason = null
545
+ // Snapshot the pre-turn history length so any stream-init failure (at
546
+ // any round) can rollback the entire turn atomically. We derive it
547
+ // from the current length minus the user message we just pushed at
548
+ // L251 — clamped to 0 so this stays defensive if the trim above ever
549
+ // collapses history harder than expected. Pre-#4109 the rollback only
550
+ // ran at round 0, leaving a trailing tool_result `user` turn after a
551
+ // round-1+ failure — the next sendMessage would then push another
552
+ // `user` turn back-to-back, soft-breaking the alternation invariant
553
+ // the API may tighten on in future.
554
+ const historyLengthBeforeSend = Math.max(0, this._history.length - 1)
555
+
556
+ try {
557
+ for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
558
+ let stream
559
+ try {
560
+ stream = this._client.messages.stream(
561
+ {
562
+ model: this.model || this._defaultModel,
563
+ max_tokens: DEFAULT_MAX_TOKENS,
564
+ ...(systemPrompt ? { system: systemPrompt } : {}),
565
+ // #4078: merge BUILTIN_TOOLS with live MCP tools at turn time.
566
+ // fleet.anthropicTools filters DEAD servers, so a crashed-then-
567
+ // restart-exhausted MCP server cleanly disappears from the next
568
+ // turn without anything to invalidate.
569
+ tools: this._buildTools(),
570
+ messages: this._history,
571
+ },
572
+ { signal: this._abortController.signal },
573
+ )
574
+ } catch (err) {
575
+ // Stream init threw synchronously. Rollback the ENTIRE turn —
576
+ // the user prompt + every assistant/tool_result pair appended
577
+ // by completed rounds. Truncating to the pre-send length is
578
+ // simpler and stronger than the previous round-0-only pop:
579
+ // the next sendMessage starts from a known-clean state with no
580
+ // possibility of back-to-back user turns (#4109).
581
+ if (this._history.length > historyLengthBeforeSend) {
582
+ this._history.length = historyLengthBeforeSend
583
+ }
584
+ throw err
585
+ }
586
+
587
+ for await (const event of stream) {
588
+ const t = translateSdkEvent(event)
589
+ if (!t) continue
590
+ switch (t.kind) {
591
+ case 'stream_delta':
592
+ this.emit('stream_delta', { messageId, delta: t.text })
593
+ break
594
+ case 'tool_start': {
595
+ // Surface the tool_use opening to the dashboard so it can
596
+ // render a tool-call bubble. Matches sdk-session.js /
597
+ // cli-session.js shape — event-normalizer reads `tool`
598
+ // and `input` (ServerToolStartSchema requires `tool` as a
599
+ // non-null string). Pre-#4240 this emitted `toolName`,
600
+ // which the normalizer silently dropped, so the dashboard
601
+ // saw `tool: undefined` and rendered a generic bubble.
602
+ // `input` is null here because the model streams the
603
+ // tool's JSON input via subsequent input_json_delta
604
+ // events; tool_input_delta carries the partials.
605
+ //
606
+ // #4262: Use the tool's content_block.id as the tool_start
607
+ // messageId so each tool in a multi-tool turn has a distinct
608
+ // id. Sharing the turn-level messageId across tools collides
609
+ // with itself (store-core/handlers/handleToolStart uses
610
+ // messageId as ChatMessage.id, so later tools overwrite
611
+ // earlier ones in replay-dedupe) AND with the post-tool
612
+ // stream_start id (#stream_id_collision class). Mirrors
613
+ // sdk-session.js:635-641 / cli-session.js:708-714.
614
+ // #4364: Mirror sdk-session.js:635-641 — reuse the
615
+ // derived toolId for both fields so the wire schema
616
+ // (`ServerToolStartSchema.toolUseId: z.string()`) holds
617
+ // even on the defensive fallback path. Pre-#4364 this
618
+ // emitted `toolUseId: undefined` when content_block.id
619
+ // was absent; no observable runtime impact today (no
620
+ // broadcast-side validator) but the schema is the
621
+ // contract.
622
+ const toolId = t.toolUseId || `${messageId}-tool`
623
+ this.emit('tool_start', {
624
+ messageId: toolId,
625
+ toolUseId: toolId,
626
+ tool: t.toolName,
627
+ input: null,
628
+ })
629
+ // #4080: track index→toolUseId so the upcoming
630
+ // tool_input_delta events (which only carry the index)
631
+ // can be re-tagged with the toolUseId before re-emit.
632
+ if (typeof t.index === 'number' && t.toolUseId) {
633
+ this._streamingIndexToToolUseId.set(t.index, t.toolUseId)
634
+ }
635
+ break
636
+ }
637
+ case 'tool_input_delta': {
638
+ // #4080: stream the partial JSON to the dashboard so the
639
+ // tool-call bubble can live-preview the model's evolving
640
+ // input (especially valuable for Bash, where users can
641
+ // early-abort once they see a destructive `command`
642
+ // forming). The translator only carries the block index;
643
+ // resolve to toolUseId via the per-stream map we populated
644
+ // on tool_start.
645
+ const toolUseId = typeof t.index === 'number'
646
+ ? this._streamingIndexToToolUseId.get(t.index)
647
+ : undefined
648
+ if (!toolUseId) {
649
+ // Delta for a content block that wasn't a tool_use
650
+ // (text deltas already went through stream_delta) or
651
+ // for an index we never saw a start for (SDK reorder /
652
+ // malformed event). Drop quietly — the accepted shape
653
+ // for partial input is "may not arrive."
654
+ break
655
+ }
656
+ if (this._pendingPermissionToolUseIds.has(toolUseId)) {
657
+ // A permission prompt is pending for this exact
658
+ // toolUseId — suppress the delta so the bubble doesn't
659
+ // flicker between "running…" and partial-input while
660
+ // the user is mid-decision. See constructor comment.
661
+ break
662
+ }
663
+ this.emit('tool_input_delta', {
664
+ messageId,
665
+ toolUseId,
666
+ partialJson: t.partial,
667
+ })
668
+ break
669
+ }
670
+ case 'content_block_stop':
671
+ // #4080: free the per-index slot as soon as the block
672
+ // finishes so a long turn's map doesn't grow unbounded.
673
+ // Safe to delete even if index isn't in the map — that
674
+ // just means we never tracked this block (text /
675
+ // thinking) and the lookup is a no-op.
676
+ if (typeof t.index === 'number') {
677
+ this._streamingIndexToToolUseId.delete(t.index)
678
+ }
679
+ break
680
+ case 'message_delta':
681
+ if (t.stopReason) lastStopReason = t.stopReason
682
+ // Don't accumulate from message_delta — it carries the
683
+ // round's running totals that culminate in final.usage. We
684
+ // accumulate exactly once per round below, after
685
+ // finalMessage() resolves.
686
+ break
687
+ case 'unknown':
688
+ log.warn(`unknown SDK event type=${t.sdkType} forwarded as no-op`)
689
+ break
690
+ default:
691
+ break
692
+ }
693
+ }
694
+
695
+ const final = await stream.finalMessage()
696
+ // #4080: defensive cleanup. content_block_stop should have
697
+ // drained every entry above, but if the stream ended on an
698
+ // error path or the SDK ever skips the stop event for a
699
+ // block, the map would leak across rounds and a later
700
+ // tool_input_delta for index N could pick up a STALE
701
+ // toolUseId from the previous round. Clear here so each round
702
+ // starts with an empty per-stream map.
703
+ this._streamingIndexToToolUseId.clear()
704
+ lastStopReason = final.stop_reason
705
+ const roundUsage = final.usage || {}
706
+ turnUsage.input_tokens += Number(roundUsage.input_tokens) || 0
707
+ turnUsage.output_tokens += Number(roundUsage.output_tokens) || 0
708
+ turnUsage.cache_read_input_tokens += Number(roundUsage.cache_read_input_tokens) || 0
709
+ turnUsage.cache_creation_input_tokens += Number(roundUsage.cache_creation_input_tokens) || 0
710
+ // #5630: skip a null (unknown) cost so turnCost never becomes NaN;
711
+ // a non-null value marks the turn cost as known.
712
+ {
713
+ const c = computePromptCostUsd(roundUsage, pricing)
714
+ if (c !== null) { turnCost += c; turnCostKnown = true }
715
+ }
716
+
717
+ // Append the assistant turn — full content array preserves
718
+ // tool_use blocks for the next round of conversation.
719
+ this._history.push({ role: 'assistant', content: final.content })
720
+
721
+ if (lastStopReason !== 'tool_use') {
722
+ // Done — model wants no more tools. Break out and emit result.
723
+ break
724
+ }
725
+
726
+ // Execute each tool_use block. Build a tool_result content array
727
+ // to send back as the user message.
728
+ //
729
+ // #4061 history invariant: the Anthropic API rejects (400) any
730
+ // assistant turn that contains tool_use blocks unless the
731
+ // immediately-following user message has a tool_result for EVERY
732
+ // tool_use id. If the user aborts mid-loop, we have to synthesize
733
+ // tool_result blocks for the unexecuted remainder so the next
734
+ // sendMessage doesn't 400 on a mismatched history.
735
+ //
736
+ // #4062: when the model emits multiple tool_use blocks in one
737
+ // turn (parallel tool calls — common for 3 unrelated Reads), we
738
+ // execute them concurrently to save wall-clock latency. Two
739
+ // distinct phases:
740
+ //
741
+ // 1. PERMISSION GATE — strictly sequential. The user can't
742
+ // answer N prompts simultaneously on the phone, and the
743
+ // dashboard's permission_request handler assumes one prompt
744
+ // at a time. Auto-allow / session-rule decisions resolve
745
+ // synchronously, so this phase is effectively free when no
746
+ // real prompt fires.
747
+ //
748
+ // 2. EXECUTION — fanned out via Promise.all on every approved
749
+ // block. Denied blocks short-circuit to a synthetic
750
+ // tool_result. Order is preserved by index so the API sees
751
+ // tool_results in the same order as the tool_uses.
752
+ //
753
+ // Abort handling: if the signal trips DURING the gate phase, we
754
+ // stop gating and the unscheduled remainder gets a synthetic
755
+ // 'Interrupted' tool_result (same #4061 invariant). If it trips
756
+ // mid-execution, the shared AbortSignal propagates to
757
+ // executeBuiltinTool and any in-flight tool aborts cleanly.
758
+ const toolBlocks = (final.content || []).filter((b) => b?.type === 'tool_use')
759
+ const toolResults = await this._processToolBlocks({ toolBlocks, messageId })
760
+ if (toolResults.length === 0) {
761
+ // stop_reason was tool_use but no tool_use blocks — defensive
762
+ // bailout to avoid an empty user message that the SDK rejects.
763
+ log.warn(`stop_reason=tool_use but no tool_use blocks in final.content; ending turn`)
764
+ break
765
+ }
766
+ this._history.push({ role: 'user', content: toolResults })
767
+
768
+ if (this._abortController?.signal?.aborted) break
769
+
770
+ if (round === MAX_TOOL_ROUNDS - 1) {
771
+ // #4063: instead of bailing silently, run ONE more text-only
772
+ // stream so the model can summarise what it accomplished and the
773
+ // user sees a closing message instead of an apparent hang. To
774
+ // preserve the strict user/assistant alternation invariant
775
+ // (#4109/#4118), we EMBED the summary instruction as an extra
776
+ // content block on the existing tool_result user turn rather
777
+ // than pushing a second user turn back-to-back.
778
+ log.warn(`hit MAX_TOOL_ROUNDS=${MAX_TOOL_ROUNDS} cap; running summary round`)
779
+
780
+ // Emit a non-fatal error so the dashboard can render a warning
781
+ // banner. The session stays alive — the user can keep talking;
782
+ // it's not a STREAM_ERROR / ABORT.
783
+ this.emit('error', {
784
+ messageId,
785
+ code: 'MAX_TOOL_ROUNDS_REACHED',
786
+ message: `Tool round cap reached (${MAX_TOOL_ROUNDS}). Asked the model to summarise what it accomplished so far.`,
787
+ fatal: false,
788
+ })
789
+
790
+ // Append the instruction as a text block on the last user turn
791
+ // (the one we just pushed at line ~432 with tool_results).
792
+ const summaryInstruction = {
793
+ type: 'text',
794
+ text: `Tool budget exhausted (${MAX_TOOL_ROUNDS} rounds). Please summarise what you accomplished so far. Do not call any more tools.`,
795
+ }
796
+ const lastTurn = this._history[this._history.length - 1]
797
+ if (lastTurn?.role === 'user' && Array.isArray(lastTurn.content)) {
798
+ lastTurn.content.push(summaryInstruction)
799
+ } else {
800
+ // Defensive fallback — should never hit given the immediately-
801
+ // prior push at line ~432, but if invariants change later
802
+ // we'd rather log and bail than corrupt history.
803
+ log.warn(`MAX_TOOL_ROUNDS cap-hit: last turn is not a user tool_result turn; skipping summary`)
804
+ break
805
+ }
806
+
807
+ let summaryStream
808
+ try {
809
+ summaryStream = this._client.messages.stream(
810
+ {
811
+ model: this.model || this._defaultModel,
812
+ max_tokens: DEFAULT_MAX_TOKENS,
813
+ ...(systemPrompt ? { system: systemPrompt } : {}),
814
+ // No tools — force a text-only summary. Even if the model
815
+ // tried to tool_use, the API would reject (no tools to
816
+ // dispatch to). Cleaner to just omit.
817
+ messages: this._history,
818
+ },
819
+ { signal: this._abortController.signal },
820
+ )
821
+ } catch (err) {
822
+ // Stream-init threw synchronously. Pop the instruction we
823
+ // just appended so the user turn returns to pure tool_results
824
+ // — invariant preserved.
825
+ const popped = lastTurn.content.pop()
826
+ if (popped !== summaryInstruction) {
827
+ log.warn(`MAX_TOOL_ROUNDS rollback: popped content block was not the summary instruction`)
828
+ }
829
+ log.warn(`MAX_TOOL_ROUNDS summary stream-init failed: ${err?.message}`)
830
+ break
831
+ }
832
+
833
+ // Async failures inside the for-await or finalMessage() rethrow
834
+ // and propagate to the outer catch, which truncates _history to
835
+ // historyLengthBeforeSend — rolling back the entire turn
836
+ // (consistent with #4109/#4118). The user has already seen
837
+ // emitted tool_result events; only the history-persisted state
838
+ // resets.
839
+ for await (const event of summaryStream) {
840
+ const t = translateSdkEvent(event)
841
+ if (!t) continue
842
+ switch (t.kind) {
843
+ case 'stream_delta':
844
+ this.emit('stream_delta', { messageId, delta: t.text })
845
+ break
846
+ case 'message_delta':
847
+ if (t.stopReason) lastStopReason = t.stopReason
848
+ break
849
+ default:
850
+ break
851
+ }
852
+ }
853
+
854
+ const summaryFinal = await summaryStream.finalMessage()
855
+ lastStopReason = summaryFinal.stop_reason
856
+ const sUsage = summaryFinal.usage || {}
857
+ turnUsage.input_tokens += Number(sUsage.input_tokens) || 0
858
+ turnUsage.output_tokens += Number(sUsage.output_tokens) || 0
859
+ turnUsage.cache_read_input_tokens += Number(sUsage.cache_read_input_tokens) || 0
860
+ turnUsage.cache_creation_input_tokens += Number(sUsage.cache_creation_input_tokens) || 0
861
+ // #5630: skip a null (unknown) cost — see the round-usage add above.
862
+ {
863
+ const c = computePromptCostUsd(sUsage, pricing)
864
+ if (c !== null) { turnCost += c; turnCostKnown = true }
865
+ }
866
+ this._history.push({ role: 'assistant', content: summaryFinal.content })
867
+ break
868
+ }
869
+ }
870
+
871
+ // #4049: fold any subagent (Task tool) usage + cost into the
872
+ // user-facing turn totals. Cost accounting must attribute the
873
+ // child's API spend to the parent session so the user sees a
874
+ // single number for "what did this turn cost?" rather than
875
+ // having delegated work disappear from accounting.
876
+ turnUsage.input_tokens += this._subagentUsageThisTurn.input_tokens
877
+ turnUsage.output_tokens += this._subagentUsageThisTurn.output_tokens
878
+ turnUsage.cache_read_input_tokens += this._subagentUsageThisTurn.cache_read_input_tokens
879
+ turnUsage.cache_creation_input_tokens += this._subagentUsageThisTurn.cache_creation_input_tokens
880
+ // Subagent cost is a finite accumulator (child `result.cost` coerced via
881
+ // `Number(...) || 0`); any positive contribution means the turn cost is
882
+ // at least partially known (#5630).
883
+ turnCost += this._subagentCostThisTurn
884
+ if (this._subagentCostThisTurn > 0) turnCostKnown = true
885
+
886
+ this.emit('stream_end', { messageId })
887
+ this.emit('result', {
888
+ sessionId: null,
889
+ messageId,
890
+ stopReason: lastStopReason,
891
+ duration: Date.now() - turnStartedAt,
892
+ usage: turnUsage,
893
+ // #5630: emit null when no round produced a known cost so the UI
894
+ // shows "n/a" instead of a misleading $0.00.
895
+ cost: turnCostKnown ? turnCost : null,
896
+ })
897
+ } catch (err) {
898
+ // #4118: extend the synchronous stream-init rollback (#4109) to
899
+ // ANY error that bubbles to the outer catch at round 1+ — the
900
+ // for-await loop rejecting mid-iteration, finalMessage() rejecting,
901
+ // a tool-execution promise rejecting after at least one round has
902
+ // committed assistant + user tool_result to _history. Without this,
903
+ // history ends on a `user` tool_result turn and the next
904
+ // sendMessage pushes a plain-text `user` turn back-to-back —
905
+ // soft-breaking the alternation invariant the API may tighten on.
906
+ //
907
+ // The synthetic-tool_result completion path (#4061, when the user
908
+ // aborts mid-tool-loop) intentionally COMMITS the user turn so
909
+ // the next turn doesn't 400. That path emits a 'result' event
910
+ // before reaching this catch and never throws, so it's not
911
+ // affected here. We only catch real errors.
912
+ //
913
+ // Truncating to historyLengthBeforeSend is idempotent: if the
914
+ // inner stream-init catch already truncated (round-0 path), the
915
+ // length is already at or below the snapshot and this is a no-op.
916
+ if (this._history.length > historyLengthBeforeSend) {
917
+ this._history.length = historyLengthBeforeSend
918
+ }
919
+ // #5020: fold any subagent (Task tool) usage + cost into the
920
+ // partial turn totals BEFORE the error fires so the user sees
921
+ // what the failed turn cost. Without this fold the child's
922
+ // tokens are silently dropped at _finishTurn reset even though
923
+ // the user is still billed for them. Mirrors the success-path
924
+ // fold above; the partial totals reflect every completed parent
925
+ // round + every completed child API call before the failure.
926
+ turnUsage.input_tokens += this._subagentUsageThisTurn.input_tokens
927
+ turnUsage.output_tokens += this._subagentUsageThisTurn.output_tokens
928
+ turnUsage.cache_read_input_tokens += this._subagentUsageThisTurn.cache_read_input_tokens
929
+ turnUsage.cache_creation_input_tokens += this._subagentUsageThisTurn.cache_creation_input_tokens
930
+ turnCost += this._subagentCostThisTurn
931
+ if (this._subagentCostThisTurn > 0) turnCostKnown = true
932
+ this.emit('stream_end', { messageId })
933
+ this._emitTurnError(messageId, err, 'STREAM_ERROR', {
934
+ usage: turnUsage,
935
+ // #5630: null when no priced round committed before the error so the
936
+ // partial-cost line shows "n/a" rather than $0.00.
937
+ cost: turnCostKnown ? turnCost : null,
938
+ })
939
+ } finally {
940
+ // #4080: per-turn isolation guarantee. The per-round clear after
941
+ // finalMessage() above runs on the success path; an iteration or
942
+ // finalMessage() throw skips it and would leak stale
943
+ // index→toolUseId entries into the next turn (mis-tagging the
944
+ // next stream's tool_input_delta events). Clearing here drains
945
+ // them on every exit path — success, error, abort, hard timeout.
946
+ // Safe to call when already empty.
947
+ this._streamingIndexToToolUseId.clear()
948
+ this._finishTurn()
949
+ }
950
+ }
951
+
952
+ /**
953
+ * Orchestrate one round's tool_use blocks (#4062).
954
+ *
955
+ * Phase 1: Gate ALL blocks sequentially in source order so the
956
+ * permission prompts surface one-at-a-time (UX guarantee — the user
957
+ * can only answer one prompt at a time on the phone).
958
+ * Phase 2: Execute approved blocks in parallel via Promise.all to
959
+ * collapse wall-clock latency on multi-Read turns.
960
+ *
961
+ * Preserves the #4061 history invariant: returns a tool_result content
962
+ * block for EVERY tool_use, in the same order. Aborts during gating
963
+ * synthesise 'Interrupted' tool_results for the unscheduled remainder.
964
+ */
965
+ async _processToolBlocks({ toolBlocks, messageId }) {
966
+ const signal = this._abortController?.signal
967
+ // Pre-allocate result slots so we can write by index from parallel
968
+ // executions while preserving model-emit order in the final array.
969
+ const toolResults = new Array(toolBlocks.length)
970
+ const gateDecisions = new Array(toolBlocks.length)
971
+ let firstUngatedIndex = toolBlocks.length
972
+
973
+ // Synthetic-fill helper (#4108, #4247). Used both for the mid-gate
974
+ // remainder (blocks that never entered the gate) AND the
975
+ // inter-phase race (every block was gated, but the signal tripped
976
+ // before phase 2 schedules — without this guard, write-side tools
977
+ // that ignore the signal would execute AFTER the user pressed Stop).
978
+ const fillInterrupted = (startIndex) => {
979
+ const interrupted = 'Interrupted by user before execution'
980
+ for (let j = startIndex; j < toolBlocks.length; j++) {
981
+ // Skip slots that already carry a real result (defensive — the
982
+ // inter-phase guard fires when startIndex === 0, but only the
983
+ // blocks that *would* have executed in phase 2 need filling).
984
+ if (toolResults[j]) continue
985
+ const remaining = toolBlocks[j]
986
+ this.emit('tool_result', {
987
+ messageId,
988
+ toolUseId: remaining.id,
989
+ result: interrupted,
990
+ isError: true,
991
+ })
992
+ toolResults[j] = {
993
+ type: 'tool_result',
994
+ tool_use_id: remaining.id,
995
+ content: interrupted,
996
+ is_error: true,
997
+ }
998
+ }
999
+ }
1000
+
1001
+ // PHASE 1 — sequential permission gating.
1002
+ for (let i = 0; i < toolBlocks.length; i++) {
1003
+ if (signal?.aborted) {
1004
+ firstUngatedIndex = i
1005
+ break
1006
+ }
1007
+ gateDecisions[i] = await this._gateToolBlock({
1008
+ block: toolBlocks[i],
1009
+ messageId,
1010
+ })
1011
+ }
1012
+
1013
+ // Mid-gate abort: fill synthetic 'Interrupted' tool_results for the
1014
+ // unscheduled remainder (#4108). The early-aborted blocks never
1015
+ // emitted a tool_start (we didn't even get to the executor), but
1016
+ // the SDK already emitted tool_start when streaming the assistant
1017
+ // turn — so the bubble would hang in 'running…' without a closing
1018
+ // tool_result event.
1019
+ if (firstUngatedIndex < toolBlocks.length) {
1020
+ fillInterrupted(firstUngatedIndex)
1021
+ }
1022
+
1023
+ // Inter-phase race guard (#4247): if the signal tripped while the
1024
+ // last gate was awaiting — or any time after phase 1's loop check
1025
+ // and before phase 2 schedules — short-circuit the remainder into
1026
+ // synthetic-fills rather than launching write-side tools (Read,
1027
+ // Write, Edit, TodoWrite) that don't honour the signal and would
1028
+ // run to completion AFTER the user pressed Stop. Pre-fix, the
1029
+ // sequential-loop's bottom-of-iteration check caught this; the
1030
+ // parallel refactor (#4062) opened a window between phase 1 and
1031
+ // phase 2 where the abort could go unobserved.
1032
+ //
1033
+ // Only applies when phase 1 completed fully (every block was
1034
+ // successfully gated). The mid-gate path above already handled
1035
+ // the partial-gate case and must keep block N's execution — its
1036
+ // gate ran BEFORE the abort tripped, so the user's permission
1037
+ // answer would be wasted if we re-synthesized it here.
1038
+ if (signal?.aborted && firstUngatedIndex === toolBlocks.length) {
1039
+ fillInterrupted(0)
1040
+ firstUngatedIndex = 0
1041
+ }
1042
+
1043
+ // PHASE 2 — parallel execution of every successfully-gated block.
1044
+ // Promise.all preserves array order, but we write by index to
1045
+ // double-guard against any future reordering refactor.
1046
+ const executions = []
1047
+ for (let i = 0; i < firstUngatedIndex; i++) {
1048
+ const block = toolBlocks[i]
1049
+ const decision = gateDecisions[i]
1050
+ executions.push(
1051
+ this._executeToolBlock({ block, messageId, decision }).then(
1052
+ (result) => { toolResults[i] = result },
1053
+ ),
1054
+ )
1055
+ }
1056
+ await Promise.all(executions)
1057
+
1058
+ return toolResults
1059
+ }
1060
+
1061
+ /**
1062
+ * Resolve the permission decision for a single tool_use block. Split
1063
+ * out from _executeToolBlock so the orchestrator can serialize gating
1064
+ * across all blocks in a turn before fanning out execution (#4062).
1065
+ *
1066
+ * Returns the PermissionManager decision shape directly, or a synthetic
1067
+ * deny-shaped object if the gate itself rejected (timeout/abort). The
1068
+ * caller distinguishes by checking `decision.behavior !== 'allow'`.
1069
+ */
1070
+ async _gateToolBlock({ block, messageId }) {
1071
+ // messageId is currently unused here, but kept in the signature so
1072
+ // future telemetry (e.g. emitting a permission_pending event tied to
1073
+ // the round) can hook in without changing every call site.
1074
+ void messageId
1075
+ const toolUseId = block.id
1076
+ const toolName = block.name
1077
+ const input = block.input || {}
1078
+ const signal = this._abortController?.signal
1079
+ // #4080: track that this toolUseId has a pending permission prompt
1080
+ // so any tool_input_delta for the SAME toolUseId (e.g. a future
1081
+ // mid-stream gate, or a re-streamed input in a later round) is
1082
+ // suppressed until the prompt resolves. PermissionManager keys
1083
+ // its own pending map by requestId, not toolUseId, so the
1084
+ // tracking has to live here. Wrap the whole permission gate so
1085
+ // both the allow-and-deny paths drain.
1086
+ this._pendingPermissionToolUseIds.add(toolUseId)
1087
+ try {
1088
+ return await this._permissions.handlePermission(
1089
+ toolName,
1090
+ input,
1091
+ signal,
1092
+ this.permissionMode,
1093
+ )
1094
+ } catch (err) {
1095
+ // permission_request was rejected (timeout, abort, etc.). Surface
1096
+ // as a deny so the executor short-circuits to a tool_result.
1097
+ return {
1098
+ behavior: 'deny',
1099
+ message: `Permission gate error: ${err?.message || String(err)}`,
1100
+ }
1101
+ } finally {
1102
+ this._pendingPermissionToolUseIds.delete(toolUseId)
1103
+ }
1104
+ }
1105
+
1106
+ /**
1107
+ * Run one tool_use block: permission gate, dispatch to executor, emit
1108
+ * tool_result events, return the {type:'tool_result', ...} content
1109
+ * block to append to the next user message.
1110
+ *
1111
+ * #4062: When called from the orchestrator, a pre-resolved `decision`
1112
+ * is supplied so we skip the gate (it already ran sequentially in
1113
+ * _processToolBlocks). When called directly (legacy callers and tests
1114
+ * that stub the seam) the gate runs inline — preserves backwards
1115
+ * compatibility with the original single-phase contract.
1116
+ */
1117
+ async _executeToolBlock({ block, messageId, decision }) {
1118
+ const toolUseId = block.id
1119
+ const toolName = block.name
1120
+ const input = block.input || {}
1121
+ const signal = this._abortController?.signal
1122
+
1123
+ // Permission gate. PermissionManager handles all four modes
1124
+ // (approve / auto / acceptEdits / plan) and session rules. The
1125
+ // _pendingPermissionToolUseIds tracking (#4080) lives inside
1126
+ // _gateToolBlock so it covers both the orchestrator (#4062) path
1127
+ // and the legacy inline-gate path used by direct callers/tests.
1128
+ let resolvedDecision = decision
1129
+ if (!resolvedDecision) {
1130
+ resolvedDecision = await this._gateToolBlock({ block, messageId })
1131
+ }
1132
+
1133
+ if (resolvedDecision.behavior !== 'allow') {
1134
+ const msg = resolvedDecision.message || 'Permission denied by user.'
1135
+ this.emit('tool_result', {
1136
+ messageId,
1137
+ toolUseId,
1138
+ result: msg,
1139
+ isError: true,
1140
+ })
1141
+ return {
1142
+ type: 'tool_result',
1143
+ tool_use_id: toolUseId,
1144
+ content: msg,
1145
+ is_error: true,
1146
+ }
1147
+ }
1148
+
1149
+ // Execute locally. Three dispatch paths:
1150
+ // 1. Task (#4049) — recursive subagent. Spawns a fresh
1151
+ // ClaudeByokSession with isolated history but shared client +
1152
+ // cwd + permission mode, emits agent_spawned / agent_completed
1153
+ // events, and folds the child's cost/usage back into the
1154
+ // parent's turn totals.
1155
+ // 2. MCP tools (mcp__<server>__<tool>) — route through the fleet
1156
+ // to the right child process via stdio JSON-RPC.
1157
+ // 3. Built-in tools (Read/Write/Bash/etc) — route through
1158
+ // `_dispatchBuiltinTool` which by default runs in-process.
1159
+ // Subclasses (e.g. DockerByokSession, #4053) override
1160
+ // `_dispatchBuiltinTool` to redirect execution into an isolated
1161
+ // environment without touching this loop.
1162
+ const effectiveInput = resolvedDecision.updatedInput || input
1163
+ let dispatchResult
1164
+ if (toolName === 'Task') {
1165
+ dispatchResult = await this._executeTaskTool({
1166
+ toolUseId,
1167
+ input: effectiveInput,
1168
+ messageId,
1169
+ signal,
1170
+ })
1171
+ } else if (toolName.startsWith(MCP_TOOL_PREFIX)) {
1172
+ dispatchResult = await this._dispatchMcpTool(toolName, effectiveInput)
1173
+ } else {
1174
+ dispatchResult = await this._dispatchBuiltinTool({
1175
+ toolName,
1176
+ input: effectiveInput,
1177
+ signal,
1178
+ })
1179
+ }
1180
+ const { content, isError } = dispatchResult
1181
+
1182
+ this.emit('tool_result', {
1183
+ messageId,
1184
+ toolUseId,
1185
+ result: content,
1186
+ isError,
1187
+ })
1188
+
1189
+ return {
1190
+ type: 'tool_result',
1191
+ tool_use_id: toolUseId,
1192
+ content,
1193
+ is_error: isError,
1194
+ }
1195
+ }
1196
+
1197
+ /**
1198
+ * #4049: dispatch the Task tool by spawning a child ClaudeByokSession.
1199
+ *
1200
+ * Design (v1 minimum protocol surface):
1201
+ * - Child inherits the parent's cwd, model, permission mode, and
1202
+ * Anthropic SDK client — same API key authenticates both, no
1203
+ * second resolveCredentials() pass.
1204
+ * - Child gets a FRESH _history (the subagent doesn't see the
1205
+ * parent's conversation — that's the point of delegating to a
1206
+ * focused scope). The prompt arrives as its first user message.
1207
+ * - Child's intermediate tool calls are silent on the wire — the
1208
+ * parent only sees `agent_spawned` (when the child starts) and
1209
+ * `agent_completed` (when it returns). Surfacing per-child tool
1210
+ * streams as sub-bubbles is a deliberate v2 follow-up (the issue
1211
+ * calls it out as "optional"). Keeping v1 silent matches how
1212
+ * sdk-session.js surfaces Task today.
1213
+ * - Cost + usage from the child fold into _subagentUsageThisTurn /
1214
+ * _subagentCostThisTurn, which sendMessage() adds to the user-
1215
+ * facing result.cost before emitting (acceptance criteria:
1216
+ * "child tokens attributed to the parent session").
1217
+ * - Cancellation cascade: the parent's AbortSignal triggers
1218
+ * child.interrupt() via the interrupt() override that iterates
1219
+ * _subagentSessions. A signal that aborts mid-flight also fires
1220
+ * the local onAbort listener so the cascade happens even on a
1221
+ * micro-race between the abort and the child's sendMessage.
1222
+ *
1223
+ * Per-launch permission-mode override (#5017):
1224
+ * The model may pass an optional `permission_mode` field on the Task
1225
+ * input. When set, it overrides the inherited mode for this one
1226
+ * launch — but only if it is at-most-as-permissive as the parent
1227
+ * (plan < approve < acceptEdits < auto). Requesting a stricter mode
1228
+ * is allowed; requesting a more permissive mode is rejected with
1229
+ * an is_error tool_result.
1230
+ *
1231
+ * Deferred (per scope note):
1232
+ * - Sub-bubble UI / mid-flight tool surfacing for the child
1233
+ * - subagent_type profile registry — the field is accepted in the
1234
+ * schema for forward-compat but the runner ignores it in v1
1235
+ *
1236
+ * @returns {Promise<{content: string, isError: boolean}>}
1237
+ */
1238
+ async _executeTaskTool({ toolUseId, input, messageId, signal }) {
1239
+ void messageId
1240
+ const description = typeof input?.description === 'string'
1241
+ ? input.description.slice(0, 200)
1242
+ : 'Background task'
1243
+ const prompt = typeof input?.prompt === 'string' ? input.prompt : ''
1244
+ if (!prompt) {
1245
+ return {
1246
+ content: 'Task tool requires a non-empty `prompt` field describing the work for the subagent.',
1247
+ isError: true,
1248
+ }
1249
+ }
1250
+ // #5017: per-launch permission_mode override. When omitted, the child
1251
+ // inherits the parent's mode (existing v1 behaviour). When set, the
1252
+ // value must be a known mode AND at-most-as-permissive as the parent
1253
+ // (plan < approve < acceptEdits < auto) — a subagent must not be able
1254
+ // to escalate beyond the policy the user picked for the parent.
1255
+ let childPermissionMode = this.permissionMode
1256
+ if (input?.permission_mode !== undefined) {
1257
+ const requested = input.permission_mode
1258
+ if (typeof requested !== 'string' || !TASK_PERMISSION_MODE_LIST.includes(requested)) {
1259
+ return {
1260
+ content: `Task tool: invalid \`permission_mode\` "${requested}". Allowed values: ${TASK_PERMISSION_MODE_LIST.join(', ')}.`,
1261
+ isError: true,
1262
+ }
1263
+ }
1264
+ const parentRank = TASK_PERMISSION_MODE_RANK[this.permissionMode]
1265
+ const requestedRank = TASK_PERMISSION_MODE_RANK[requested]
1266
+ // parentRank can be undefined if the parent's mode is somehow
1267
+ // off-list (shouldn't happen — base-session validates — but defend
1268
+ // anyway). Treat that as "no override allowed".
1269
+ if (parentRank === undefined || requestedRank > parentRank) {
1270
+ return {
1271
+ content: `Task tool: \`permission_mode\` "${requested}" is more permissive than the parent's mode "${this.permissionMode}". Subagents must be at-most-as-permissive as the parent.`,
1272
+ isError: true,
1273
+ }
1274
+ }
1275
+ childPermissionMode = requested
1276
+ }
1277
+ // #5019: validate inherit_mcp type BEFORE the agent_spawned emit /
1278
+ // _activeAgents.set so a non-boolean value (string "true", number 1,
1279
+ // null — anything `typeof !== 'boolean'`) returns an is_error result
1280
+ // without leaving a phantom entry in _activeAgents or emitting an
1281
+ // unbalanced agent_spawned. The dashboard's active-agents badge would
1282
+ // otherwise show a spawn that never clears. Mirrors the placement of
1283
+ // the permission_mode validation above. The model gets a crisp signal
1284
+ // naming the offending field rather than us silently coercing to one
1285
+ // of the two paths.
1286
+ let inheritMcp = true
1287
+ if (input?.inherit_mcp !== undefined) {
1288
+ if (typeof input.inherit_mcp !== 'boolean') {
1289
+ return {
1290
+ content: `Task tool: invalid \`inherit_mcp\` value (got ${typeof input.inherit_mcp}). Must be a boolean.`,
1291
+ isError: true,
1292
+ }
1293
+ }
1294
+ inheritMcp = input.inherit_mcp
1295
+ }
1296
+ // #5018: subagent_type profile lookup. When the model passes a
1297
+ // `subagent_type`, look it up in the registry and apply the profile
1298
+ // (systemPrompt + toolSet) to the child before its first sendMessage.
1299
+ // Unknown values fall back to v1 behaviour (no profile applied) and
1300
+ // emit a warn log per the issue's acceptance criteria — keeps the
1301
+ // delegation forward-compatible with a future model that requests a
1302
+ // profile id this server doesn't yet know about, rather than failing
1303
+ // the entire tool call. When omitted, no profile is applied and the
1304
+ // v1 default behaviour stands.
1305
+ let subagentProfile = null
1306
+ if (input?.subagent_type !== undefined) {
1307
+ subagentProfile = getSubagentProfile(input.subagent_type)
1308
+ if (!subagentProfile) {
1309
+ const got = typeof input.subagent_type === 'string'
1310
+ ? `"${input.subagent_type}"`
1311
+ : String(input.subagent_type)
1312
+ log.warn(
1313
+ `Task tool: unknown subagent_type ${got}; falling back to v1 default (no profile applied). `
1314
+ + `Available profiles: ${SUBAGENT_PROFILE_NAMES.join(', ')}.`,
1315
+ )
1316
+ }
1317
+ }
1318
+ if (signal?.aborted) {
1319
+ return { content: 'Interrupted by user before subagent spawned', isError: true }
1320
+ }
1321
+ // Emit agent_spawned BEFORE creating the child so the dashboard's
1322
+ // active-agents badge updates immediately. Same shape as
1323
+ // sdk-session.js's emit on _handleToolUseBlock (`toolUseId`,
1324
+ // `description`, `startedAt`). The toolUseId matches the parent
1325
+ // turn's tool_use block id so the dashboard correlates the spawn
1326
+ // with the open tool_call bubble.
1327
+ const startedAt = Date.now()
1328
+ const agentInfo = { toolUseId, description, startedAt }
1329
+ this._activeAgents.set(toolUseId, agentInfo)
1330
+ this.emit('agent_spawned', agentInfo)
1331
+
1332
+ // Build a child session. Reuse this session's already-resolved
1333
+ // client so the API key resolution + Anthropic constructor only
1334
+ // ran once. mcpConfigPath: null skips MCP-config DISCOVERY in the
1335
+ // child — the child does not parse a second copy of ~/.claude.json
1336
+ // and does not spawn its own fleet. Whether the child gets MCP tools
1337
+ // is controlled by the fleet-sharing block below (#5019), not by
1338
+ // the constructor.
1339
+ //
1340
+ // #5019: by default the child borrows the parent's already-running
1341
+ // MCP fleet — this gives nested Task subagents access to the same
1342
+ // mcp__<server>__<tool> set the parent sees, at zero extra spawn
1343
+ // cost (the parent's MCP children are reused). The child does NOT
1344
+ // own the fleet, so destroy() won't kill the parent's MCP children
1345
+ // when the subagent finishes. Per-call permission gating still
1346
+ // runs through the child's own PermissionManager — only the fleet
1347
+ // (process pool + tool catalogue) is shared.
1348
+ //
1349
+ // The model can opt out per-launch by passing `inherit_mcp: false`
1350
+ // on the Task input — useful when the subagent's prompt should be
1351
+ // strictly scoped to built-in tools or when an MCP server is known
1352
+ // to be misbehaving and the user wants to isolate it from the
1353
+ // delegated work. `inherit_mcp` defaults to true when omitted.
1354
+ //
1355
+ // #5015 review: wrap construction + init in try/catch. If the
1356
+ // ClaudeByokSession ctor or any of the field assignments throws
1357
+ // (unlikely today but a future refactor could add an init step
1358
+ // that does), the parent has already emitted agent_spawned and
1359
+ // populated _activeAgents — we MUST balance that with a matching
1360
+ // agent_completed + _activeAgents delete + matching error tool_result
1361
+ // so the dashboard badge clears and we don't leak the entry.
1362
+ let child
1363
+ try {
1364
+ const ClaudeByokSessionCtor = this.constructor
1365
+ child = new ClaudeByokSessionCtor({
1366
+ cwd: this.cwd,
1367
+ model: this.model || this._defaultModel,
1368
+ mcpConfigPath: null,
1369
+ })
1370
+ // Skip start()'s credential resolution — share the parent's client
1371
+ // so the child uses the same API key path. Also avoids a duplicate
1372
+ // credentials.json read which could rate-limit on disk for parallel
1373
+ // fan-outs.
1374
+ child._client = this._client
1375
+ child._apiKeySource = this._apiKeySource
1376
+ child._processReady = true
1377
+ // #5019: share the parent's MCP fleet (default) unless the model
1378
+ // explicitly opted out via `inherit_mcp: false`. Borrowed fleets
1379
+ // MUST set _ownsMcpFleet = false so the child's destroy() doesn't
1380
+ // tear down the parent's MCP children.
1381
+ if (inheritMcp && this._mcpFleet) {
1382
+ child._mcpFleet = this._mcpFleet
1383
+ child._ownsMcpFleet = false
1384
+ }
1385
+ // Inherit permission mode so the subagent runs under the same
1386
+ // gating policy as the parent — a user who set `auto` doesn't
1387
+ // want the child to start prompting again, and a user in
1388
+ // `approve` mode expects to gate the child's tools too. When the
1389
+ // model passes a `permission_mode` override on the Task input
1390
+ // (#5017), we use that instead — already validated above to be
1391
+ // at-most-as-permissive as the parent. Direct assignment (vs
1392
+ // setPermissionMode) is safe here: the child is fresh, not busy,
1393
+ // and has no pending permissions to flush.
1394
+ child.permissionMode = childPermissionMode
1395
+ // #5018: apply the subagent profile (validated above). Route the
1396
+ // systemPrompt through setSessionPreamble so the profile follows
1397
+ // the same trim + SESSION_PREAMBLE_MAX_LENGTH cap as user-authored
1398
+ // preambles — keeps the system-prompt size bounded and predictable
1399
+ // even if a future profile prompt grows. The profile's systemPrompt
1400
+ // rides in the same slot _buildSystemPrompt() reads, so the existing
1401
+ // skills/chroxy-hint ordering still composes. When the toolSet is
1402
+ // restricted to a name list, install the filter on the child so its
1403
+ // `_buildTools()` only emits the allowed built-ins; `toolSet: 'all'`
1404
+ // leaves the filter unset so the child sees the full BUILTIN_TOOLS
1405
+ // array.
1406
+ if (subagentProfile) {
1407
+ child.setSessionPreamble(subagentProfile.systemPrompt)
1408
+ if (subagentProfile.toolSet !== 'all') {
1409
+ child._allowedBuiltinToolNames = new Set(subagentProfile.toolSet)
1410
+ }
1411
+ }
1412
+ this._subagentSessions.set(toolUseId, child)
1413
+ } catch (ctorErr) {
1414
+ // Balance the agent_spawned emit + _activeAgents.set above so the
1415
+ // dashboard badge clears and the entry doesn't leak forever.
1416
+ this._finalizeAgentByToolUseId(toolUseId)
1417
+ log.warn(`subagent construction failed: ${ctorErr?.message || ctorErr}`)
1418
+ return {
1419
+ content: `Subagent construction failed: ${ctorErr?.message || ctorErr}`,
1420
+ isError: true,
1421
+ }
1422
+ }
1423
+
1424
+ // Collect the child's stream_delta text into a buffer that becomes
1425
+ // the tool_result content. usage / cost are taken from the child's
1426
+ // single `result` event (the agent loop's per-round usage already
1427
+ // folds into the child's own result.usage).
1428
+ const textChunks = []
1429
+ let childCost = 0
1430
+ const childUsage = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
1431
+ let childError = null
1432
+ let resolveDone
1433
+ const done = new Promise((r) => { resolveDone = r })
1434
+
1435
+ child.on('stream_delta', (e) => {
1436
+ if (typeof e?.delta === 'string') textChunks.push(e.delta)
1437
+ // #5016: forward the child's stream_delta to the parent so the
1438
+ // dashboard can render its assistant text as a nested sub-bubble.
1439
+ this._emitAgentEvent(toolUseId, 'stream_delta', e)
1440
+ })
1441
+ child.on('result', (e) => {
1442
+ const u = e?.usage || {}
1443
+ childUsage.input_tokens = Number(u.input_tokens) || 0
1444
+ childUsage.output_tokens = Number(u.output_tokens) || 0
1445
+ childUsage.cache_read_input_tokens = Number(u.cache_read_input_tokens) || 0
1446
+ childUsage.cache_creation_input_tokens = Number(u.cache_creation_input_tokens) || 0
1447
+ childCost = Number(e?.cost) || 0
1448
+ resolveDone()
1449
+ })
1450
+ child.on('error', (e) => {
1451
+ // First error wins — capture the message but DON'T resolve yet,
1452
+ // wait for the eventual stream_end so usage still folds in.
1453
+ if (!childError) childError = e?.message || 'subagent failed'
1454
+ })
1455
+ child.on('stream_end', () => {
1456
+ // Belt-and-braces: if `result` never fires (provider error,
1457
+ // abort, or stream-init throw), stream_end still resolves the
1458
+ // promise so this method doesn't hang the parent's tool loop.
1459
+ resolveDone()
1460
+ })
1461
+ // #5016: forward the child's per-tool wire events to the parent as
1462
+ // `agent_event` carrying the parent toolUseId so the dashboard
1463
+ // groups them under the Task tool_call bubble. Cost / usage are
1464
+ // intentionally NOT replayed here (they fold once via the parent's
1465
+ // own per-turn accumulators above — no double-counting).
1466
+ child.on('tool_start', (e) => {
1467
+ this._emitAgentEvent(toolUseId, 'tool_start', e)
1468
+ })
1469
+ child.on('tool_input_delta', (e) => {
1470
+ this._emitAgentEvent(toolUseId, 'tool_input_delta', e)
1471
+ })
1472
+ child.on('tool_result', (e) => {
1473
+ this._emitAgentEvent(toolUseId, 'tool_result', e)
1474
+ })
1475
+ // #5056: relay the child's permission_request up to the parent's
1476
+ // wire path so the dashboard can render the nested prompt and the
1477
+ // user can approve/deny it. Without this, an MCP tool the subagent
1478
+ // fires under `approve` mode surfaces a permission_request that
1479
+ // nothing forwards — the dashboard never shows it and the request
1480
+ // silently times out → denied.
1481
+ //
1482
+ // The pending entry lives in the CHILD's PermissionManager, so we
1483
+ // record `requestId -> child` in the parent's routing table. When
1484
+ // the user responds, ws-permissions calls the PARENT's
1485
+ // respondToPermission (the only session id it knows); the parent
1486
+ // consults this table and forwards to the child that actually holds
1487
+ // the pending entry. See respondToPermission below.
1488
+ //
1489
+ // Authority note (bearer-token-authority.md): this relay does NOT
1490
+ // widen the trust boundary. The response still flows through the
1491
+ // existing ws-permissions gate on the PARENT session id (primary or
1492
+ // pairing-bound-to-parent token required). The routing table only
1493
+ // redirects an already-authorized decision to the correct in-process
1494
+ // PermissionManager — it grants no new authority and is unreachable
1495
+ // by the child or the model (in-process Map, no wire surface).
1496
+ child.on('permission_request', (e) => {
1497
+ if (e && e.requestId) {
1498
+ this._subagentPermissionRouting.set(e.requestId, child)
1499
+ }
1500
+ this._emitAgentEvent(toolUseId, 'permission_request', e)
1501
+ })
1502
+ child.on('permission_resolved', (e) => {
1503
+ if (e && e.requestId) {
1504
+ this._subagentPermissionRouting.delete(e.requestId)
1505
+ }
1506
+ this._emitAgentEvent(toolUseId, 'permission_resolved', e)
1507
+ })
1508
+ // #5016: when the child itself dispatches a Task (grand-child),
1509
+ // its own `agent_event` fires on the child. Forward those too,
1510
+ // re-tagged with THIS parent's toolUseId so the dashboard groups
1511
+ // all descendants under the outermost Task bubble. The original
1512
+ // (grand-child) `parentToolUseId` is preserved on the payload's
1513
+ // `parentToolUseId` for downstream renderers that may want to
1514
+ // distinguish depth — we merge it INTO the forwarded payload so
1515
+ // consumers can read `payload.parentToolUseId` to recover the
1516
+ // immediate-parent (grand-child Task) id. Without this merge the
1517
+ // grand-child's id is lost on the way up; the comment claimed
1518
+ // preservation but the original implementation dropped it.
1519
+ // A non-string `e?.type` would re-emit as `'agent_event'` which
1520
+ // the consumer reducer doesn't recognise — skip those so noise
1521
+ // doesn't reach the wire.
1522
+ child.on('agent_event', (e) => {
1523
+ if (typeof e?.type !== 'string') return
1524
+ const basePayload = (e?.payload && typeof e.payload === 'object' && !Array.isArray(e.payload))
1525
+ ? e.payload
1526
+ : {}
1527
+ const mergedPayload = e?.parentToolUseId
1528
+ ? { ...basePayload, parentToolUseId: e.parentToolUseId }
1529
+ : basePayload
1530
+ // #5056: a grand-child permission_request reaches us as an
1531
+ // `agent_event` re-emitted by the child. Route the response one
1532
+ // hop down — to the IMMEDIATE child — which already holds the
1533
+ // grand-child mapping in its own routing table and forwards the
1534
+ // decision the rest of the way. This keeps the chain recursive:
1535
+ // each level only needs to know its direct child.
1536
+ if (e.type === 'permission_request' && basePayload.requestId) {
1537
+ this._subagentPermissionRouting.set(basePayload.requestId, child)
1538
+ } else if (e.type === 'permission_resolved' && basePayload.requestId) {
1539
+ this._subagentPermissionRouting.delete(basePayload.requestId)
1540
+ }
1541
+ this._emitAgentEvent(toolUseId, e.type, mergedPayload)
1542
+ })
1543
+
1544
+ // Register a cascade hook on the parent's signal — interrupt()
1545
+ // already iterates _subagentSessions, but this listener also
1546
+ // catches the micro-race when the signal aborts between the
1547
+ // top-of-function check and child.sendMessage's first await.
1548
+ const onAbort = () => { try { child.interrupt() } catch { /* noop */ } }
1549
+ if (signal) {
1550
+ if (signal.aborted) onAbort()
1551
+ else signal.addEventListener('abort', onAbort, { once: true })
1552
+ }
1553
+
1554
+ // #5015 review: second abort check immediately before sendMessage.
1555
+ // Closes the micro-race where the signal aborts AFTER the top-of-
1556
+ // function `signal?.aborted` check but BEFORE the child flips
1557
+ // _isBusy=true. In that window, the `onAbort` listener fires
1558
+ // child.interrupt() which no-ops (`if (!this._isBusy) return`) —
1559
+ // sendMessage would then proceed and burn tokens after Stop.
1560
+ // Short-circuit with an interrupted result so cancellation is
1561
+ // honored even when the abort lands during this narrow gap.
1562
+ if (signal?.aborted) {
1563
+ if (signal) signal.removeEventListener?.('abort', onAbort)
1564
+ this._subagentSessions.delete(toolUseId)
1565
+ this._purgeSubagentPermissionRouting(child)
1566
+ try { await child.destroy() } catch (err) {
1567
+ log.warn(`subagent destroy on pre-send abort failed: ${err?.message || err}`)
1568
+ }
1569
+ this._finalizeAgentByToolUseId(toolUseId)
1570
+ return { content: 'Interrupted by user before subagent started', isError: true }
1571
+ }
1572
+ try {
1573
+ await child.sendMessage(prompt)
1574
+ await done
1575
+ } finally {
1576
+ if (signal) signal.removeEventListener?.('abort', onAbort)
1577
+ // Drop the child from _subagentSessions before destroy() so a
1578
+ // racing interrupt() during teardown doesn't try to abort an
1579
+ // already-half-destroyed child.
1580
+ this._subagentSessions.delete(toolUseId)
1581
+ // #5056: drop any still-outstanding permission routing entries for
1582
+ // this child so a late dashboard response can't dereference a
1583
+ // destroyed child (the child's own teardown rejects its pending
1584
+ // permissions; this just clears the parent's pointer).
1585
+ this._purgeSubagentPermissionRouting(child)
1586
+ try { await child.destroy() } catch (err) {
1587
+ log.warn(`subagent destroy on Task completion failed: ${err?.message || err}`)
1588
+ }
1589
+ this._finalizeAgentByToolUseId(toolUseId)
1590
+ }
1591
+
1592
+ // Fold child usage + cost into the parent's per-turn accumulators
1593
+ // so the user-facing result.cost includes every API call this
1594
+ // turn caused (acceptance criteria #4049).
1595
+ this._subagentUsageThisTurn.input_tokens += childUsage.input_tokens
1596
+ this._subagentUsageThisTurn.output_tokens += childUsage.output_tokens
1597
+ this._subagentUsageThisTurn.cache_read_input_tokens += childUsage.cache_read_input_tokens
1598
+ this._subagentUsageThisTurn.cache_creation_input_tokens += childUsage.cache_creation_input_tokens
1599
+ this._subagentCostThisTurn += childCost
1600
+
1601
+ if (childError) {
1602
+ // Surface the child's error as the tool_result content so the
1603
+ // parent model can see what went wrong and decide whether to
1604
+ // retry / re-prompt / abandon.
1605
+ return { content: `Subagent failed: ${childError}`, isError: true }
1606
+ }
1607
+ const summary = textChunks.join('').trim()
1608
+ if (!summary) {
1609
+ return {
1610
+ content: 'Subagent finished without producing any output text.',
1611
+ isError: true,
1612
+ }
1613
+ }
1614
+ return { content: summary, isError: false }
1615
+ }
1616
+
1617
+ /**
1618
+ * #5016: re-emit a Task subagent's intermediate wire event under the
1619
+ * parent's `agent_event` channel so the dashboard can render nested
1620
+ * sub-bubbles inside the parent's Task tool_call.
1621
+ *
1622
+ * `parentToolUseId` is the toolUseId of the parent's Task tool_use
1623
+ * block (the same id used for `agent_spawned` / `agent_completed`) —
1624
+ * the consumer keys the nested sub-bubble container off this id.
1625
+ *
1626
+ * `type` is the child's original event name (`tool_start`,
1627
+ * `tool_input_delta`, `tool_result`, `stream_delta`). The dashboard
1628
+ * switches on this to render the child's wire event in the same
1629
+ * shape it would for a top-level event.
1630
+ *
1631
+ * `payload` is the original child event payload, passed through
1632
+ * verbatim. Renderers MUST treat fields as best-effort (some payloads
1633
+ * carry messageId / toolUseId, others carry delta text only).
1634
+ *
1635
+ * Nested-Task support: when a Task subagent itself dispatches a Task,
1636
+ * the grand-child's events arrive as `agent_event` on the child
1637
+ * (because each session's `_emitAgentEvent` re-emits to itself), and
1638
+ * we surface them on the parent under the parent's toolUseId. This
1639
+ * means the dashboard sees a flat stream tagged with the IMMEDIATE
1640
+ * parent's id — nested-nested rendering is intentionally not in v2.
1641
+ *
1642
+ * @param {string} parentToolUseId
1643
+ * @param {string} type
1644
+ * @param {object} payload
1645
+ */
1646
+ _emitAgentEvent(parentToolUseId, type, payload) {
1647
+ this.emit('agent_event', {
1648
+ parentToolUseId,
1649
+ type,
1650
+ payload: payload ?? {},
1651
+ })
1652
+ }
1653
+
1654
+ /**
1655
+ * #5056: remove every permission-routing entry that points at the given
1656
+ * child session. Called when a Task subagent is torn down so a late
1657
+ * dashboard response can never dereference a destroyed child. Cheap
1658
+ * (the map is empty in the common case where no permission was pending).
1659
+ *
1660
+ * @param {object} child The subagent session being torn down
1661
+ */
1662
+ _purgeSubagentPermissionRouting(child) {
1663
+ for (const [requestId, routed] of this._subagentPermissionRouting) {
1664
+ if (routed === child) this._subagentPermissionRouting.delete(requestId)
1665
+ }
1666
+ }
1667
+
1668
+ /**
1669
+ * Dispatch one built-in tool (Read/Write/Edit/Bash/Glob/Grep/WebFetch/
1670
+ * TodoWrite) to the local executor. Returns `{ content, isError }` —
1671
+ * the shape `_executeToolBlock` threads into the next round's
1672
+ * tool_result content block.
1673
+ *
1674
+ * Subclass seam (#4053): `DockerByokSession` overrides this to
1675
+ * redirect tool execution into an isolated Docker container while the
1676
+ * outer agent loop — model streaming, permission gating, MCP dispatch,
1677
+ * cost accounting — stays unchanged. The base implementation runs the
1678
+ * tool in-process on the host, which is what the host-side
1679
+ * `claude-byok` provider has always done.
1680
+ *
1681
+ * @param {object} args
1682
+ * @param {string} args.toolName Tool name from the model's tool_use block
1683
+ * @param {object} args.input Already-parsed JSON input from the model
1684
+ * @param {AbortSignal} [args.signal] Per-turn abort signal
1685
+ */
1686
+ async _dispatchBuiltinTool({ toolName, input, signal }) {
1687
+ return executeBuiltinTool({
1688
+ toolName,
1689
+ input,
1690
+ cwd: this.cwd,
1691
+ cwdRealCache: this._cwdRealCache,
1692
+ cwdCacheTtl: CWD_CACHE_TTL_MS,
1693
+ signal,
1694
+ todoStore: this._todos,
1695
+ })
1696
+ }
1697
+
1698
+ /**
1699
+ * Dispatch one MCP tool_use to the fleet. Flattens `{ content: [...],
1700
+ * isError }` from the MCP server into the `{ content: string, isError }`
1701
+ * shape `_executeToolBlock` returns. Concatenates any text blocks; for
1702
+ * non-text blocks (image, resource) we stringify the block so the model
1703
+ * sees the shape and can decide what to do — chroxy itself doesn't
1704
+ * interpret them.
1705
+ *
1706
+ * Errors (server unknown, server dead, RPC error, timeout, child crash
1707
+ * mid-call) become is_error:true tool_results — same shape as
1708
+ * executeBuiltinTool's catch-all. The session keeps running.
1709
+ */
1710
+ async _dispatchMcpTool(toolName, input) {
1711
+ try {
1712
+ // #4482: pass undefined when the operator didn't set a timeout so
1713
+ // MCPFleet.callTool's destructured default (DEFAULT_TOOL_CALL_TIMEOUT_MS)
1714
+ // fires — duplicating the constant here would silently desync if
1715
+ // MCPClient ever retunes its 30s default.
1716
+ const result = await this._mcpFleet.callTool(toolName, input, this._mcpToolCallTimeoutMs ?? undefined)
1717
+ const blocks = Array.isArray(result?.content) ? result.content : []
1718
+ const text = blocks
1719
+ .map((b) => (typeof b?.text === 'string' ? b.text : JSON.stringify(b)))
1720
+ .join('\n')
1721
+ return { content: text, isError: result?.isError === true }
1722
+ } catch (err) {
1723
+ return { content: `MCP ${toolName} failed: ${err?.message || String(err)}`, isError: true }
1724
+ }
1725
+ }
1726
+
1727
+ /**
1728
+ * In-process permission response — called by ws-permissions.js when the
1729
+ * user taps Approve/Deny on the phone or dashboard. Forwards to
1730
+ * PermissionManager which resolves the pending Promise in
1731
+ * handlePermission() above.
1732
+ */
1733
+ respondToPermission(requestId, decision, editedInput) {
1734
+ // #5056: if this requestId belongs to a Task subagent (its pending
1735
+ // entry lives in the CHILD's PermissionManager, not ours), forward
1736
+ // the decision to that child. ws-permissions only ever calls the
1737
+ // PARENT (the session id it knows), so this redirect is what lets a
1738
+ // dashboard Approve/Deny reach a nested MCP permission prompt. The
1739
+ // child's own respondToPermission recurses if the prompt actually
1740
+ // belongs to a grand-child. Authority is unchanged: the caller was
1741
+ // already authorized against the parent session by ws-permissions.
1742
+ const child = this._subagentPermissionRouting.get(requestId)
1743
+ if (child) {
1744
+ // Drop the routing entry first so a duplicate/late response can't
1745
+ // re-resolve a stale id. The child also emits permission_resolved
1746
+ // which our relay listener uses to clear the same entry — deleting
1747
+ // here too is idempotent and closes the lifetime tightly.
1748
+ this._subagentPermissionRouting.delete(requestId)
1749
+ // #6543: forward the operator's per-hunk editedInput to the child too.
1750
+ return child.respondToPermission(requestId, decision, editedInput)
1751
+ }
1752
+ return this._permissions.respondToPermission(requestId, decision, editedInput)
1753
+ }
1754
+
1755
+ /**
1756
+ * Response to an AskUserQuestion tool. Same forwarding pattern.
1757
+ */
1758
+ respondToQuestion(text, answersMap) {
1759
+ this._permissions.respondToQuestion(text, answersMap)
1760
+ }
1761
+
1762
+ /**
1763
+ * Session-scoped permission rules (the dashboard's "Allow for Session"
1764
+ * affordance, #3072). Optional method — providers.js's capability check
1765
+ * uses presence to advertise sessionRules: true.
1766
+ */
1767
+ setPermissionRules(rules) {
1768
+ if (typeof this._permissions.setRules === 'function') {
1769
+ this._permissions.setRules(rules)
1770
+ }
1771
+ }
1772
+
1773
+ _emitTurnError(messageId, err, fallbackCode, partials) {
1774
+ // #4057: SDK v0.81+ throws `APIUserAbortError` (not the generic
1775
+ // `AbortError`) when an in-flight messages.stream sees its signal
1776
+ // aborted. Primary check is `instanceof` — the SDK class itself
1777
+ // never sets `.name`, so a name-string check would fail
1778
+ // (instance.name === 'Error', verified at runtime). Keep the
1779
+ // legacy `name === 'AbortError'` fallback for raw fetch aborts
1780
+ // (the SDK's own internal abort helper uses this convention). The
1781
+ // signal.aborted fallback catches paths where the SDK swallowed
1782
+ // the original error and re-threw something we don't recognise.
1783
+ //
1784
+ // #5020: `partials` carries the parent's completed-round usage +
1785
+ // cost (already folded with any subagent Task tool spend). Surface
1786
+ // it on every error path — ABORT and STREAM_ERROR alike — so the
1787
+ // user can see what the failed turn cost. The error envelope schema
1788
+ // is `.passthrough()` (ServerErrorEnvelopeSchema, protocol/server.ts)
1789
+ // so additional fields propagate without a wire-side schema change.
1790
+ // Optional / undefined-safe: pre-#5020 call sites pass nothing and
1791
+ // the fields are simply absent on the event payload.
1792
+ const aborted =
1793
+ err instanceof APIUserAbortError ||
1794
+ err?.name === 'AbortError' ||
1795
+ this._abortController?.signal?.aborted
1796
+ if (aborted) {
1797
+ this.emit('error', {
1798
+ messageId,
1799
+ message: 'Interrupted by user',
1800
+ code: 'ABORT',
1801
+ ...(partials ? { usage: partials.usage, cost: partials.cost } : {}),
1802
+ })
1803
+ return
1804
+ }
1805
+ const code = err?.status ? `HTTP_${err.status}` : (err?.code || fallbackCode)
1806
+ const message = err?.message || String(err)
1807
+ this.emit('error', {
1808
+ messageId,
1809
+ message,
1810
+ code,
1811
+ ...(partials ? { usage: partials.usage, cost: partials.cost } : {}),
1812
+ })
1813
+ }
1814
+
1815
+ _finishTurn() {
1816
+ this._isBusy = false
1817
+ this._currentMessageId = null
1818
+ this._abortController = null
1819
+ // #4049: reset the subagent accumulators so the next turn starts
1820
+ // clean — even on error / abort paths where the result event never
1821
+ // fired and the fold-in step above was skipped.
1822
+ this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
1823
+ this._subagentCostThisTurn = 0
1824
+ }
1825
+
1826
+ interrupt() {
1827
+ if (!this._isBusy) return
1828
+ if (this._abortController) {
1829
+ this._abortController.abort()
1830
+ }
1831
+ // #4049: cascade the interrupt to any active subagent sessions.
1832
+ // Each child has its own AbortController — interrupt() short-
1833
+ // circuits its in-flight stream so it returns promptly, which lets
1834
+ // _executeTaskTool's awaited promise resolve and the parent's
1835
+ // outer agent loop can finish the user-facing result event.
1836
+ for (const child of this._subagentSessions.values()) {
1837
+ try { child.interrupt() } catch (err) {
1838
+ log.warn(`subagent interrupt failed: ${err?.message || err}`)
1839
+ }
1840
+ }
1841
+ }
1842
+
1843
+ /**
1844
+ * #5274 (Control Room Phase 2a parity): cancel a single in-flight subagent
1845
+ * node by its `activityId` (the Task `toolUseId`). Mirrors
1846
+ * `SdkSession.cancelActivity` and returns the same structured-result
1847
+ * vocabulary, but the *mechanism* differs: SdkSession maps the node to the
1848
+ * SDK's `query.stopTask(task_id)`, whereas ClaudeByokSession owns each
1849
+ * subagent as a child session in `_subagentSessions` — so cancel aborts the
1850
+ * child's in-flight stream (via its `interrupt()` → `AbortController`) and
1851
+ * finalizes the parent's agent node.
1852
+ *
1853
+ * @param {string} activityId
1854
+ * @returns {Promise<{ ok: boolean, reason?: string, error?: string }>}
1855
+ */
1856
+ async cancelActivity(activityId) {
1857
+ if (typeof activityId !== 'string' || !activityId) return { ok: false, reason: 'invalid-id' }
1858
+ const entry = this._activity.getEntry(activityId)
1859
+ if (!entry) return { ok: false, reason: 'not-found' }
1860
+ if (entry.kind !== 'agent') {
1861
+ // Shells and tool calls have no per-node cancel surface (same as
1862
+ // SdkSession) — distinguish the shell case so the UI can point at
1863
+ // "Interrupt turn" instead of implying a transient error.
1864
+ return { ok: false, reason: entry.kind === 'shell' ? 'shell-not-cancellable' : 'not-cancellable' }
1865
+ }
1866
+ const child = this._subagentSessions.get(activityId)
1867
+ if (!child) {
1868
+ // The agent node is in the registry but we hold no live child handle —
1869
+ // the subagent already returned and was cleaned up; nothing to abort.
1870
+ return { ok: false, reason: 'not-found' }
1871
+ }
1872
+ log.info(`Cancelling byok subagent ${activityId}`)
1873
+ // Best-effort: the child's interrupt() aborts its in-flight stream, but
1874
+ // early-returns if the child isn't busy yet (the narrow window between
1875
+ // _subagentSessions.set and the child's sendMessage flipping _isBusy). In
1876
+ // that window the cancel can't pre-empt the not-yet-started turn — we still
1877
+ // optimistically finalize the node, matching the SDK path's best-effort
1878
+ // stopTask contract.
1879
+ try {
1880
+ child.interrupt()
1881
+ } catch (err) {
1882
+ log.warn(`subagent cancel failed for ${activityId}: ${err?.message || err}`)
1883
+ return { ok: false, reason: 'stop-failed', error: err?.message || String(err) }
1884
+ }
1885
+ // Optimistic finalize — idempotent with the natural agent_completed that
1886
+ // fires when the child's aborted stream unwinds.
1887
+ this._finalizeAgentByToolUseId(activityId)
1888
+ return { ok: true }
1889
+ }
1890
+
1891
+ /**
1892
+ * #5274: drop a subagent's `_activeAgents` entry and emit `agent_completed`
1893
+ * so its activity node terminates promptly on cancel. Idempotent (guards on
1894
+ * `_activeAgents.has`) so the optimistic cancel-finalize and the natural
1895
+ * completion don't double-emit. Mirrors SdkSession's helper of the same name
1896
+ * (minus the task-id map, which byok doesn't have).
1897
+ *
1898
+ * @param {string} toolUseId
1899
+ */
1900
+ _finalizeAgentByToolUseId(toolUseId) {
1901
+ if (typeof toolUseId !== 'string' || !toolUseId) return
1902
+ if (!this._activeAgents.has(toolUseId)) return
1903
+ this._activeAgents.delete(toolUseId)
1904
+ this.emit('agent_completed', { toolUseId })
1905
+ }
1906
+
1907
+ // #5374: no setModel override needed — BaseSession.setModel updates the
1908
+ // field and the next sendMessage uses it. No restart: the SDK is a stateless
1909
+ // HTTP client; each turn opens a fresh stream.
1910
+
1911
+ _onPermissionModeChanged(mode) {
1912
+ // #3729 / #4462: flipping to auto/bypass mid-turn must drain any
1913
+ // open permission prompts so the user isn't left staring at modals
1914
+ // after declaring "approve everything". Mirrors sdk-session.js's
1915
+ // behaviour.
1916
+ //
1917
+ // MCP trust prompts are exempt — autoAllowPending denies them so
1918
+ // the bypass doesn't silently persist a binary to the trust store
1919
+ // (a panic-button shouldn't grant forever-trust). See
1920
+ // permission-manager.js:autoAllowPending and the byok-mcp-trust
1921
+ // recordTrust path.
1922
+ if (mode === 'auto') {
1923
+ this._permissions.autoAllowPending()
1924
+ }
1925
+ }
1926
+
1927
+ // #4078: assemble the per-turn tools array. BUILTIN_TOOLS first
1928
+ // (Read/Write/Edit/Bash/Glob/Grep) then any live MCP tools surfaced by
1929
+ // the fleet, namespaced as mcp__<server>__<tool>. Re-evaluated every
1930
+ // turn rather than cached because the cost is trivial and the fleet's
1931
+ // READY-state filter is the source of truth for which servers are
1932
+ // contributing right now.
1933
+ //
1934
+ // #5018: when this session is a subagent that was spawned with a
1935
+ // restricted profile, `_allowedBuiltinToolNames` is a Set of the
1936
+ // allowed built-in tool names. Filter BUILTIN_TOOLS down to just
1937
+ // those — MCP tools pass through unchanged in v1 (gating MCP per
1938
+ // profile is a follow-up; the immediate value of a restricted
1939
+ // profile like code-reviewer is preventing accidental Write/Edit/Bash,
1940
+ // and MCP tools are off by default in subagents anyway). Unrestricted
1941
+ // (or non-subagent) sessions skip the filter entirely so this stays
1942
+ // a zero-cost path for the common case.
1943
+ _buildTools() {
1944
+ const builtins = this._allowedBuiltinToolNames
1945
+ ? BUILTIN_TOOLS.filter((t) => this._allowedBuiltinToolNames.has(t.name))
1946
+ : BUILTIN_TOOLS
1947
+ if (!this._mcpFleet) return builtins
1948
+ const mcp = this._mcpFleet.anthropicTools
1949
+ return mcp.length === 0 ? builtins : [...builtins, ...mcp]
1950
+ }
1951
+
1952
+ async destroy() {
1953
+ if (this._destroying) return
1954
+ this._destroying = true
1955
+ this.interrupt()
1956
+ // Mirror sdk-session.js:1272-1300 teardown: PermissionManager owns
1957
+ // its own destroy (which calls clearAll() and any internal timer
1958
+ // cleanup), and removeAllListeners drops every EventEmitter
1959
+ // subscription we registered on this session. Without these the
1960
+ // process leaks listeners + timers per session destroyed.
1961
+ try {
1962
+ this._permissions?.destroy()
1963
+ } catch (err) {
1964
+ log.warn(`PermissionManager teardown failed: ${err.message}`)
1965
+ }
1966
+ this._history = []
1967
+ this._todos.clear()
1968
+ // #4153: consistency with the existing _history/_todos teardown so
1969
+ // every in-memory collection on this session is reset at destroy.
1970
+ // Neither is a leak risk (both are bounded + small) — but if anything
1971
+ // outside the session retains a reference (debugger, future export
1972
+ // feature, tests that capture the instance) these collections would
1973
+ // otherwise outlive the session.
1974
+ this._cwdRealCache.clear()
1975
+ this._pricingWarnedModels.clear()
1976
+ // #4080: same-rationale teardown — both maps are bounded by the
1977
+ // active stream / outstanding permission count, but any external
1978
+ // reference (test capture, future export) would keep them alive.
1979
+ this._streamingIndexToToolUseId.clear()
1980
+ this._pendingPermissionToolUseIds.clear()
1981
+ // #5056: drop any outstanding subagent permission-routing pointers so
1982
+ // the destroyed parent doesn't retain references to its children.
1983
+ this._subagentPermissionRouting.clear()
1984
+ // #4049: tear down any active subagent sessions. interrupt() (run
1985
+ // at the top of destroy()) already cascaded the abort signal; this
1986
+ // step also drops each child's PermissionManager, MCP fleet, and
1987
+ // EventEmitter listeners so a long-running parent that fanned-out
1988
+ // a series of Task subagents doesn't leak per-child resources.
1989
+ if (this._subagentSessions.size > 0) {
1990
+ const children = [...this._subagentSessions.values()]
1991
+ this._subagentSessions.clear()
1992
+ for (const child of children) {
1993
+ try { await child.destroy() } catch (err) {
1994
+ log.warn(`subagent destroy failed: ${err?.message || err}`)
1995
+ }
1996
+ }
1997
+ }
1998
+ this._client = null
1999
+ // #4077: tear down MCP children with SIGTERM → SIGKILL grace.
2000
+ // Awaits up to FLEET_KILL_GRACE_MS (2s) + 500ms safety margin so a
2001
+ // hung child cannot stall destroy() indefinitely.
2002
+ //
2003
+ // #5019: only the owning session tears the fleet down. A Task subagent
2004
+ // that borrowed the parent's fleet (_ownsMcpFleet === false) just
2005
+ // drops its reference — destroying the parent's MCP children mid-flight
2006
+ // would kill MCP tool access for the parent and any sibling subagents.
2007
+ if (this._mcpFleet) {
2008
+ const fleet = this._mcpFleet
2009
+ const owns = this._ownsMcpFleet
2010
+ this._mcpFleet = null
2011
+ if (owns) {
2012
+ try { await fleet.destroy() } catch (err) {
2013
+ log.warn(`MCP fleet teardown failed: ${err?.message || err}`)
2014
+ }
2015
+ }
2016
+ }
2017
+ this.removeAllListeners()
2018
+ }
2019
+ }