@chroxy/server 0.10.0 → 0.11.10

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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -15,9 +15,12 @@
15
15
  */
16
16
 
17
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'
18
+ import { assertAuthorized, stillAuthorized } from './connection-authority.js'
19
+ import { performance } from 'node:perf_hooks'
20
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission } from './base-session.js'
21
+ import { BYOK_CUSTOMIZATION } from './provider-customization.js'
22
+ import { loadByokInstructionPolicy } from './instruction-policy.js'
23
+ import { synthesizeModelUsage } from './usage-normalize.js'
21
24
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
22
25
  import { createLogger } from './logger.js'
23
26
  import { isOperatorTimeoutInRange } from './duration.js'
@@ -32,9 +35,29 @@ import { BILLING_CLASSES } from './billing-class.js'
32
35
  import { translateSdkEvent } from './byok-event-translator.js'
33
36
  import { BUILTIN_TOOLS, TASK_PERMISSION_MODE_LIST, TASK_PERMISSION_MODE_RANK } from './byok-tools.js'
34
37
  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'
38
+ import {
39
+ addMcpServerToConfig,
40
+ defaultClaudeConfigPath,
41
+ discoverMcpServerSpecs,
42
+ mcpWriteScopeToSource,
43
+ planAddMcpServerToConfig,
44
+ removeMcpServerFromConfig,
45
+ mcpSourceToWriteScope,
46
+ toMcpServerMetadata,
47
+ validateMcpServerNameForRemoval,
48
+ validateNewMcpServerName,
49
+ } from './byok-mcp-config.js'
50
+ import { MCPFleet, MCP_TOOL_PREFIX, parseMcpToolName } from './byok-mcp-fleet.js'
51
+ import {
52
+ defaultTrustStorePath,
53
+ isTrusted,
54
+ loadTrustStore,
55
+ recordTrust,
56
+ withTrustStoreLock,
57
+ } from './byok-mcp-trust.js'
37
58
  import { getSubagentProfile, SUBAGENT_PROFILE_NAMES } from './byok-subagent-profiles.js'
59
+ import { configPath } from './config-dir.js'
60
+ import { turnOutcomeField, outcomeFromByokTurn } from './turn-outcome.js'
38
61
 
39
62
  const log = createLogger('byok-session')
40
63
 
@@ -55,13 +78,85 @@ const MAX_HISTORY_TURNS = 50
55
78
  // up an unbounded API bill.
56
79
  const MAX_TOOL_ROUNDS = 25
57
80
 
81
+ // #8559: the assistant turn kept in history when a requested Stop lands before the
82
+ // model streamed any text. The API refuses an empty text block, and leaving the
83
+ // assistant slot out would put the stopped prompt and the next one back to back.
84
+ const STOPPED_BEFORE_TEXT = '[Interrupted by the user before any reply was produced.]'
85
+ // ...and the tool_result answering a tool_use whose result the Stop kept from being
86
+ // recorded. It may already have run (an earlier tool in the same round can complete
87
+ // before a later one throws), so the model is told to check, not that it did not run.
88
+ const STOPPED_BEFORE_TOOL = 'Interrupted by the user before this result was recorded. The tool may or may not have run; check its effects before running it again.'
89
+
58
90
  // TTL for the per-session realpath cache used by validatePathWithinCwd
59
91
  // in the tool executor. The cwd shouldn't change mid-session, but caching
60
92
  // for 30s strikes a balance between safety (re-stat to catch a swap) and
61
93
  // performance (don't re-realpath the same cwd on every file op).
62
94
  const CWD_CACHE_TTL_MS = 30_000
63
95
 
96
+ // #6845: display cap for the server-controlled MCP-prompt expansion surfaced
97
+ // in the transcript (the honesty marker). The FULL resolved text still goes to
98
+ // the model as the user turn — only the copy shown in the transcript is capped
99
+ // so a huge `prompts/get` response can't flood the chat. event-normalizer.js
100
+ // re-bounds at the wire boundary and store-core re-bounds again (defense in
101
+ // depth), mirroring the #6768 compact_boundary bounding chain.
102
+ const MCP_PROMPT_EXPANSION_DISPLAY_CAP = 4000
103
+
104
+ // Post-#6845-review fix (thread 2): the suffix names that the model still got
105
+ // the full text — mirrors event-normalizer.js's and store-core's wording so a
106
+ // reader sees the same honest note regardless of which layer's copy they're
107
+ // looking at (the marker component, the mobile/System-tab `content` fallback
108
+ // below, a wire-bypassing replay, etc).
109
+ const MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX = '\n…(truncated for display; full text sent to the model)'
110
+
111
+ // Bound an MCP-prompt expansion to the display cap, appending a truncation
112
+ // marker when it overflows. Returns the (possibly truncated) text plus a
113
+ // `truncated` flag so the renderer can badge it.
114
+ //
115
+ // Post-#6845-review fix (thread 2): previously sliced to `cap` and THEN
116
+ // appended the suffix, so the returned string could exceed `cap` by the
117
+ // suffix's length. The slice length now subtracts the suffix's own length so
118
+ // `text.length` (slice + suffix) never exceeds `cap` — computed from the
119
+ // suffix's actual `.length` rather than a hardcoded magic number, so this
120
+ // stays correct if the wording changes again.
121
+ function boundMcpPromptExpansionText(text, cap = MCP_PROMPT_EXPANSION_DISPLAY_CAP) {
122
+ const s = typeof text === 'string' ? text : String(text ?? '')
123
+ if (s.length <= cap) return { text: s, truncated: false }
124
+ const sliceLen = Math.max(0, cap - MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX.length)
125
+ return { text: `${s.slice(0, sliceLen)}${MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX}`, truncated: true }
126
+ }
127
+
128
+ // Provider factories that add a layer above ClaudeByokSession must preserve
129
+ // both the BaseSession contract and BYOK's own constructor-only options. The
130
+ // BaseSession picker alone intentionally cannot know about MCP discovery or
131
+ // project-instruction loading, so using it directly in a BYOK subclass would
132
+ // silently drop those controls before ClaudeByokSession can consume them.
133
+ export const BYOK_SESSION_LOCAL_OPT_KEYS = Object.freeze([
134
+ 'mcpConfigPath',
135
+ 'disabledMcpServers',
136
+ 'mcpToolCallTimeoutMs',
137
+ 'mcpStartCapMs',
138
+ '_mcpConfigFsync',
139
+ 'loadProjectInstructions',
140
+ '_instructionPolicyLoader',
141
+ '_machineInstructionPath',
142
+ '_machineInstructionRoot',
143
+ ])
144
+
145
+ export function buildByokSessionOpts(fullOpts = {}, overrides = {}) {
146
+ const picked = buildBaseSessionOpts(fullOpts)
147
+ for (const key of BYOK_SESSION_LOCAL_OPT_KEYS) {
148
+ if (key in fullOpts) picked[key] = fullOpts[key]
149
+ }
150
+ return { ...picked, ...overrides }
151
+ }
152
+
64
153
  export class ClaudeByokSession extends BaseSession {
154
+ static get customizationDescriptor() {
155
+ return BYOK_CUSTOMIZATION
156
+ }
157
+
158
+ static agentConnectionRoutes = ['api']
159
+ static agentConnectionCredentialKey = 'ANTHROPIC_API_KEY'
65
160
  // #5858: Claude-family flag — single source of truth for isClaudeProvider().
66
161
  // DockerByokSession (docker-byok) extends this and correctly inherits it.
67
162
  // NOTE: non-Claude providers that ALSO extend this for the agent loop
@@ -73,6 +168,43 @@ export class ClaudeByokSession extends BaseSession {
73
168
  return 'Claude (API key — BYOK)'
74
169
  }
75
170
 
171
+ /**
172
+ * #6769: build the end-of-turn context-window OCCUPANCY snapshot from the
173
+ * FINAL agent-loop round's individual usage.
174
+ *
175
+ * That round's `input_tokens + cache_read_input_tokens +
176
+ * cache_creation_input_tokens` is exactly the prompt the API was last sent
177
+ * — i.e. the conversation's current size — so it is a true occupancy
178
+ * snapshot. The summed `turnUsage` billing aggregate is NOT (it re-counts
179
+ * the history once per round; a 5-round turn over-reads ≈5× — the #6816
180
+ * review finding). Output tokens are deliberately excluded (the coordinator
181
+ * contract pins the snapshot to the prompt side; the next turn's snapshot
182
+ * absorbs the reply), as is subagent usage (a child Task runs in its own
183
+ * separate window).
184
+ *
185
+ * Returns null when the turn produced no usable round usage (error before
186
+ * the first finalMessage(), or an endpoint that reports no usage — e.g. an
187
+ * anthropic-compatible server that omits the field). The result then emits
188
+ * WITHOUT `contextOccupancy` and clients keep their previous snapshot / dash.
189
+ *
190
+ * Static + pure so tests can pin the arithmetic without a live session;
191
+ * subclasses that reuse the agent loop (docker-byok, deepseek, ollama,
192
+ * anthropic-compatible) inherit it — wherever their endpoint reports real
193
+ * per-round usage, the snapshot is equally honest.
194
+ *
195
+ * @param {object|null} roundUsage — the final round's `final.usage`
196
+ * @returns {{totalTokens: number, source: 'final-round-prompt'}|null}
197
+ */
198
+ static _buildFinalRoundOccupancy(roundUsage) {
199
+ if (!roundUsage || typeof roundUsage !== 'object') return null
200
+ const totalTokens =
201
+ (Number(roundUsage.input_tokens) || 0) +
202
+ (Number(roundUsage.cache_read_input_tokens) || 0) +
203
+ (Number(roundUsage.cache_creation_input_tokens) || 0)
204
+ if (!Number.isFinite(totalTokens) || totalTokens <= 0) return null
205
+ return { totalTokens, source: 'final-round-prompt' }
206
+ }
207
+
76
208
  static get dataDir() {
77
209
  // BYOK does NOT depend on ~/.claude — no claude binary, no OAuth.
78
210
  // Returning null tells getProviderDataDirs() to skip this provider
@@ -87,6 +219,8 @@ export class ClaudeByokSession extends BaseSession {
87
219
  // PermissionManager (same machinery as claude-sdk).
88
220
  permissions: true,
89
221
  inProcessPermissions: true,
222
+ permissionFloor: true,
223
+ autoPermissionMode: true,
90
224
  modelSwitch: true,
91
225
  permissionModeSwitch: true,
92
226
  planMode: false,
@@ -97,18 +231,35 @@ export class ClaudeByokSession extends BaseSession {
97
231
  // Thinking config supported by the SDK but not wired through the
98
232
  // chroxy UI yet — leave off until the toggle lands.
99
233
  thinkingLevel: false,
234
+ // #7725: BYOK builds its own request and never calls
235
+ // detectThinkingKeyword — the magic words reach the model as plain prose.
236
+ // Inherited by the anthropic-compatible / openai-compatible factories,
237
+ // DeepSeek, Ollama and docker-byok, which all extend this class.
238
+ thinkingKeywords: false,
239
+ thinkingLevelEffective: false, // #8700: no report of the applied level
100
240
  streaming: true,
101
241
  // We rebuild the system prompt on every turn from
102
242
  // _buildSystemPrompt(), so an activate/deactivate of a skill
103
243
  // takes effect on the next user message. Same property as the
104
244
  // SDK provider.
105
245
  skillToggle: true,
246
+ // #6888: BYOK shares SdkSession's PermissionManager/respondToPermission
247
+ // path — see the matching comment in sdk-session.js's capabilities. A
248
+ // deny reason genuinely reaches the agent as the tool's denial message.
249
+ denyReason: true,
106
250
  }
107
251
  }
108
252
 
109
253
  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 /
254
+ // #8574: `tool_start` / `tool_result` are deliberately NOT listed. They are
255
+ // PROXIED events (session-manager.js PROXIED_SESSION_EVENTS): the proxied
256
+ // listener forwards them AND records them to history, so listing them
257
+ // here added a second, transient listener and every frame reached the
258
+ // client twice. tool-events-overlap guard:
259
+ // tests/provider-custom-events-overlap.test.js.
260
+ //
261
+ // tool_input_delta is surfaced per turn for the dashboard's tool-call
262
+ // bubble UI. permission_request /
112
263
  // user_question / permission_resolved are re-emitted from
113
264
  // PermissionManager and already known to the SessionManager
114
265
  // forwarding pipeline, but list them here so the capability matrix
@@ -133,7 +284,7 @@ export class ClaudeByokSession extends BaseSession {
133
284
  // accumulator and the final summary text becomes the parent's
134
285
  // Task tool_result content; replaying it as a nested event would
135
286
  // double-render the same content.
136
- return ['tool_start', 'tool_result', 'tool_input_delta', 'agent_spawned', 'agent_completed', 'agent_event']
287
+ return ['tool_input_delta', 'agent_spawned', 'agent_completed', 'agent_event']
137
288
  }
138
289
 
139
290
  /**
@@ -146,7 +297,7 @@ export class ClaudeByokSession extends BaseSession {
146
297
  label: 'Claude (BYOK)',
147
298
  credentials: {
148
299
  envVars: ['ANTHROPIC_API_KEY'],
149
- hint: `set ANTHROPIC_API_KEY or save it in ${join(homedir(), '.chroxy', 'credentials.json')} (mode 0600)`,
300
+ hint: `set ANTHROPIC_API_KEY or save it in ${configPath('credentials.json')} (mode 0600)`,
150
301
  optional: false,
151
302
  },
152
303
  }
@@ -228,23 +379,36 @@ export class ClaudeByokSession extends BaseSession {
228
379
  * overrides (system prompt, settings) can be added as distinct named opts when
229
380
  * any of them are actually used.
230
381
  * @param {number} [opts.mcpToolCallTimeoutMs] Per-tools/call timeout; null/undefined = MCPClient default (30s).
382
+ * @param {Function} [opts._mcpConfigFsync] TEST-ONLY (#7070): `(target, { isDir }) => void` fsync
383
+ * seam forwarded to the MCP-config remove write, so a test can fail the post-rename directory
384
+ * fsync. Production never passes it; undefined keeps the real `fsyncForDurability`.
231
385
  */
232
386
  constructor(opts = {}) {
233
387
  super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-byok' }))
234
388
  // Anthropic SDK client; lazily instantiated in start() so unit tests
235
389
  // can stub it via this._client = ... before start().
236
390
  this._client = null
391
+ this._instructionPolicyLoader = opts._instructionPolicyLoader || loadByokInstructionPolicy
392
+ this._loadProjectInstructions = opts.loadProjectInstructions === true || Boolean(opts._instructionPolicyLoader)
393
+ this._machineInstructionPath = opts._machineInstructionPath
394
+ this._machineInstructionRoot = opts._machineInstructionRoot
395
+ this._instructionPolicyLoaded = false
237
396
  // In-memory conversation history. Each entry is a Claude API message
238
397
  // ({ role: 'user'|'assistant', content: <string|array> }). The SDK
239
398
  // accepts either shape for user/assistant turns.
240
399
  this._history = []
241
400
  // AbortController for the active stream so interrupt() can cancel.
242
401
  this._abortController = null
402
+ // #8553: this turn's abort was driven by a parent session (see interrupt()).
403
+ this._abortCascaded = false
243
404
 
244
405
  // PermissionManager + event re-emission via the shared wiring (P2-9) so the
245
406
  // dashboard / mobile permission UI and the audit log work uniformly across
246
407
  // providers. ByokSession passes no pause/resume hooks (no result-timeout).
247
- this._permissions = new PermissionManager({ log })
408
+ // #6794 — pass cwd so the protected-path floor can resolve relative tool
409
+ // targets (.git/.claude/.env…) against this session's working directory.
410
+ // #6771 — pass the durable rule store (persistent per-project allow-always).
411
+ this._permissions = new PermissionManager({ log, cwd: this.cwd, ruleStore: this._permissionRuleStore })
248
412
  wirePermissionManager(this, this._permissions)
249
413
 
250
414
  // Realpath cache used by the tool executor's path-safety check. One
@@ -269,17 +433,28 @@ export class ClaudeByokSession extends BaseSession {
269
433
  // pair" — not "one warn per current model."
270
434
  this._pricingWarnedModels = new Set()
271
435
 
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()
436
+ // #6756: per-stream index → thinking messageId. The translated
437
+ // `thinking_delta` events carry only the block index; this maps each
438
+ // thinking block's index to the distinct thinking id we open on its first
439
+ // delta so subsequent deltas + the content_block_stop route correctly.
440
+ // Entry is deleted on `content_block_stop`; the whole map is also cleared
441
+ // after each round and on every turn exit path. Kept inside the session
442
+ // (not the translator) per #4059's boundary call: the translator stays
443
+ // pure, stateful tracking lives here. (#8137 removed the matching
444
+ // index→toolUseId map: tool input is now read off `final.content`, so
445
+ // nothing resolves a streaming index back to a tool_use id any more.)
446
+ this._streamingIndexToThinkingId = new Map()
447
+ // #6630: the turn the thinking-stream counter below belongs to, and the counter.
448
+ this._thinkingSeqTurn = null
449
+ this._thinkingSeq = 0
450
+
451
+ // #6391 (chat-redesign footer-stat): thinking messageId → performance.now()
452
+ // when the reasoning block opened, so its content_block_stop can stamp the
453
+ // elapsed `thinkingDurationMs` on the thinking stream_end. Cleared alongside
454
+ // `_streamingIndexToThinkingId`. #6943: monotonic clock (perf_hooks), not
455
+ // Date.now() — wall-clock jumps (NTP step, manual change, DST) would
456
+ // otherwise clamp a backward jump to 0 or inflate a forward jump.
457
+ this._thinkingStartMs = new Map()
283
458
 
284
459
  // #4080: toolUseIds whose permission_request is currently pending.
285
460
  // Populated when this session re-emits permission_request (line
@@ -329,6 +504,10 @@ export class ClaudeByokSession extends BaseSession {
329
504
  // leak into a future turn.
330
505
  this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
331
506
  this._subagentCostThisTurn = 0
507
+ // #8569: tool_use ids whose `tool_result` event already went out this turn, so a
508
+ // Stop that settles `_history` with synthesized results closes only the rows
509
+ // still open and never emits a second result for a tool that has one.
510
+ this._toolResultsEmitted = new Set()
332
511
 
333
512
  // #5018: per-session built-in tool allowlist. Set by _executeTaskTool
334
513
  // ONLY on child sessions spawned with a `subagent_type` profile that
@@ -348,12 +527,42 @@ export class ClaudeByokSession extends BaseSession {
348
527
  // session only reads the `mcpServers` block, so a separate
349
528
  // "whole Claude config" knob added no behavior over
350
529
  // `mcpConfigPath` and had no callers. See constructor JSDoc.
351
- const mcpConfig = loadClaudeMcpConfig(opts.mcpConfigPath)
530
+ // #6974: retain the resolved config path so the add/remove mutation path
531
+ // writes back to the SAME file this session read from (a test override or
532
+ // $CHROXY_CLAUDE_CONFIG must not be bypassed on the write half).
533
+ this._mcpConfigPath = opts.mcpConfigPath || defaultClaudeConfigPath()
534
+ // #7070: test-only fsync seam for the config write; see the constructor JSDoc.
535
+ this._mcpConfigFsync = opts._mcpConfigFsync
536
+ // #7112: `opts.mcpConfigPath === null` (a Task subagent, see
537
+ // `_executeTaskTool`) explicitly SKIPS discovery — the child does not
538
+ // parse a second copy of ~/.claude.json / <cwd>/.mcp.json and does not
539
+ // spawn its own fleet. `this.cwd` is set by the BaseSession super() call
540
+ // above, so it is available here. Resolves project scope
541
+ // (`projects[<realpath(cwd)>].mcpServers`), repo-local `.mcp.json`, and
542
+ // user root — the same three sources, in the same precedence order,
543
+ // `discoverConfiguredMcpServers` reads via the shared
544
+ // `readMcpSourcesInPrecedenceOrder` helper — instead of only ever
545
+ // reading the config's root `mcpServers` block.
546
+ const mcpConfig = opts.mcpConfigPath === null
547
+ ? { servers: [], warnings: [] }
548
+ : discoverMcpServerSpecs(this.cwd, { configPath: this._mcpConfigPath })
352
549
  for (const warning of mcpConfig.warnings) {
353
550
  log.warn(`BYOK MCP config: ${warning}`)
354
551
  }
355
552
  this._mcpServerConfigs = mcpConfig.servers
356
553
  this.mcpServers = Object.freeze(mcpConfig.servers.map(toMcpServerMetadata))
554
+ // #6824: per-session set of parked (disabled) MCP server names. Seeded from
555
+ // the persisted `disabledMcpServers` opt (session-manager forwards the
556
+ // restored set), filtered to names actually present in this session's
557
+ // config so a stale entry can't wedge. Threaded into the MCPFleet at
558
+ // start() (parked servers get no client) and round-tripped back to session
559
+ // state via `getDisabledMcpServers()`. Byok-local opt — read straight off
560
+ // `opts`, not a BaseSession key.
561
+ const configuredMcpNames = new Set(mcpConfig.servers.map((s) => s.name))
562
+ this._disabledMcpServers = new Set(
563
+ (Array.isArray(opts.disabledMcpServers) ? opts.disabledMcpServers : [])
564
+ .filter((name) => typeof name === 'string' && configuredMcpNames.has(name)),
565
+ )
357
566
  // #4077: MCPFleet is lazy — created in start() only if servers exist.
358
567
  // Held here so destroy() can tear down even if start() never ran.
359
568
  this._mcpFleet = null
@@ -410,7 +619,74 @@ export class ClaudeByokSession extends BaseSession {
410
619
  return getModelPricing(model)
411
620
  }
412
621
 
622
+ /**
623
+ * #7012: lazily construct + start the MCP fleet from whatever is currently in
624
+ * `_mcpServerConfigs`, exactly once. Extracted out of `start()` (which was the
625
+ * ONLY caller pre-#7012) so `addMcpServer` can reach the same construction path:
626
+ * a session that started with zero configured MCP servers never created a
627
+ * fleet, so `addMcpServer`'s old `if (this._mcpFleet)` gate skipped the
628
+ * fleet-attach step entirely — the server was persisted but stayed
629
+ * unconnected until a restart. `addMcpServer` appends the new entry to
630
+ * `_mcpServerConfigs` BEFORE calling this, so the fleet's constructor (which
631
+ * spawns one client per config) picks the new server up directly; no separate
632
+ * `fleet.addServer()` call is needed on that path.
633
+ *
634
+ * Single-flight without extra bookkeeping: `this._mcpFleet` is assigned
635
+ * SYNCHRONOUSLY, before the `await fleet.start()` below — the same
636
+ * synchronous stretch that reads `_mcpServerConfigs` and decides whether to
637
+ * call this method (see `addMcpServer`). JS never preempts mid-synchronous-
638
+ * stretch, so two concurrent `addMcpServer` calls can never both observe
639
+ * `_mcpFleet` as null: whichever runs first sets it before yielding on the
640
+ * `await`, and the other sees it already set and falls through to the
641
+ * existing-fleet `fleet.addServer()` branch instead of racing a second
642
+ * `new MCPFleet(...)`.
643
+ *
644
+ * Guards:
645
+ * - zero configured servers → no fleet (mirrors the pre-#7012 `start()`
646
+ * guard — nothing to spawn).
647
+ * - `_destroying` → no fleet (a session torn down mid-add must not spawn a
648
+ * new MCP child that `destroy()` has already finished looking for).
649
+ */
650
+ async _ensureMcpFleet() {
651
+ if (this._mcpFleet) return this._mcpFleet
652
+ if (this._destroying || this._mcpServerConfigs.length === 0) return null
653
+ // #4457: pass the session's PermissionManager so the fleet can
654
+ // emit a trust prompt for a not-yet-trusted spawn config (#7001: name +
655
+ // command + the full args + env).
656
+ // Tuples already trusted in ~/.chroxy/mcp-trust.json spawn directly
657
+ // with no prompt; denied tuples set state=DEAD without spawning.
658
+ // #4456: forward startCapMs override so operators can tune the
659
+ // session-start wall-clock cap. Passing undefined lets the fleet's
660
+ // constructor default (DEFAULT_FLEET_START_CAP_MS) win — exactly
661
+ // what we want when no override is in play.
662
+ const fleetOpts = { log, permissionManager: this._permissions }
663
+ if (this._mcpStartCapMs !== null) fleetOpts.startCapMs = this._mcpStartCapMs
664
+ // #6824: seed the fleet with the persisted parked set so a respawn skips
665
+ // starting servers the operator disabled before the restart.
666
+ fleetOpts.disabledServers = [...this._disabledMcpServers]
667
+ const fleet = new MCPFleet(this._mcpServerConfigs, fleetOpts)
668
+ this._mcpFleet = fleet
669
+ await fleet.start()
670
+ return fleet
671
+ }
672
+
413
673
  async start() {
674
+ // API-driven BYOK providers have no vendor-native project-file discovery.
675
+ // Compile before client creation so malformed/over-budget policy cannot
676
+ // reach a model. Container cwd mapping is not yet verified.
677
+ if (this._loadProjectInstructions && !this._instructionPolicyLoaded && !this.constructor.capabilities?.containerized) {
678
+ const projection = await this._instructionPolicyLoader({
679
+ cwd: this.cwd,
680
+ ...(this._machineInstructionPath !== undefined
681
+ ? { machinePath: this._machineInstructionPath }
682
+ : {}),
683
+ ...(this._machineInstructionRoot !== undefined
684
+ ? { machineRoot: this._machineInstructionRoot }
685
+ : {}),
686
+ })
687
+ this._installProjectInstructionProjection(projection)
688
+ this._instructionPolicyLoaded = true
689
+ }
414
690
  if (this._client === null) {
415
691
  // Spike (BYOK direct) confirmed the SDK's standard constructor
416
692
  // works fine; baseURL defaults to api.anthropic.com.
@@ -440,36 +716,474 @@ export class ClaudeByokSession extends BaseSession {
440
716
  // tools, identical to a server missing from config. We deliberately
441
717
  // wait for fleet.start() so this.mcpServers + tools list are stable
442
718
  // 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
- }
719
+ // #7012: extracted into _ensureMcpFleet so addMcpServer can reach the
720
+ // SAME construction path for a session that started with zero MCP
721
+ // servers configured (previously only start() ever created a fleet).
722
+ await this._ensureMcpFleet()
457
723
 
458
724
  this._processReady = true
459
725
  this.emit('ready', { sessionId: null, model: this.model, tools: [] })
726
+ // #6824: BYOK is the authoritative MCP lane — publish the live server list
727
+ // (with per-server enabled/canToggle) so the dashboard/mobile MCP views can
728
+ // render the enable/disable toggle. sdk/cli parse their list off the live
729
+ // stream; the BYOK fleet is in-daemon, so we emit it here after start().
730
+ this._emitMcpServers()
731
+ }
732
+
733
+ /**
734
+ * #6824: build the `mcp_servers` broadcast payload — one entry per configured
735
+ * server with `{ name, status, enabled, canToggle: true }`. When the fleet
736
+ * exists (the normal post-start case) its `getServerStatuses()` is
737
+ * authoritative (live states + parked servers). Before start() / when the
738
+ * fleet never spun up, fall back to the static config list so the payload is
739
+ * still coherent (parked → 'disabled', otherwise 'configured').
740
+ */
741
+ _buildMcpServersPayload() {
742
+ if (this._mcpFleet) return this._mcpFleet.getServerStatuses()
743
+ return this._mcpServerConfigs.map((cfg) => {
744
+ const disabled = this._disabledMcpServers.has(cfg.name)
745
+ const scope = mcpSourceToWriteScope(cfg.source)
746
+ return {
747
+ name: cfg.name,
748
+ status: disabled ? 'disabled' : 'configured',
749
+ enabled: !disabled,
750
+ canToggle: true,
751
+ // #7028: same rule as the fleet's snapshot — present only when known.
752
+ ...(scope ? { scope } : {}),
753
+ }
754
+ })
755
+ }
756
+
757
+ /**
758
+ * #6824: emit the current MCP server list to all subscribers. Best-effort —
759
+ * a throwing listener must not escape the ready / toggle paths this is called
760
+ * from (mirrors claude-tui-session `_emitConfiguredMcpServers`). No servers
761
+ * configured → nothing to publish.
762
+ */
763
+ _emitMcpServers({ force = false } = {}) {
764
+ // #6974: `force` exists for the remove path. The zero-config early return
765
+ // is right on the ready path (nothing configured → nothing to publish), but
766
+ // removing the LAST configured server also lands on zero — and skipping the
767
+ // emit there would leave every client rendering the row we just deleted.
768
+ if (this._mcpServerConfigs.length === 0 && !force) return
769
+ try {
770
+ this.emit('mcp_servers', { servers: this._buildMcpServersPayload() })
771
+ } catch (err) {
772
+ log.warn(`BYOK MCP: mcp_servers emit failed: ${err?.message || err}`)
773
+ }
774
+ }
775
+
776
+ /**
777
+ * #6824: enable or disable a single configured MCP server for this session.
778
+ * Delegates the park/unpark to the fleet (destroy-and-forget vs
779
+ * rebuild-through-trust-gate), updates the persisted parked set, and
780
+ * re-emits `mcp_servers` so every connected client converges. Returns
781
+ * `{ found, changed, status }` — `found: false` when `name` is not a
782
+ * configured server so the WS handler can surface a clean error.
783
+ */
784
+ async setMcpServerEnabled(name, enabled) {
785
+ if (typeof name !== 'string' || !this._mcpServerConfigs.some((c) => c.name === name)) {
786
+ return { found: false, changed: false, status: null }
787
+ }
788
+ let result
789
+ if (this._mcpFleet) {
790
+ result = await this._mcpFleet.setEnabled(name, enabled)
791
+ // Sync the persisted set from the fleet's AUTHORITATIVE one rather than
792
+ // applying the requested state — the fleet's in-flight churn latch can
793
+ // legitimately ignore this toggle (changed:false while another park/
794
+ // unpark for the same server is awaiting), and blindly recording the
795
+ // request here would diverge what respawn honours from what actually ran.
796
+ this._disabledMcpServers = new Set(this._mcpFleet.disabledServers)
797
+ } else {
798
+ // Fleet not yet started (no servers spawned): just record intent so
799
+ // start() honours it. Treat as changed only if the set actually moves.
800
+ const was = this._disabledMcpServers.has(name)
801
+ result = { found: true, changed: was === enabled, status: enabled ? 'configured' : 'disabled' }
802
+ if (enabled) this._disabledMcpServers.delete(name)
803
+ else this._disabledMcpServers.add(name)
804
+ }
805
+ if (result.changed) this._emitMcpServers()
806
+ return result
807
+ }
808
+
809
+ /**
810
+ * #6822: submit a pasted OAuth authorization code for a remote MCP server that
811
+ * reported `oauth-required`. Delegates redemption + authenticated reconnect to
812
+ * the fleet, then re-emits `mcp_servers` so every client converges on the new
813
+ * status. Returns `{ found, ok?, status?, error? }`; `found: false` when the
814
+ * server isn't configured (or the fleet never started), so the WS handler can
815
+ * surface a clean error. The code + tokens never touch a log or the wire.
816
+ */
817
+ async submitMcpAuthCode(name, code) {
818
+ if (typeof name !== 'string' || !this._mcpServerConfigs.some((c) => c.name === name)) {
819
+ return { found: false }
820
+ }
821
+ if (!this._mcpFleet) {
822
+ return { found: false }
823
+ }
824
+ const result = await this._mcpFleet.submitAuthCode(name, code)
825
+ if (result?.ok) this._emitMcpServers()
826
+ return result
827
+ }
828
+
829
+ /**
830
+ * #6974: rebuild the frozen `mcpServers` metadata view after a config
831
+ * mutation. `this.mcpServers` is the read-only, credential-stripped list other
832
+ * surfaces read, so it must track `_mcpServerConfigs` on add/remove.
833
+ */
834
+ _refreshMcpServerMetadata() {
835
+ this.mcpServers = Object.freeze(this._mcpServerConfigs.map(toMcpServerMetadata))
836
+ }
837
+
838
+ /**
839
+ * The trust-store path this session's gates use. Resolved through
840
+ * `defaultTrustStorePath()` (which honours `CHROXY_MCP_TRUST_PATH`) so the
841
+ * session's pre-write gate and the fleet's spawn-time gate always agree on the
842
+ * same file — the fleet resolves it the same way when no override is passed.
843
+ */
844
+ _mcpTrustStorePath() {
845
+ return defaultTrustStorePath()
846
+ }
847
+
848
+ /**
849
+ * #7001: obtain the user's SPAWN-TRUST decision for `cfg` BEFORE its config
850
+ * entry is persisted.
851
+ *
852
+ * Why this cannot be left to the fleet's spawn-time gate alone: the gate runs
853
+ * after the write, so a denial left the server configured. The user said "no",
854
+ * yet the entry stayed in `~/.claude.json` and re-prompted on every subsequent
855
+ * session start — one accidental "allow" (or a UI that auto-confirms) later and
856
+ * it runs. Deciding first means a denied add persists NOTHING.
857
+ *
858
+ * Same gate the fleet uses, so the two cannot disagree: same trust store, same
859
+ * `withTrustStoreLock` critical section (load → prompt → recordTrust), same
860
+ * `requestMcpTrust` payload shape (header/env VALUES never included). On allow
861
+ * the decision is recorded, so the fleet's own gate then sees `isTrusted` and
862
+ * does NOT prompt a second time for the same add.
863
+ *
864
+ * The lock is NOT held across the subsequent write/fleet-attach —
865
+ * `withTrustStoreLock` is not re-entrant and the fleet's gate takes it again.
866
+ *
867
+ * No PermissionManager → no gate, exactly as in `MCPFleet._makeClient` (#4457):
868
+ * there is no one to ask, and this must not become a hard failure for headless
869
+ * contexts that never had a trust prompt in the first place.
870
+ *
871
+ * @returns {Promise<{ allowed: boolean, prompted: boolean }>}
872
+ */
873
+ async _decideMcpSpawnTrust(cfg) {
874
+ const pm = this._permissions
875
+ if (!pm || typeof pm.requestMcpTrust !== 'function') return { allowed: true, prompted: false }
876
+ const trustPath = this._mcpTrustStorePath()
877
+ return withTrustStoreLock(trustPath, async () => {
878
+ const store = loadTrustStore(trustPath, { log })
879
+ if (isTrusted(store, cfg)) return { allowed: true, prompted: false }
880
+ const isRemote = typeof cfg.url === 'string' && cfg.url.length > 0
881
+ // #7939: forward the scope this add targets (see mcpWriteScopeToSource
882
+ // above) so the pre-write trust prompt names where the server is being
883
+ // configured, same as a rediscovered spec's prompt would.
884
+ const trustReq = isRemote
885
+ ? { name: cfg.name, url: cfg.url, headerKeys: Object.keys(cfg.headers || {}).sort(), source: cfg.source }
886
+ : { name: cfg.name, command: cfg.command, args: cfg.args, envKeys: Object.keys(cfg.env || {}).sort(), source: cfg.source }
887
+ const allowed = await pm.requestMcpTrust(trustReq)
888
+ if (allowed) recordTrust(cfg, trustPath)
889
+ return { allowed: allowed === true, prompted: true }
890
+ })
891
+ }
892
+
893
+ /**
894
+ * Build the in-memory fleet config from a normalized persisted entry, filling
895
+ * the shape defaults (`args`/`env` for stdio, `headers` for remote) the fleet
896
+ * and the trust key both read.
897
+ *
898
+ * #7939: optional `source` (an `MCP_SERVER_SOURCE` value) tags where this
899
+ * config came from — a discovered spec already carries one from
900
+ * `discoverMcpServerSpecs`, but a live `addMcpServer` entry has none until
901
+ * the caller derives it from the WRITE scope via `mcpWriteScopeToSource` and
902
+ * passes it here, so both paths converge on the same shape before either
903
+ * reaches the spawn-trust gate.
904
+ */
905
+ static _mcpCfgFromEntry(name, entry, { source } = {}) {
906
+ const cfg = { name, ...entry }
907
+ if (cfg.command !== undefined) {
908
+ cfg.args = Array.isArray(cfg.args) ? cfg.args : []
909
+ cfg.env = cfg.env && typeof cfg.env === 'object' ? cfg.env : {}
910
+ } else {
911
+ cfg.headers = cfg.headers && typeof cfg.headers === 'object' ? cfg.headers : {}
912
+ }
913
+ if (source !== undefined) cfg.source = source
914
+ return cfg
915
+ }
916
+
917
+ /**
918
+ * #6974: add a brand-new MCP server — a CONFIG MUTATION, not a runtime toggle.
919
+ *
920
+ * Order (tightened by #7001):
921
+ * 1. validate + PLAN the write (`planAddMcpServerToConfig`) — every check the
922
+ * commit performs, no write. Yields the exact normalized entry that would
923
+ * be persisted, so the trust decision is made against precisely the config
924
+ * that would run, and a name that would fail (EXISTS / invalid) never
925
+ * raises a prompt.
926
+ * 2. obtain the spawn-trust decision for that entry. DENIED → return without
927
+ * writing anything: the user's config is untouched.
928
+ * 3. commit the config write — the durability commit point. If it fails,
929
+ * nothing about the live session changed.
930
+ * 4. only then attach to the live fleet, so a user can never end up with a
931
+ * running server that vanishes on restart.
932
+ *
933
+ * Adding is still not, by itself, permission to execute: step 2 IS that
934
+ * permission, and the fleet's independent gate re-checks it at spawn time (a
935
+ * config entry that is persisted but untrusted — e.g. hand-added to
936
+ * `~/.claude.json`, or trusted-then-tampered — still prompts).
937
+ *
938
+ * Returns `{ ok, error?, code?, status? }`. `code: 'EXISTS'` distinguishes a
939
+ * duplicate name from a generic validation failure; `code: 'TRUST_DENIED'`
940
+ * distinguishes "the user said no" from a failure.
941
+ */
942
+ async addMcpServer(name, config, scope = 'user', { isAuthorized } = {}) {
943
+ const valid = validateNewMcpServerName(name)
944
+ if (!valid.ok) return { ok: false, error: valid.error }
945
+
946
+ let planned
947
+ try {
948
+ planned = planAddMcpServerToConfig({
949
+ name: valid.name,
950
+ config,
951
+ scope,
952
+ cwd: this.cwd,
953
+ configPath: this._mcpConfigPath,
954
+ })
955
+ } catch (err) {
956
+ return { ok: false, error: `Failed to read MCP config: ${err?.message || String(err)}` }
957
+ }
958
+ if (!planned.ok) return { ok: false, error: planned.error, code: planned.code }
959
+
960
+ // The candidate config, exactly as it would be persisted and spawned.
961
+ // #7939: tag it with the scope the user is adding it to (mapped onto the
962
+ // same MCP_SERVER_SOURCE vocabulary discovery uses) so the trust prompt
963
+ // for THIS add names its scope consistently with a rediscovered server.
964
+ const cfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, planned.entry, {
965
+ source: mcpWriteScopeToSource(planned.scope),
966
+ })
967
+
968
+ const trust = await this._decideMcpSpawnTrust(cfg)
969
+ if (!trust.allowed) {
970
+ return {
971
+ ok: false,
972
+ code: 'TRUST_DENIED',
973
+ error: `Spawning MCP server '${valid.name}' was denied, so it was not added to the config.`,
974
+ }
975
+ }
976
+
977
+ // The trust prompt above was a wait: the requesting connection may have ended.
978
+ assertAuthorized(isAuthorized)
979
+
980
+ let written
981
+ try {
982
+ written = addMcpServerToConfig({
983
+ name: valid.name,
984
+ config,
985
+ scope,
986
+ cwd: this.cwd,
987
+ configPath: this._mcpConfigPath,
988
+ })
989
+ } catch (err) {
990
+ // A throw here is an I/O failure (permissions, ENOSPC, a failed fsync) —
991
+ // the atomic writer leaves the original file intact, so the session is
992
+ // still coherent. Surface it without echoing config contents.
993
+ return { ok: false, error: `Failed to write MCP config: ${err?.message || String(err)}` }
994
+ }
995
+ if (!written.ok) return { ok: false, error: written.error, code: written.code }
996
+
997
+ // #7002: the config's existing mode is PRESERVED by design, so a
998
+ // group/world-readable `~/.claude.json` that just received `env`/`headers`
999
+ // (routinely API tokens) is a case where we are the party making things
1000
+ // worse. Say so loudly in the daemon log — it never echoes a secret value —
1001
+ // and hand it to the caller so a client can surface it too.
1002
+ if (written.warning) log.warn(`BYOK MCP: ${written.warning}`)
1003
+
1004
+ // Mirror the persisted entry into the in-memory config list. `entry` is the
1005
+ // NORMALIZED object that was actually written, so memory and disk cannot
1006
+ // diverge. Normalization is pure over (name, config), so this is structurally
1007
+ // identical to the `cfg` the trust decision was made against — and if it ever
1008
+ // were not, the fleet's own gate below would see an untrusted config and
1009
+ // prompt rather than spawn. #7939: carries the same write-scope-derived
1010
+ // `source` as `cfg` above, so a live-added server's fleet re-prompt (the
1011
+ // backstop in `MCPFleet.addServer`/`_makeClient`) shows the identical scope.
1012
+ const persistedCfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, written.entry, {
1013
+ source: mcpWriteScopeToSource(written.scope),
1014
+ })
1015
+ this._mcpServerConfigs = [...this._mcpServerConfigs, persistedCfg]
1016
+ this._refreshMcpServerMetadata()
1017
+
1018
+ let status = 'configured'
1019
+ if (this._mcpFleet) {
1020
+ const result = await this._mcpFleet.addServer(persistedCfg)
1021
+ if (result.status) status = result.status
1022
+ } else if (this._processReady) {
1023
+ // #7012: no fleet exists yet — either this is the session's first-ever
1024
+ // MCP server, or start() never spun one up because zero servers were
1025
+ // configured at start. `_mcpServerConfigs` already carries this server
1026
+ // (appended above), so `_ensureMcpFleet`'s constructor picks it up
1027
+ // directly; `fleet.addServer()` is not called on this path — see that
1028
+ // method's docstring for why.
1029
+ const fleet = await this._ensureMcpFleet()
1030
+ if (fleet) {
1031
+ const entry = fleet.getServerStatuses().find((s) => s.name === persistedCfg.name)
1032
+ if (entry?.status) status = entry.status
1033
+ }
1034
+ }
1035
+ // else: addMcpServer was called before start() (production only ever
1036
+ // reaches a started session — the WS handler requires one). Leave status
1037
+ // 'configured' and let start() pick the persisted entry up normally,
1038
+ // rather than spawning an MCP child ahead of `_processReady`.
1039
+ this._emitMcpServers()
1040
+ const result = { ok: true, status }
1041
+ if (written.warning) result.warning = written.warning
1042
+ return result
460
1043
  }
461
1044
 
462
- async sendMessage(prompt, attachments, _options = {}) {
1045
+ /**
1046
+ * #6974: permanently remove a configured MCP server — the counterpart to
1047
+ * `addMcpServer`, and distinct from `setMcpServerEnabled(name, false)` (which
1048
+ * parks a server that stays configured).
1049
+ *
1050
+ * The config write is again the commit point and happens first: removal is a
1051
+ * capability REDUCTION, so it must be durable before the live fleet stops
1052
+ * enforcing it. `found: false` (absent from the requested scope) is reported
1053
+ * without touching the fleet, so a mis-scoped remove cannot disconnect a
1054
+ * server it did not remove from disk.
1055
+ *
1056
+ * Returns `{ ok, found?, error? }`.
1057
+ */
1058
+ async removeMcpServer(name, scope = 'user') {
1059
+ const valid = validateMcpServerNameForRemoval(name)
1060
+ if (!valid.ok) return { ok: false, error: valid.error }
1061
+
1062
+ let written
1063
+ try {
1064
+ written = removeMcpServerFromConfig({
1065
+ name: valid.name,
1066
+ scope,
1067
+ cwd: this.cwd,
1068
+ configPath: this._mcpConfigPath,
1069
+ _fsync: this._mcpConfigFsync,
1070
+ })
1071
+ } catch (err) {
1072
+ return { ok: false, error: `Failed to write MCP config: ${err?.message || String(err)}` }
1073
+ }
1074
+ if (!written.ok) return { ok: false, error: written.error }
1075
+ if (!written.found) return { ok: true, found: false }
1076
+
1077
+ this._mcpServerConfigs = this._mcpServerConfigs.filter((c) => c.name !== valid.name)
1078
+ this._refreshMcpServerMetadata()
1079
+ this._disabledMcpServers.delete(valid.name)
1080
+ if (this._mcpFleet) await this._mcpFleet.removeServer(valid.name)
1081
+ // force: removing the last configured server still has to publish the now-
1082
+ // empty list, or clients keep rendering the row we just deleted.
1083
+ this._emitMcpServers({ force: true })
1084
+ // #7054/#7068: surface the durability caveat on the REDUCTION path. The
1085
+ // removal IS in effect (fleet stopped, config rewritten), so this is a
1086
+ // warning riding a success — not a failure. Mirrors addMcpServer's existing
1087
+ // `warning` channel rather than inventing a second convention.
1088
+ if (written.durabilityUnconfirmed) {
1089
+ return {
1090
+ ok: true,
1091
+ found: true,
1092
+ warning:
1093
+ `The server was removed and is no longer running, but the config write could not be confirmed ` +
1094
+ `durable (${written.durabilityUnconfirmed}) — a power loss could restore it on the next start. ` +
1095
+ `Resolve the storage error and re-check.`,
1096
+ }
1097
+ }
1098
+ return { ok: true, found: true }
1099
+ }
1100
+
1101
+ /**
1102
+ * #6824: the parked (disabled) server names, sorted, for persistence into
1103
+ * session-state.json. Session-manager reads this in `_serializeSessionEntry`
1104
+ * and forwards it back as `disabledMcpServers` on restore.
1105
+ */
1106
+ getDisabledMcpServers() {
1107
+ return [...this._disabledMcpServers].sort()
1108
+ }
1109
+
1110
+ async sendMessage(prompt, attachments, sendOptions = {}) {
463
1111
  if (this._isBusy) {
464
1112
  this.emit('error', { message: 'Already processing a message' })
1113
+ reportInputAdmission(sendOptions, {
1114
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1115
+ reason: 'busy', message: 'The provider is already processing a message.',
1116
+ })
465
1117
  return
466
1118
  }
467
1119
  if (this._destroying || !this._processReady || !this._client) {
468
1120
  this.emit('error', { message: 'Session not ready' })
1121
+ reportInputAdmission(sendOptions, {
1122
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1123
+ reason: 'not_runnable', message: 'The provider session is not ready to accept input.',
1124
+ })
1125
+ return
1126
+ }
1127
+ if (sendOptions.context && Array.isArray(attachments) && attachments.length > 0) {
1128
+ this.emit('error', {
1129
+ message: `BYOK provider does not yet materialise attachments (${attachments.length} dropped). Track follow-up: file-via-Read tool flow.`,
1130
+ })
1131
+ reportInputAdmission(sendOptions, {
1132
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1133
+ reason: 'unsupported_attachments', message: 'This provider does not support image context.',
1134
+ })
469
1135
  return
470
1136
  }
471
1137
 
1138
+ // Claim busy up front so the async MCP-prompt resolution below can't race a
1139
+ // second concurrent send (isRunning stays true across the await window).
472
1140
  this._isBusy = true
1141
+ // #8430: a new turn starts with no user Stop in flight, whatever the last one left.
1142
+ this._permissions.clearUserStopInFlight()
1143
+
1144
+ // #6823: MCP prompt-as-slash-command interception. A leading
1145
+ // `/mcp__<server>__<prompt>` that matches a connected MCP server's prompt
1146
+ // is expanded via `prompts/get` and the returned messages become the user
1147
+ // turn. On a resolution failure (bad args, dead server) we release busy and
1148
+ // surface an error WITHOUT starting a turn. Plain text and non-MCP slash
1149
+ // commands (`/clear`, etc.) pass through untouched.
1150
+ let promptText = typeof prompt === 'string' ? prompt : String(prompt ?? '')
1151
+ const mcpPromptMatch = this._matchMcpPromptCommand(promptText)
1152
+ if (mcpPromptMatch) {
1153
+ try {
1154
+ promptText = await this._resolveMcpPromptToText(mcpPromptMatch)
1155
+ if (!stillAuthorized(sendOptions.isAuthorized)) {
1156
+ this._isBusy = false
1157
+ this._permissions.clearUserStopInFlight()
1158
+ reportInputAdmission(sendOptions, {
1159
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1160
+ reason: 'connection_not_authorized', message: 'The sending connection is no longer authorized; the input was not dispatched.',
1161
+ })
1162
+ return
1163
+ }
1164
+ } catch (err) {
1165
+ this._isBusy = false
1166
+ this._permissions.clearUserStopInFlight() // #8430: this turn ends here, off the _finishTurn path
1167
+ this.emit('error', {
1168
+ message: `MCP prompt /${mcpPromptMatch.prefixedName} failed: ${err?.message || String(err)}`,
1169
+ })
1170
+ reportInputAdmission(sendOptions, {
1171
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1172
+ reason: 'prompt_resolution_failed', message: 'The provider prompt could not be resolved before dispatch.',
1173
+ })
1174
+ return
1175
+ }
1176
+ // #6845: honesty. The raw `/mcp__server__prompt` the user typed is NOT
1177
+ // what the model receives — the SERVER-CONTROLLED expansion above is,
1178
+ // injected as the user turn. Surface it in the transcript as a labeled
1179
+ // system marker so the user can audit the actual injected content (a
1180
+ // trusted-but-verbose, or later-compromised, MCP server could inject
1181
+ // surprising text). Emitted before stream_start so it renders between the
1182
+ // user's raw command echo and the assistant response. Never lets a marker
1183
+ // failure break the turn — the message send is what matters.
1184
+ this._emitMcpPromptExpansionMarker(mcpPromptMatch, promptText)
1185
+ }
1186
+
473
1187
  this._messageCounter += 1
474
1188
  const messageId = `${this._messageIdPrefix}-${this._messageCounter}`
475
1189
  this._currentMessageId = messageId
@@ -488,8 +1202,10 @@ export class ClaudeByokSession extends BaseSession {
488
1202
  // Build the user message. On the very first turn, prepend any skills
489
1203
  // text from BaseSession._buildPrependPrompt(). Subsequent turns are
490
1204
  // plain prompt text — skills that targeted `system` ride on the
491
- // rebuilt systemPrompt instead.
492
- let userText = typeof prompt === 'string' ? prompt : String(prompt ?? '')
1205
+ // rebuilt systemPrompt instead. #6823: `promptText` is the MCP-prompt-
1206
+ // expanded text when the input was a `/mcp__server__prompt` command, else
1207
+ // the raw prompt.
1208
+ let userText = promptText
493
1209
  if (this._history.length === 0) {
494
1210
  const prepend = typeof this._buildPrependPrompt === 'function'
495
1211
  ? this._buildPrependPrompt()
@@ -511,6 +1227,7 @@ export class ClaudeByokSession extends BaseSession {
511
1227
  ? this._buildSystemPrompt()
512
1228
  : ''
513
1229
 
1230
+ this._toolResultsEmitted.clear()
514
1231
  this.emit('stream_start', { messageId })
515
1232
 
516
1233
  // Agent loop. Each iteration:
@@ -534,6 +1251,14 @@ export class ClaudeByokSession extends BaseSession {
534
1251
  // dashboard shows "n/a" rather than a misleading $0.00 — distinct from a
535
1252
  // genuine zero-cost turn.
536
1253
  let turnCostKnown = false
1254
+ // #6769: the FINAL round's individual usage — a true prompt-size SNAPSHOT
1255
+ // (that round's input + cache_read + cache_creation is exactly the
1256
+ // conversation as last sent to the API), unlike the summed `turnUsage`
1257
+ // above which re-counts the history once per round and must never feed
1258
+ // the context meter. Updated after every finalMessage() so whatever round
1259
+ // ends the turn (normal break, abort break, summary round) leaves its
1260
+ // snapshot here.
1261
+ let lastRoundUsage = null
537
1262
  const pricingModel = this.model || this._defaultModel
538
1263
  const pricing = this._getPricing(pricingModel)
539
1264
  if (!pricing && !this._pricingWarnedModels.has(pricingModel)) {
@@ -542,6 +1267,13 @@ export class ClaudeByokSession extends BaseSession {
542
1267
  log.warn(`no pricing entry for model=${pricingModel}; result.cost will be 0 — update CLAUDE_PRICING_USD_PER_MTOK in models.js`)
543
1268
  }
544
1269
  let lastStopReason = null
1270
+ // #8461: set when the loop spends MAX_TOOL_ROUNDS; the forced summary round's
1271
+ // own `end_turn` overwrites lastStopReason, so the cap needs its own flag.
1272
+ let toolRoundCapReached = false
1273
+ // #7072: an interrupt that landed in the tool phase ends the loop below WITHOUT a
1274
+ // thrown abort, so the stream-phase catch never sees it. (A requested Stop that
1275
+ // lands in the stream phase reaches the same `result` through that catch, #8553.)
1276
+ let stoppedInToolPhase = false
545
1277
  // Snapshot the pre-turn history length so any stream-init failure (at
546
1278
  // any round) can rollback the entire turn atomically. We derive it
547
1279
  // from the current length minus the user message we just pushed at
@@ -552,9 +1284,16 @@ export class ClaudeByokSession extends BaseSession {
552
1284
  // `user` turn back-to-back, soft-breaking the alternation invariant
553
1285
  // the API may tighten on in future.
554
1286
  const historyLengthBeforeSend = Math.max(0, this._history.length - 1)
1287
+ // #8559: text streamed by the round that is still in flight (not yet committed to
1288
+ // `_history`). A requested Stop mid-stream keeps it as a truncated assistant turn.
1289
+ let streamedText = ''
1290
+ // The summary round's instruction block (appended to the last tool_result turn)
1291
+ // while that round is in flight, so a requested Stop can take it back out.
1292
+ let pendingSummary = null
555
1293
 
556
1294
  try {
557
1295
  for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
1296
+ streamedText = ''
558
1297
  let stream
559
1298
  try {
560
1299
  stream = this._client.messages.stream(
@@ -581,16 +1320,58 @@ export class ClaudeByokSession extends BaseSession {
581
1320
  if (this._history.length > historyLengthBeforeSend) {
582
1321
  this._history.length = historyLengthBeforeSend
583
1322
  }
1323
+ if (round === 0) {
1324
+ reportInputAdmission(sendOptions, {
1325
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1326
+ reason: 'stream_start_failed', message: 'The provider rejected the input before streaming began.',
1327
+ })
1328
+ }
584
1329
  throw err
585
1330
  }
586
1331
 
1332
+ if (round === 0) {
1333
+ reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
1334
+ }
1335
+
587
1336
  for await (const event of stream) {
588
1337
  const t = translateSdkEvent(event)
589
1338
  if (!t) continue
590
1339
  switch (t.kind) {
591
1340
  case 'stream_delta':
1341
+ streamedText += t.text
592
1342
  this.emit('stream_delta', { messageId, delta: t.text })
593
1343
  break
1344
+ case 'thinking_delta': {
1345
+ // #6756 — extended-thinking (reasoning) delta. The translator
1346
+ // already recognises `thinking_delta` (byok-event-translator.js);
1347
+ // previously it hit `default: break` and was dropped. Route it to
1348
+ // a distinct thinking id (opened lazily on the block's first
1349
+ // delta) so it streams into a `type: 'thinking'` bubble.
1350
+ const idx = typeof t.index === 'number' ? t.index : 0
1351
+ let thinkingId = this._streamingIndexToThinkingId.get(idx)
1352
+ if (!thinkingId) {
1353
+ // #6630: unique per thinking STREAM in the turn, not per block
1354
+ // index. The index restarts at 0 every tool round while the turn's
1355
+ // `messageId` does not, so `<turn>-thinking-<idx>` named a round-2
1356
+ // thought the same as the round-1 one: live, the client's accumulator
1357
+ // concatenated the two; the history (keyed by id) kept one. A counter
1358
+ // that runs for the whole turn keeps every stream's id its own, and
1359
+ // still ends in `-thinking-<n>` for the legacy classifier.
1360
+ if (this._thinkingSeqTurn !== messageId) {
1361
+ this._thinkingSeqTurn = messageId
1362
+ this._thinkingSeq = 0
1363
+ }
1364
+ thinkingId = `${messageId}-thinking-${this._thinkingSeq++}`
1365
+ this._streamingIndexToThinkingId.set(idx, thinkingId)
1366
+ // #6391 footer-stat: mark the block's start for the
1367
+ // content_block_stop elapsed-time computation. #6943:
1368
+ // performance.now() (monotonic), not Date.now().
1369
+ this._thinkingStartMs.set(thinkingId, performance.now())
1370
+ this.emit('stream_start', { messageId: thinkingId, thinking: true })
1371
+ }
1372
+ this.emit('stream_delta', { messageId: thinkingId, delta: t.text, thinking: true })
1373
+ break
1374
+ }
594
1375
  case 'tool_start': {
595
1376
  // Surface the tool_use opening to the dashboard so it can
596
1377
  // render a tool-call bubble. Matches sdk-session.js /
@@ -626,55 +1407,46 @@ export class ClaudeByokSession extends BaseSession {
626
1407
  tool: t.toolName,
627
1408
  input: null,
628
1409
  })
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
1410
  break
636
1411
  }
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
- })
1412
+ case 'tool_input_delta':
1413
+ // #8137: the SDK's raw `input_json_delta` chunks are
1414
+ // deliberately NOT forwarded — a secret can straddle chunk
1415
+ // boundaries (e.g. "export TOKEN=sk-" in one delta,
1416
+ // "ant-api03-…" in the next), and mid-stream partial JSON
1417
+ // generally isn't valid JSON, so it can't be parsed to run
1418
+ // `sanitizeToolInput`'s structured key/value passes over it
1419
+ // either. Matches the #8135 fix already applied to
1420
+ // cli-session.js / sdk-session.js: the sanitized FULL input
1421
+ // is instead delivered once, as a single `tool_input_delta`,
1422
+ // right after `stream.finalMessage()` resolves below — see
1423
+ // the loop over `toolBlocks` a few dozen lines down. Was
1424
+ // previously forwarded raw here (pre-#8137).
668
1425
  break
669
- }
670
1426
  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
1427
  if (typeof t.index === 'number') {
677
- this._streamingIndexToToolUseId.delete(t.index)
1428
+ // #6756 — close the thinking stream for this block so the
1429
+ // client finalises its "Thinking… → Thought" label.
1430
+ const thinkingId = this._streamingIndexToThinkingId.get(t.index)
1431
+ if (thinkingId) {
1432
+ this._streamingIndexToThinkingId.delete(t.index)
1433
+ // #6391 footer-stat: elapsed monotonic time from the block's
1434
+ // open to now → the client's `thought for Xs` footer. Omit
1435
+ // when the start wasn't tracked so we never send a bogus 0.
1436
+ // No token count: Anthropic's usage folds thinking tokens
1437
+ // into output_tokens with no per-block breakdown (see
1438
+ // follow-up). #6943: startMs is a performance.now() sample
1439
+ // (monotonic, immune to wall-clock jumps), so elapsed can
1440
+ // never legitimately be negative — Math.max(0, …) is a
1441
+ // defensive floor only, not a correctness requirement.
1442
+ const startMs = this._thinkingStartMs.get(thinkingId)
1443
+ this._thinkingStartMs.delete(thinkingId)
1444
+ const streamEndMsg = { messageId: thinkingId, thinking: true }
1445
+ if (typeof startMs === 'number') {
1446
+ streamEndMsg.thinkingDurationMs = Math.max(0, Math.round(performance.now() - startMs))
1447
+ }
1448
+ this.emit('stream_end', streamEndMsg)
1449
+ }
678
1450
  }
679
1451
  break
680
1452
  case 'message_delta':
@@ -696,13 +1468,17 @@ export class ClaudeByokSession extends BaseSession {
696
1468
  // #4080: defensive cleanup. content_block_stop should have
697
1469
  // drained every entry above, but if the stream ended on an
698
1470
  // 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()
1471
+ // block, a thinking entry would leak across rounds and a later
1472
+ // delta for index N could route to a STALE thinking id from the
1473
+ // previous round. Clear here so each round starts with empty
1474
+ // per-stream maps.
1475
+ this._streamingIndexToThinkingId.clear()
1476
+ this._thinkingStartMs.clear()
704
1477
  lastStopReason = final.stop_reason
705
1478
  const roundUsage = final.usage || {}
1479
+ // #6769: keep the raw per-round usage — the LAST one standing at emit
1480
+ // time is the turn's occupancy snapshot.
1481
+ lastRoundUsage = roundUsage
706
1482
  turnUsage.input_tokens += Number(roundUsage.input_tokens) || 0
707
1483
  turnUsage.output_tokens += Number(roundUsage.output_tokens) || 0
708
1484
  turnUsage.cache_read_input_tokens += Number(roundUsage.cache_read_input_tokens) || 0
@@ -717,6 +1493,57 @@ export class ClaudeByokSession extends BaseSession {
717
1493
  // Append the assistant turn — full content array preserves
718
1494
  // tool_use blocks for the next round of conversation.
719
1495
  this._history.push({ role: 'assistant', content: final.content })
1496
+ streamedText = ''
1497
+
1498
+ // Computed once — reused below both for the finalized
1499
+ // tool_input_delta emission (#8137) and, if the round proceeds
1500
+ // past the stop_reason check, for tool execution.
1501
+ const toolBlocks = (final.content || []).filter((b) => b?.type === 'tool_use')
1502
+
1503
+ // #8137: deliver the SANITIZED full input for every tool_use
1504
+ // block as a single `tool_input_delta`, now that
1505
+ // `stream.finalMessage()` has resolved and the complete, parsed
1506
+ // input is known. This REPLACES the raw per-chunk
1507
+ // `input_json_delta` forwarding removed from the
1508
+ // `tool_input_delta` case above — a secret can straddle chunk
1509
+ // boundaries and mid-stream partial JSON can't be sanitized, so
1510
+ // the safe delivery point is "sanitize the complete parsed
1511
+ // value, then send it once" (mirrors the #8135 fix already
1512
+ // applied to cli-session.js's `_captureFinalizedToolInput` /
1513
+ // sdk-session.js's `_handleToolUseBlock`). Runs through
1514
+ // `_recordToolInput` (base-session.js), the same #6029
1515
+ // `sanitizeToolInput` floor already applied on the
1516
+ // permission_request path — BYOK never populates
1517
+ // `_inFlightToolStarts`, so the tracking half of
1518
+ // `_recordToolInput` is a no-op here, but the sanitize call
1519
+ // always runs. Emitted before the `lastStopReason` check below
1520
+ // so the client sees the tool's input even in the
1521
+ // (should-never-happen) case where the API pairs tool_use
1522
+ // content with a non-tool_use stop_reason.
1523
+ for (const block of toolBlocks) {
1524
+ const toolUseId = block?.id
1525
+ if (!toolUseId) continue
1526
+ if (this._pendingPermissionToolUseIds.has(toolUseId)) {
1527
+ // Defensive — mirrors the pre-#8137 per-chunk suppression
1528
+ // (see the constructor comment on
1529
+ // `_pendingPermissionToolUseIds`). Today permission gating
1530
+ // for this toolUseId can't start until AFTER this point in
1531
+ // the same round (`_processToolBlocks` runs later, below),
1532
+ // so this branch is unreachable in production; kept in case
1533
+ // a future refactor requests permission before a round's
1534
+ // tool inputs are surfaced.
1535
+ continue
1536
+ }
1537
+ const sanitizedInput = this._recordToolInput(toolUseId, block.input ?? null)
1538
+ // `null`/`undefined` means "known to have no input" — don't
1539
+ // ship a literal "null" chunk for it (mirrors sdk-session.js).
1540
+ if (sanitizedInput === null || sanitizedInput === undefined) continue
1541
+ this.emit('tool_input_delta', {
1542
+ messageId,
1543
+ toolUseId,
1544
+ partialJson: JSON.stringify(sanitizedInput),
1545
+ })
1546
+ }
720
1547
 
721
1548
  if (lastStopReason !== 'tool_use') {
722
1549
  // Done — model wants no more tools. Break out and emit result.
@@ -755,7 +1582,6 @@ export class ClaudeByokSession extends BaseSession {
755
1582
  // 'Interrupted' tool_result (same #4061 invariant). If it trips
756
1583
  // mid-execution, the shared AbortSignal propagates to
757
1584
  // executeBuiltinTool and any in-flight tool aborts cleanly.
758
- const toolBlocks = (final.content || []).filter((b) => b?.type === 'tool_use')
759
1585
  const toolResults = await this._processToolBlocks({ toolBlocks, messageId })
760
1586
  if (toolResults.length === 0) {
761
1587
  // stop_reason was tool_use but no tool_use blocks — defensive
@@ -765,7 +1591,17 @@ export class ClaudeByokSession extends BaseSession {
765
1591
  }
766
1592
  this._history.push({ role: 'user', content: toolResults })
767
1593
 
768
- if (this._abortController?.signal?.aborted) break
1594
+ if (this._abortController?.signal?.aborted) {
1595
+ // #7072: the tool results above are committed to history (the #4061
1596
+ // invariant) and the turn's spend is real, so this still ends in a
1597
+ // `result` -- but one that says the turn was STOPPED, not a success. The
1598
+ // stream-phase abort throws into the catch below, which ends a REQUESTED
1599
+ // Stop in the same result (#8553); this path never throws. byok emits no
1600
+ // `stopped` of its own, so the result is the only terminal event an
1601
+ // orchestration TurnDriver hears (BaseSession.emit adds the quiet one).
1602
+ stoppedInToolPhase = true
1603
+ break
1604
+ }
769
1605
 
770
1606
  if (round === MAX_TOOL_ROUNDS - 1) {
771
1607
  // #4063: instead of bailing silently, run ONE more text-only
@@ -776,6 +1612,7 @@ export class ClaudeByokSession extends BaseSession {
776
1612
  // content block on the existing tool_result user turn rather
777
1613
  // than pushing a second user turn back-to-back.
778
1614
  log.warn(`hit MAX_TOOL_ROUNDS=${MAX_TOOL_ROUNDS} cap; running summary round`)
1615
+ toolRoundCapReached = true
779
1616
 
780
1617
  // Emit a non-fatal error so the dashboard can render a warning
781
1618
  // banner. The session stays alive — the user can keep talking;
@@ -804,6 +1641,8 @@ export class ClaudeByokSession extends BaseSession {
804
1641
  break
805
1642
  }
806
1643
 
1644
+ pendingSummary = { turn: lastTurn, block: summaryInstruction }
1645
+ streamedText = ''
807
1646
  let summaryStream
808
1647
  try {
809
1648
  summaryStream = this._client.messages.stream(
@@ -841,6 +1680,7 @@ export class ClaudeByokSession extends BaseSession {
841
1680
  if (!t) continue
842
1681
  switch (t.kind) {
843
1682
  case 'stream_delta':
1683
+ streamedText += t.text
844
1684
  this.emit('stream_delta', { messageId, delta: t.text })
845
1685
  break
846
1686
  case 'message_delta':
@@ -854,6 +1694,9 @@ export class ClaudeByokSession extends BaseSession {
854
1694
  const summaryFinal = await summaryStream.finalMessage()
855
1695
  lastStopReason = summaryFinal.stop_reason
856
1696
  const sUsage = summaryFinal.usage || {}
1697
+ // #6769: the summary round is the turn's final API round — its
1698
+ // individual usage supersedes the previous round's snapshot.
1699
+ lastRoundUsage = sUsage
857
1700
  turnUsage.input_tokens += Number(sUsage.input_tokens) || 0
858
1701
  turnUsage.output_tokens += Number(sUsage.output_tokens) || 0
859
1702
  turnUsage.cache_read_input_tokens += Number(sUsage.cache_read_input_tokens) || 0
@@ -864,6 +1707,8 @@ export class ClaudeByokSession extends BaseSession {
864
1707
  if (c !== null) { turnCost += c; turnCostKnown = true }
865
1708
  }
866
1709
  this._history.push({ role: 'assistant', content: summaryFinal.content })
1710
+ streamedText = ''
1711
+ pendingSummary = null
867
1712
  break
868
1713
  }
869
1714
  }
@@ -883,16 +1728,25 @@ export class ClaudeByokSession extends BaseSession {
883
1728
  turnCost += this._subagentCostThisTurn
884
1729
  if (this._subagentCostThisTurn > 0) turnCostKnown = true
885
1730
 
886
- this.emit('stream_end', { messageId })
887
- this.emit('result', {
888
- sessionId: null,
1731
+ // #6769: occupancy snapshot from the FINAL round's individual usage.
1732
+ // input + cache_read + cache_creation of that one API call = the
1733
+ // conversation as last sent (the true prompt size). Deliberately NOT
1734
+ // the summed turnUsage (over-reads ≈N× on an N-round turn) and
1735
+ // deliberately excludes subagent usage (a child Task runs in its own
1736
+ // window). Omitted when the turn produced no round usage — clients
1737
+ // keep their previous snapshot.
1738
+ const finalRoundOccupancy = ClaudeByokSession._buildFinalRoundOccupancy(lastRoundUsage)
1739
+
1740
+ this._emitTurnResult({
889
1741
  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,
1742
+ lastStopReason,
1743
+ toolRoundCapReached,
1744
+ interrupted: stoppedInToolPhase,
1745
+ turnStartedAt,
1746
+ turnUsage,
1747
+ turnCost,
1748
+ turnCostKnown,
1749
+ finalRoundOccupancy,
896
1750
  })
897
1751
  } catch (err) {
898
1752
  // #4118: extend the synchronous stream-init rollback (#4109) to
@@ -913,7 +1767,17 @@ export class ClaudeByokSession extends BaseSession {
913
1767
  // Truncating to historyLengthBeforeSend is idempotent: if the
914
1768
  // inner stream-init catch already truncated (round-0 path), the
915
1769
  // length is already at or below the snapshot and this is a no-op.
916
- if (this._history.length > historyLengthBeforeSend) {
1770
+ //
1771
+ // #8559: the exception is a Stop somebody requested while the model was
1772
+ // STREAMING. The tool-phase Stop above keeps the prompt and every completed
1773
+ // round, so this one does too: the user asked for the turn to END, not to be
1774
+ // erased, and the next prompt ("what did I just ask?") needs it. Every other
1775
+ // abort (a destroy, a parent's cascade) and every provider error keeps the
1776
+ // rollback: nobody asked for those turns to count.
1777
+ const requestedStop = this._isRequestedStop(err)
1778
+ if (requestedStop) {
1779
+ this._commitStoppedStream({ streamedText, historyLengthBeforeSend, pendingSummary, messageId })
1780
+ } else if (this._history.length > historyLengthBeforeSend) {
917
1781
  this._history.length = historyLengthBeforeSend
918
1782
  }
919
1783
  // #5020: fold any subagent (Task tool) usage + cost into the
@@ -929,22 +1793,49 @@ export class ClaudeByokSession extends BaseSession {
929
1793
  turnUsage.cache_creation_input_tokens += this._subagentUsageThisTurn.cache_creation_input_tokens
930
1794
  turnCost += this._subagentCostThisTurn
931
1795
  if (this._subagentCostThisTurn > 0) turnCostKnown = true
1796
+ // #8553: a Stop somebody requested that lands while the model is STREAMING
1797
+ // ends the turn exactly as the tool-phase one does (#7072): one `result`
1798
+ // that says it was stopped, then the quiet `stopped` BaseSession.emit adds
1799
+ // for it, and no `error`. The rollback and the usage fold above already ran
1800
+ // and are the same either way.
1801
+ if (requestedStop) {
1802
+ this._emitTurnResult({
1803
+ messageId,
1804
+ lastStopReason,
1805
+ toolRoundCapReached,
1806
+ interrupted: true,
1807
+ turnStartedAt,
1808
+ turnUsage,
1809
+ turnCost,
1810
+ turnCostKnown,
1811
+ finalRoundOccupancy: ClaudeByokSession._buildFinalRoundOccupancy(lastRoundUsage),
1812
+ })
1813
+ return
1814
+ }
932
1815
  this.emit('stream_end', { messageId })
933
1816
  this._emitTurnError(messageId, err, 'STREAM_ERROR', {
934
1817
  usage: turnUsage,
935
1818
  // #5630: null when no priced round committed before the error so the
936
1819
  // partial-cost line shows "n/a" rather than $0.00.
937
1820
  cost: turnCostKnown ? turnCost : null,
1821
+ // #6692: partial-spend turns get the same single-model split as the
1822
+ // success path so per-model accounting survives errored turns.
1823
+ modelUsage: synthesizeModelUsage(
1824
+ this.model || this._defaultModel,
1825
+ turnUsage,
1826
+ turnCostKnown ? turnCost : null,
1827
+ ),
938
1828
  })
939
1829
  } finally {
940
1830
  // #4080: per-turn isolation guarantee. The per-round clear after
941
1831
  // 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()
1832
+ // finalMessage() throw skips it and would leak stale per-index
1833
+ // entries into the next turn (mis-routing the next stream's
1834
+ // thinking deltas). Clearing here drains them on every exit path
1835
+ // — success, error, abort, hard timeout. Safe to call when
1836
+ // already empty.
1837
+ this._streamingIndexToThinkingId.clear()
1838
+ this._thinkingStartMs.clear()
948
1839
  this._finishTurn()
949
1840
  }
950
1841
  }
@@ -982,19 +1873,11 @@ export class ClaudeByokSession extends BaseSession {
982
1873
  // inter-phase guard fires when startIndex === 0, but only the
983
1874
  // blocks that *would* have executed in phase 2 need filling).
984
1875
  if (toolResults[j]) continue
985
- const remaining = toolBlocks[j]
986
- this.emit('tool_result', {
1876
+ toolResults[j] = this._interruptedToolResult({
987
1877
  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,
1878
+ toolUseId: toolBlocks[j].id,
995
1879
  content: interrupted,
996
- is_error: true,
997
- }
1880
+ })
998
1881
  }
999
1882
  }
1000
1883
 
@@ -1090,6 +1973,8 @@ export class ClaudeByokSession extends BaseSession {
1090
1973
  input,
1091
1974
  signal,
1092
1975
  this.permissionMode,
1976
+ undefined,
1977
+ toolUseId,
1093
1978
  )
1094
1979
  } catch (err) {
1095
1980
  // permission_request was rejected (timeout, abort, etc.). Surface
@@ -1132,7 +2017,7 @@ export class ClaudeByokSession extends BaseSession {
1132
2017
 
1133
2018
  if (resolvedDecision.behavior !== 'allow') {
1134
2019
  const msg = resolvedDecision.message || 'Permission denied by user.'
1135
- this.emit('tool_result', {
2020
+ this._emitToolResult({
1136
2021
  messageId,
1137
2022
  toolUseId,
1138
2023
  result: msg,
@@ -1179,7 +2064,7 @@ export class ClaudeByokSession extends BaseSession {
1179
2064
  }
1180
2065
  const { content, isError } = dispatchResult
1181
2066
 
1182
- this.emit('tool_result', {
2067
+ this._emitToolResult({
1183
2068
  messageId,
1184
2069
  toolUseId,
1185
2070
  result: content,
@@ -1324,10 +2209,12 @@ export class ClaudeByokSession extends BaseSession {
1324
2209
  // `description`, `startedAt`). The toolUseId matches the parent
1325
2210
  // turn's tool_use block id so the dashboard correlates the spawn
1326
2211
  // with the open tool_call bubble.
2212
+ // #7340: byok's Task tool AWAITS its child in-process (the tool result is
2213
+ // the child's answer), so a byok subagent can never outlive its turn —
2214
+ // `background: false` is a statement of fact here, not a default, and it
2215
+ // keeps byok agents eligible for the turn-end orphan sweep.
1327
2216
  const startedAt = Date.now()
1328
- const agentInfo = { toolUseId, description, startedAt }
1329
- this._activeAgents.set(toolUseId, agentInfo)
1330
- this.emit('agent_spawned', agentInfo)
2217
+ this._trackAgent({ toolUseId, description, background: false, startedAt })
1331
2218
 
1332
2219
  // Build a child session. Reuse this session's already-resolved
1333
2220
  // client so the API key resolution + Anthropic constructor only
@@ -1366,7 +2253,14 @@ export class ClaudeByokSession extends BaseSession {
1366
2253
  cwd: this.cwd,
1367
2254
  model: this.model || this._defaultModel,
1368
2255
  mcpConfigPath: null,
2256
+ projectInstructions: this.projectInstructions,
1369
2257
  })
2258
+ if (this.providerInstructionProjection?.status === 'delivered') {
2259
+ child._installProjectInstructionProjection({
2260
+ ...this.providerInstructionProjection,
2261
+ text: this.projectInstructions,
2262
+ })
2263
+ }
1370
2264
  // Skip start()'s credential resolution — share the parent's client
1371
2265
  // so the child uses the same API key path. Also avoids a duplicate
1372
2266
  // credentials.json read which could rate-limit on disk for parallel
@@ -1545,7 +2439,7 @@ export class ClaudeByokSession extends BaseSession {
1545
2439
  // already iterates _subagentSessions, but this listener also
1546
2440
  // catches the micro-race when the signal aborts between the
1547
2441
  // top-of-function check and child.sendMessage's first await.
1548
- const onAbort = () => { try { child.interrupt() } catch { /* noop */ } }
2442
+ const onAbort = () => { try { child.interrupt({ cascaded: true }) } catch { /* noop */ } }
1549
2443
  if (signal) {
1550
2444
  if (signal.aborted) onAbort()
1551
2445
  else signal.addEventListener('abort', onAbort, { once: true })
@@ -1644,10 +2538,19 @@ export class ClaudeByokSession extends BaseSession {
1644
2538
  * @param {object} payload
1645
2539
  */
1646
2540
  _emitAgentEvent(parentToolUseId, type, payload) {
2541
+ let wirePayload = payload ?? {}
2542
+ // #8397: `recordDescription` is an in-process field of the child's
2543
+ // `permission_request` (read by the session that owns the prompt to record
2544
+ // its outcome), not part of the wire shape. Every child relay passes through
2545
+ // here, so it is dropped here, once.
2546
+ if (type === 'permission_request' && wirePayload && typeof wirePayload === 'object' && 'recordDescription' in wirePayload) {
2547
+ const { recordDescription: _internal, ...rest } = wirePayload
2548
+ wirePayload = rest
2549
+ }
1647
2550
  this.emit('agent_event', {
1648
2551
  parentToolUseId,
1649
2552
  type,
1650
- payload: payload ?? {},
2553
+ payload: wirePayload,
1651
2554
  })
1652
2555
  }
1653
2556
 
@@ -1724,13 +2627,167 @@ export class ClaudeByokSession extends BaseSession {
1724
2627
  }
1725
2628
  }
1726
2629
 
2630
+ // -------------------------------------------------------------------------
2631
+ // #6823: MCP prompts (as slash commands) + resources (in the @-picker).
2632
+ // -------------------------------------------------------------------------
2633
+
2634
+ /**
2635
+ * Slash-command entries for every connected MCP server's prompts, namespaced
2636
+ * `mcp__<server>__<prompt>`. Merged into the session's slash-command surface
2637
+ * by the `list_slash_commands` handler + the connect-time auth_bootstrap
2638
+ * burst, so they render in SlashCommandPicker beside built-ins and markdown
2639
+ * skills. `source: 'mcp'` lets the picker badge/group them.
2640
+ */
2641
+ getMcpPromptCommands() {
2642
+ if (!this._mcpFleet) return []
2643
+ return this._mcpFleet.prompts.map((p) => ({
2644
+ name: p.name,
2645
+ description: typeof p.description === 'string' ? p.description : '',
2646
+ source: 'mcp',
2647
+ }))
2648
+ }
2649
+
2650
+ /**
2651
+ * Read-only listing of every connected MCP server's resources for the
2652
+ * dashboard `@`-mention picker. Each entry carries the owning `server` so a
2653
+ * later read (`readMcpResource`) can route back by (server, uri).
2654
+ */
2655
+ getMcpResources() {
2656
+ if (!this._mcpFleet) return []
2657
+ return this._mcpFleet.resources
2658
+ .map((r) => ({
2659
+ uri: typeof r.uri === 'string' ? r.uri : '',
2660
+ name: typeof r.name === 'string' && r.name ? r.name : (typeof r.uri === 'string' ? r.uri : ''),
2661
+ description: typeof r.description === 'string' ? r.description : undefined,
2662
+ mimeType: typeof r.mimeType === 'string' ? r.mimeType : undefined,
2663
+ server: r._mcpServer,
2664
+ }))
2665
+ .filter((r) => r.uri)
2666
+ }
2667
+
2668
+ /**
2669
+ * Read one MCP resource's contents (`resources/read`) routed by (server, uri).
2670
+ * Passthrough to the fleet; throws when no fleet exists or the read fails.
2671
+ */
2672
+ async readMcpResource(serverName, uri) {
2673
+ if (!this._mcpFleet) throw new Error('No MCP servers configured for this session')
2674
+ return this._mcpFleet.readResource(serverName, uri, this._mcpToolCallTimeoutMs ?? undefined)
2675
+ }
2676
+
2677
+ /**
2678
+ * Parse a user input as an MCP prompt slash command. Returns a match
2679
+ * descriptor when the input is a leading `/mcp__<server>__<prompt>` that a
2680
+ * connected server actually advertises, else null (so plain text and non-MCP
2681
+ * slash commands like `/clear` pass through unchanged).
2682
+ */
2683
+ _matchMcpPromptCommand(text) {
2684
+ if (!this._mcpFleet || typeof text !== 'string') return null
2685
+ if (!text.startsWith('/')) return null
2686
+ const body = text.slice(1)
2687
+ const wsIdx = body.search(/\s/)
2688
+ const name = wsIdx === -1 ? body : body.slice(0, wsIdx)
2689
+ const rest = wsIdx === -1 ? '' : body.slice(wsIdx + 1).trim()
2690
+ // Must parse as an mcp__server__name AND match a live prompt — otherwise a
2691
+ // stray `/mcp__whatever` typed by the user stays literal input.
2692
+ if (!parseMcpToolName(name)) return null
2693
+ const promptDef = this._mcpFleet.prompts.find((p) => p.name === name)
2694
+ if (!promptDef) return null
2695
+ return { prefixedName: name, rest, promptDef }
2696
+ }
2697
+
2698
+ /**
2699
+ * Resolve an MCP prompt command to the text injected as the user turn. Calls
2700
+ * `prompts/get` (with best-effort argument mapping) and flattens the returned
2701
+ * messages into text. No-argument prompts are first-class; when the prompt
2702
+ * declares arguments and the user supplied trailing text, that raw text maps
2703
+ * to the FIRST declared argument (a documented single-arg convenience — see
2704
+ * PR #6823). Throws (surfaced to the user) when the server errors or the
2705
+ * prompt yields no injectable text.
2706
+ */
2707
+ async _resolveMcpPromptToText(match) {
2708
+ const declared = Array.isArray(match.promptDef?.arguments) ? match.promptDef.arguments : []
2709
+ let args
2710
+ // #6844 review: require a NON-EMPTY declared argument name — a server
2711
+ // advertising `arguments: [{ name: '' }]` (or whitespace) must not produce
2712
+ // a bogus `{ "": text }` argument map; treat it as no declared args and
2713
+ // call prompts/get without arguments.
2714
+ const firstArgName = typeof declared[0]?.name === 'string' && declared[0].name.trim()
2715
+ ? declared[0].name
2716
+ : null
2717
+ if (firstArgName && match.rest) {
2718
+ args = { [firstArgName]: match.rest }
2719
+ }
2720
+ const result = await this._mcpFleet.getPrompt(
2721
+ match.prefixedName,
2722
+ args,
2723
+ this._mcpToolCallTimeoutMs ?? undefined,
2724
+ )
2725
+ const text = this._extractPromptMessagesText(result)
2726
+ if (!text) throw new Error('prompt returned no injectable text content')
2727
+ return text
2728
+ }
2729
+
2730
+ /**
2731
+ * #6845: emit the honesty marker for an expanded MCP prompt. The expansion is
2732
+ * SERVER-CONTROLLED (authored by the MCP server, not typed by the user) and
2733
+ * lands in the user role, so the marker is explicitly provenance-labeled and
2734
+ * carries the (bounded) injected text for audit. Structured on a `system`
2735
+ * message with `subtype: 'mcp_prompt_expansion'` + a `mcpPromptExpansion`
2736
+ * field — the same optional-field-on-an-existing-marker path #6768's
2737
+ * compact_boundary uses, so no new wire type is introduced. `content` carries
2738
+ * the same labeled+bounded text so generic renderers (mobile system bubble,
2739
+ * the System tab) stay honest even without the dedicated marker component.
2740
+ * A marker failure is logged and swallowed: surfacing the expansion must
2741
+ * never break delivery of the actual user turn.
2742
+ */
2743
+ _emitMcpPromptExpansionMarker(match, expandedText) {
2744
+ try {
2745
+ const parsed = parseMcpToolName(match?.prefixedName) || {}
2746
+ const server = typeof parsed.serverName === 'string' ? parsed.serverName : ''
2747
+ const prompt = typeof parsed.toolName === 'string' ? parsed.toolName : ''
2748
+ const { text, truncated } = boundMcpPromptExpansionText(expandedText)
2749
+ const label = `Expanded /${match?.prefixedName ?? ''} (server-controlled MCP prompt)`
2750
+ this.emit('message', {
2751
+ type: 'system',
2752
+ subtype: 'mcp_prompt_expansion',
2753
+ content: `${label} →\n${text}`,
2754
+ mcpPromptExpansion: { server, prompt, text, truncated },
2755
+ timestamp: Date.now(),
2756
+ })
2757
+ } catch (err) {
2758
+ log.warn(`failed to emit MCP prompt expansion marker: ${err?.message || String(err)}`)
2759
+ }
2760
+ }
2761
+
2762
+ /**
2763
+ * Flatten an MCP `prompts/get` result's `messages[]` into a single string.
2764
+ * Handles the spec's `content` shapes: a bare string, a single
2765
+ * `{ type:'text', text }` object, or an array of content blocks. Non-text
2766
+ * blocks (image/resource) are skipped — chroxy injects prompts as a text
2767
+ * user turn.
2768
+ */
2769
+ _extractPromptMessagesText(result) {
2770
+ const messages = Array.isArray(result?.messages) ? result.messages : []
2771
+ const parts = []
2772
+ for (const m of messages) {
2773
+ const c = m?.content
2774
+ if (typeof c === 'string') { parts.push(c); continue }
2775
+ if (Array.isArray(c)) {
2776
+ for (const block of c) if (typeof block?.text === 'string') parts.push(block.text)
2777
+ continue
2778
+ }
2779
+ if (c && typeof c === 'object' && typeof c.text === 'string') parts.push(c.text)
2780
+ }
2781
+ return parts.join('\n\n').trim()
2782
+ }
2783
+
1727
2784
  /**
1728
2785
  * In-process permission response — called by ws-permissions.js when the
1729
2786
  * user taps Approve/Deny on the phone or dashboard. Forwards to
1730
2787
  * PermissionManager which resolves the pending Promise in
1731
2788
  * handlePermission() above.
1732
2789
  */
1733
- respondToPermission(requestId, decision, editedInput) {
2790
+ respondToPermission(requestId, decision, editedInput, reason, scope) {
1734
2791
  // #5056: if this requestId belongs to a Task subagent (its pending
1735
2792
  // entry lives in the CHILD's PermissionManager, not ours), forward
1736
2793
  // the decision to that child. ws-permissions only ever calls the
@@ -1741,22 +2798,30 @@ export class ClaudeByokSession extends BaseSession {
1741
2798
  // already authorized against the parent session by ws-permissions.
1742
2799
  const child = this._subagentPermissionRouting.get(requestId)
1743
2800
  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
2801
  // #6543: forward the operator's per-hunk editedInput to the child too.
1750
- return child.respondToPermission(requestId, decision, editedInput)
2802
+ // #6773: the deny `reason` forwards to the child as well.
2803
+ // #8517: so does the session-scope label.
2804
+ const resolved = child.respondToPermission(requestId, decision, editedInput, reason, scope)
2805
+ // Drop the routing entry once the child has taken the response, so a
2806
+ // duplicate/late response can't re-resolve a stale id. The child also emits
2807
+ // permission_resolved which our relay listener uses to clear the same entry
2808
+ // — deleting here too is idempotent and closes the lifetime tightly.
2809
+ // #8446: NOT before the call. A child that REFUSES an edit throws with its
2810
+ // request still pending, and the caller's follow-up deny must find the route
2811
+ // to reach it; a route dropped first sent that deny to this manager, which
2812
+ // does not hold the request, and the child waited out its timeout.
2813
+ this._subagentPermissionRouting.delete(requestId)
2814
+ return resolved
1751
2815
  }
1752
- return this._permissions.respondToPermission(requestId, decision, editedInput)
2816
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
1753
2817
  }
1754
2818
 
1755
2819
  /**
1756
2820
  * Response to an AskUserQuestion tool. Same forwarding pattern.
1757
2821
  */
1758
- respondToQuestion(text, answersMap) {
1759
- this._permissions.respondToQuestion(text, answersMap)
2822
+ respondToQuestion(text, answersMap, toolUseId) {
2823
+ // #8460: the id lets the manager refuse an answer meant for a different question.
2824
+ return this._permissions.respondToQuestion(text, answersMap, toolUseId)
1760
2825
  }
1761
2826
 
1762
2827
  /**
@@ -1770,6 +2835,168 @@ export class ClaudeByokSession extends BaseSession {
1770
2835
  }
1771
2836
  }
1772
2837
 
2838
+ /** Current session-scoped permission rules (#3072 parity with SdkSession). */
2839
+ getPermissionRules() {
2840
+ if (typeof this._permissions.getRules === 'function') {
2841
+ return this._permissions.getRules()
2842
+ }
2843
+ return []
2844
+ }
2845
+
2846
+ /**
2847
+ * #6771 — durable (project-scoped) permission rules applied to this session.
2848
+ */
2849
+ getPersistentPermissionRules() {
2850
+ if (typeof this._permissions.getPersistentRules === 'function') {
2851
+ return this._permissions.getPersistentRules()
2852
+ }
2853
+ return []
2854
+ }
2855
+
2856
+ /**
2857
+ * #6771 — re-seed this session's in-memory durable rule set (no persist).
2858
+ */
2859
+ setPersistentPermissionRules(rules) {
2860
+ if (typeof this._permissions.setPersistentRules === 'function') {
2861
+ this._permissions.setPersistentRules(rules)
2862
+ }
2863
+ }
2864
+
2865
+ /**
2866
+ * #8553: the one way a turn's terminal `result` is built and sent, for the
2867
+ * normal ending and for a requested Stop alike (tool phase #7072, stream phase
2868
+ * #8553). `interrupted` makes the outcome `stopped` and marks the result
2869
+ * terminal-but-not-successful; BaseSession.emit turns that into the quiet
2870
+ * `stopped` when the Stop was requested. Emits `stream_end` first.
2871
+ */
2872
+ _emitTurnResult({
2873
+ messageId, lastStopReason, toolRoundCapReached, interrupted,
2874
+ turnStartedAt, turnUsage, turnCost, turnCostKnown, finalRoundOccupancy,
2875
+ }) {
2876
+ this.emit('stream_end', { messageId })
2877
+ this.emit('result', {
2878
+ sessionId: null,
2879
+ messageId,
2880
+ stopReason: lastStopReason,
2881
+ // #7326: the provider-neutral form of the stop reason above, for the wire.
2882
+ // (A different key on purpose: `stopReason` is the raw Anthropic string.)
2883
+ ...turnOutcomeField(outcomeFromByokTurn({ stopReason: lastStopReason, toolRoundCapReached, interrupted })),
2884
+ // #7072: terminal but not successful (internal; not on the wire).
2885
+ ...(interrupted ? { interrupted: true } : {}),
2886
+ duration: Date.now() - turnStartedAt,
2887
+ usage: turnUsage,
2888
+ ...(finalRoundOccupancy ? { contextOccupancy: finalRoundOccupancy } : {}),
2889
+ // #5630: emit null when no round produced a known cost so the UI
2890
+ // shows "n/a" instead of a misleading $0.00.
2891
+ cost: turnCostKnown ? turnCost : null,
2892
+ // #6692: single-model split. Task-subagent usage is folded into
2893
+ // turnUsage under the parent's model, which is CORRECT today because
2894
+ // children hard-inherit the parent model (see _executeTaskTool). If a
2895
+ // per-profile model override ever lands (#5018's deferred AC), that
2896
+ // change must split this map by actual child model (#5020).
2897
+ modelUsage: synthesizeModelUsage(
2898
+ this.model || this._defaultModel,
2899
+ turnUsage,
2900
+ turnCostKnown ? turnCost : null,
2901
+ ),
2902
+ })
2903
+ }
2904
+
2905
+ /** True when `err` is the abort of an in-flight stream (see _emitTurnError). */
2906
+ _isAbortError(err) {
2907
+ return err instanceof APIUserAbortError ||
2908
+ err?.name === 'AbortError' ||
2909
+ !!this._abortController?.signal?.aborted
2910
+ }
2911
+
2912
+ /**
2913
+ * #8553: did somebody ASK for the abort `err` reports? True only for an abort
2914
+ * that came through interrupt() (the user, the scheduler, the orchestration
2915
+ * watchdog). Not a teardown (destroy() calls interrupt() too, but nobody is
2916
+ * waiting for a stopped turn), and not the abort a parent's Stop cascades to
2917
+ * its Task subagent, which the parent reports as the subagent's failure.
2918
+ */
2919
+ _isRequestedStop(err) {
2920
+ return this._isAbortError(err) &&
2921
+ this._stopRequestedThisTurn &&
2922
+ !this._destroying &&
2923
+ !this._abortCascaded
2924
+ }
2925
+
2926
+ /**
2927
+ * Emit a `tool_result` event and remember its tool_use id for the turn (#8569).
2928
+ * Every tool_result event this session sends goes through here, so "has this tool
2929
+ * been closed on the client?" has one answer.
2930
+ */
2931
+ _emitToolResult({ messageId, toolUseId, result, isError }) {
2932
+ this._toolResultsEmitted.add(toolUseId)
2933
+ this.emit('tool_result', { messageId, toolUseId, result, isError })
2934
+ }
2935
+
2936
+ /**
2937
+ * The synthesized `is_error` tool_result for a tool the user's Stop kept from
2938
+ * running to a result: emits the closing event for the client's tool row and
2939
+ * returns the content block that answers the tool_use in `_history`. The one
2940
+ * place that shape lives -- the tool-phase Stop (`_processToolBlocks`) and the
2941
+ * Stop that threw between the history pushes (`_commitStoppedStream`) both use it.
2942
+ */
2943
+ _interruptedToolResult({ messageId, toolUseId, content }) {
2944
+ this._emitToolResult({ messageId, toolUseId, result: content, isError: true })
2945
+ return { type: 'tool_result', tool_use_id: toolUseId, content, is_error: true }
2946
+ }
2947
+
2948
+ /**
2949
+ * #8559: settle `_history` after a requested Stop that ended the turn by a throw.
2950
+ *
2951
+ * Whatever the tail is, it leaves `_history` a VALID conversation (the next
2952
+ * request is never rejected for it) and keeps the prompt and the completed work:
2953
+ *
2954
+ * - `user` tail (the stop cut a stream short; the in-flight round's assistant
2955
+ * turn is only committed once its stream finishes): close it with an assistant
2956
+ * turn holding the text that did stream -- what Claude Code keeps -- so the
2957
+ * next request alternates strictly. Only text is kept: a half-streamed
2958
+ * tool_use has no result to pair with. With no text at all a placeholder
2959
+ * stands in, because an empty text block is refused.
2960
+ * - `assistant` tail with tool_use blocks (the stop threw between the round's
2961
+ * assistant push and its tool_result push): the tool_use would be unanswered,
2962
+ * which the API refuses on every later request, so answer each with a
2963
+ * synthesized is_error tool_result, as the tool-phase Stop does (#4061). The
2964
+ * rounds before it stay too; rolling back instead would drop the prompt.
2965
+ * Each also gets the `tool_result` event that closes its row on the client
2966
+ * (#8569), unless its real result already went out.
2967
+ * - `assistant` tail without tool_use: already a valid end, left alone.
2968
+ *
2969
+ * A no-op only when the turn is already rolled back (a stream-init failure).
2970
+ */
2971
+ _commitStoppedStream({ streamedText, historyLengthBeforeSend, pendingSummary, messageId }) {
2972
+ if (this._history.length <= historyLengthBeforeSend) return
2973
+ const tail = this._history[this._history.length - 1]
2974
+ if (tail?.role === 'assistant') {
2975
+ const uses = Array.isArray(tail.content) ? tail.content.filter((b) => b?.type === 'tool_use') : []
2976
+ if (uses.length > 0) {
2977
+ // #8569: the client opened a row for each of these on `tool_start`, and only
2978
+ // a `tool_result` event closes it. Emit the same interrupted result the
2979
+ // tool-phase Stop does, except for a tool whose real result already went out.
2980
+ this._history.push({
2981
+ role: 'user',
2982
+ content: uses.map((b) => (this._toolResultsEmitted.has(b.id)
2983
+ ? { type: 'tool_result', tool_use_id: b.id, content: STOPPED_BEFORE_TOOL, is_error: true }
2984
+ : this._interruptedToolResult({ messageId, toolUseId: b.id, content: STOPPED_BEFORE_TOOL }))),
2985
+ })
2986
+ }
2987
+ return
2988
+ }
2989
+ if (pendingSummary && pendingSummary.turn === tail && Array.isArray(tail.content)) {
2990
+ // The summary round never ran to completion: take its instruction back out so
2991
+ // the next turn is not told to stop using tools.
2992
+ tail.content = tail.content.filter((b) => b !== pendingSummary.block)
2993
+ }
2994
+ this._history.push({
2995
+ role: 'assistant',
2996
+ content: [{ type: 'text', text: streamedText.trim() ? streamedText : STOPPED_BEFORE_TEXT }],
2997
+ })
2998
+ }
2999
+
1773
3000
  _emitTurnError(messageId, err, fallbackCode, partials) {
1774
3001
  // #4057: SDK v0.81+ throws `APIUserAbortError` (not the generic
1775
3002
  // `AbortError`) when an in-flight messages.stream sees its signal
@@ -1789,16 +3016,12 @@ export class ClaudeByokSession extends BaseSession {
1789
3016
  // so additional fields propagate without a wire-side schema change.
1790
3017
  // Optional / undefined-safe: pre-#5020 call sites pass nothing and
1791
3018
  // 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) {
3019
+ if (this._isAbortError(err)) {
1797
3020
  this.emit('error', {
1798
3021
  messageId,
1799
3022
  message: 'Interrupted by user',
1800
3023
  code: 'ABORT',
1801
- ...(partials ? { usage: partials.usage, cost: partials.cost } : {}),
3024
+ ...(partials ? { usage: partials.usage, cost: partials.cost, modelUsage: partials.modelUsage ?? null } : {}),
1802
3025
  })
1803
3026
  return
1804
3027
  }
@@ -1808,11 +3031,14 @@ export class ClaudeByokSession extends BaseSession {
1808
3031
  messageId,
1809
3032
  message,
1810
3033
  code,
1811
- ...(partials ? { usage: partials.usage, cost: partials.cost } : {}),
3034
+ ...(partials ? { usage: partials.usage, cost: partials.cost, modelUsage: partials.modelUsage ?? null } : {}),
1812
3035
  })
1813
3036
  }
1814
3037
 
1815
3038
  _finishTurn() {
3039
+ // #8430: a user Stop belongs to the turn it was pressed on; BYOK's teardown
3040
+ // does not go through BaseSession._clearMessageState, so clear it here.
3041
+ this._permissions.clearUserStopInFlight()
1816
3042
  this._isBusy = false
1817
3043
  this._currentMessageId = null
1818
3044
  this._abortController = null
@@ -1821,10 +3047,31 @@ export class ClaudeByokSession extends BaseSession {
1821
3047
  // fired and the fold-in step above was skipped.
1822
3048
  this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
1823
3049
  this._subagentCostThisTurn = 0
3050
+ // #7072/#8461: this teardown skips BaseSession._clearMessageState, so the
3051
+ // turn-scoped Stop request (see interrupt()) is cleared here, or it would tag
3052
+ // the NEXT turn's own abort as a requested Stop.
3053
+ this._stopRequestedThisTurn = false
3054
+ this._abortCascaded = false
3055
+ this._clearIntentionalStop()
1824
3056
  }
1825
3057
 
1826
- interrupt() {
3058
+ /**
3059
+ * @param {{ cascaded?: boolean }} [opts] `cascaded`: the parent session is
3060
+ * stopping this Task subagent (its own Stop reaching it, or a cancel of this
3061
+ * one node), rather than a Stop of this session (#8553).
3062
+ */
3063
+ interrupt({ cascaded = false } = {}) {
1827
3064
  if (!this._isBusy) return
3065
+ if (cascaded) this._abortCascaded = true
3066
+ // #7072/#8461/#8553: a Stop somebody requested (the user, the scheduler, the
3067
+ // orchestration watchdog) is acknowledged by one quiet `stopped` instead of a
3068
+ // "Stopped" chip, exactly as on claude-sdk and claude-cli. Both phases end in a
3069
+ // `result` (see sendMessage): the tool-phase abort never throws, and the
3070
+ // stream-phase one is turned into the same result by the catch, so
3071
+ // BaseSession.emit drops the chip and sends the confirmation, after marking the
3072
+ // result `interrupted`.
3073
+ this.markIntentionalStop()
3074
+ this._noteTurnStopRequested()
1828
3075
  if (this._abortController) {
1829
3076
  this._abortController.abort()
1830
3077
  }
@@ -1834,7 +3081,7 @@ export class ClaudeByokSession extends BaseSession {
1834
3081
  // _executeTaskTool's awaited promise resolve and the parent's
1835
3082
  // outer agent loop can finish the user-facing result event.
1836
3083
  for (const child of this._subagentSessions.values()) {
1837
- try { child.interrupt() } catch (err) {
3084
+ try { child.interrupt({ cascaded: true }) } catch (err) {
1838
3085
  log.warn(`subagent interrupt failed: ${err?.message || err}`)
1839
3086
  }
1840
3087
  }
@@ -1877,7 +3124,9 @@ export class ClaudeByokSession extends BaseSession {
1877
3124
  // optimistically finalize the node, matching the SDK path's best-effort
1878
3125
  // stopTask contract.
1879
3126
  try {
1880
- child.interrupt()
3127
+ // A cancel of one node reaches the subagent like the parent's own Stop
3128
+ // does: the parent reports it as the subagent's failure (#8553).
3129
+ child.interrupt({ cascaded: true })
1881
3130
  } catch (err) {
1882
3131
  log.warn(`subagent cancel failed for ${activityId}: ${err?.message || err}`)
1883
3132
  return { ok: false, reason: 'stop-failed', error: err?.message || String(err) }
@@ -1895,13 +3144,14 @@ export class ClaudeByokSession extends BaseSession {
1895
3144
  * completion don't double-emit. Mirrors SdkSession's helper of the same name
1896
3145
  * (minus the task-id map, which byok doesn't have).
1897
3146
  *
3147
+ * #7340: the body is now BaseSession's `_completeAgent` — same guard, same
3148
+ * emit, ONE implementation shared with SdkSession and CliSession. Kept as a
3149
+ * named wrapper because #5274's callers and the cancel path read by this name.
3150
+ *
1898
3151
  * @param {string} toolUseId
1899
3152
  */
1900
3153
  _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 })
3154
+ this._completeAgent(toolUseId)
1905
3155
  }
1906
3156
 
1907
3157
  // #5374: no setModel override needed — BaseSession.setModel updates the
@@ -1976,7 +3226,8 @@ export class ClaudeByokSession extends BaseSession {
1976
3226
  // #4080: same-rationale teardown — both maps are bounded by the
1977
3227
  // active stream / outstanding permission count, but any external
1978
3228
  // reference (test capture, future export) would keep them alive.
1979
- this._streamingIndexToToolUseId.clear()
3229
+ this._streamingIndexToThinkingId.clear()
3230
+ this._thinkingStartMs.clear()
1980
3231
  this._pendingPermissionToolUseIds.clear()
1981
3232
  // #5056: drop any outstanding subagent permission-routing pointers so
1982
3233
  // the destroyed parent doesn't retain references to its children.