@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  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 +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  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-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -15,10 +15,11 @@
15
15
  */
16
16
 
17
17
  import Anthropic, { APIUserAbortError } from '@anthropic-ai/sdk'
18
- import { join } from 'path'
19
- import { homedir } from 'os'
18
+ import { assertAuthorized, stillAuthorized } from './connection-authority.js'
20
19
  import { performance } from 'node:perf_hooks'
21
- import { BaseSession, buildBaseSessionOpts } from './base-session.js'
20
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission, NOT_ADMITTED_ADMISSION } from './base-session.js'
21
+ import { BYOK_CUSTOMIZATION } from './provider-customization.js'
22
+ import { loadByokInstructionPolicy } from './instruction-policy.js'
22
23
  import { synthesizeModelUsage } from './usage-normalize.js'
23
24
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
24
25
  import { createLogger } from './logger.js'
@@ -37,9 +38,11 @@ import { executeBuiltinTool } from './byok-tool-executor.js'
37
38
  import {
38
39
  addMcpServerToConfig,
39
40
  defaultClaudeConfigPath,
40
- loadClaudeMcpConfig,
41
+ discoverMcpServerSpecs,
42
+ mcpWriteScopeToSource,
41
43
  planAddMcpServerToConfig,
42
44
  removeMcpServerFromConfig,
45
+ mcpSourceToWriteScope,
43
46
  toMcpServerMetadata,
44
47
  validateMcpServerNameForRemoval,
45
48
  validateNewMcpServerName,
@@ -53,6 +56,8 @@ import {
53
56
  withTrustStoreLock,
54
57
  } from './byok-mcp-trust.js'
55
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'
56
61
 
57
62
  const log = createLogger('byok-session')
58
63
 
@@ -73,6 +78,15 @@ const MAX_HISTORY_TURNS = 50
73
78
  // up an unbounded API bill.
74
79
  const MAX_TOOL_ROUNDS = 25
75
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
+
76
90
  // TTL for the per-session realpath cache used by validatePathWithinCwd
77
91
  // in the tool executor. The cwd shouldn't change mid-session, but caching
78
92
  // for 30s strikes a balance between safety (re-stat to catch a swap) and
@@ -109,9 +123,40 @@ function boundMcpPromptExpansionText(text, cap = MCP_PROMPT_EXPANSION_DISPLAY_CA
109
123
  if (s.length <= cap) return { text: s, truncated: false }
110
124
  const sliceLen = Math.max(0, cap - MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX.length)
111
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 }
112
151
  }
113
152
 
114
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'
115
160
  // #5858: Claude-family flag — single source of truth for isClaudeProvider().
116
161
  // DockerByokSession (docker-byok) extends this and correctly inherits it.
117
162
  // NOTE: non-Claude providers that ALSO extend this for the agent loop
@@ -174,6 +219,8 @@ export class ClaudeByokSession extends BaseSession {
174
219
  // PermissionManager (same machinery as claude-sdk).
175
220
  permissions: true,
176
221
  inProcessPermissions: true,
222
+ permissionFloor: true,
223
+ autoPermissionMode: true,
177
224
  modelSwitch: true,
178
225
  permissionModeSwitch: true,
179
226
  planMode: false,
@@ -184,6 +231,12 @@ export class ClaudeByokSession extends BaseSession {
184
231
  // Thinking config supported by the SDK but not wired through the
185
232
  // chroxy UI yet — leave off until the toggle lands.
186
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
187
240
  streaming: true,
188
241
  // We rebuild the system prompt on every turn from
189
242
  // _buildSystemPrompt(), so an activate/deactivate of a skill
@@ -198,8 +251,15 @@ export class ClaudeByokSession extends BaseSession {
198
251
  }
199
252
 
200
253
  static get customEvents() {
201
- // tool_start / tool_result / tool_input_delta are surfaced per turn
202
- // 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 /
203
263
  // user_question / permission_resolved are re-emitted from
204
264
  // PermissionManager and already known to the SessionManager
205
265
  // forwarding pipeline, but list them here so the capability matrix
@@ -224,7 +284,7 @@ export class ClaudeByokSession extends BaseSession {
224
284
  // accumulator and the final summary text becomes the parent's
225
285
  // Task tool_result content; replaying it as a nested event would
226
286
  // double-render the same content.
227
- 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']
228
288
  }
229
289
 
230
290
  /**
@@ -237,7 +297,7 @@ export class ClaudeByokSession extends BaseSession {
237
297
  label: 'Claude (BYOK)',
238
298
  credentials: {
239
299
  envVars: ['ANTHROPIC_API_KEY'],
240
- 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)`,
241
301
  optional: false,
242
302
  },
243
303
  }
@@ -319,18 +379,28 @@ export class ClaudeByokSession extends BaseSession {
319
379
  * overrides (system prompt, settings) can be added as distinct named opts when
320
380
  * any of them are actually used.
321
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`.
322
385
  */
323
386
  constructor(opts = {}) {
324
387
  super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-byok' }))
325
388
  // Anthropic SDK client; lazily instantiated in start() so unit tests
326
389
  // can stub it via this._client = ... before start().
327
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
328
396
  // In-memory conversation history. Each entry is a Claude API message
329
397
  // ({ role: 'user'|'assistant', content: <string|array> }). The SDK
330
398
  // accepts either shape for user/assistant turns.
331
399
  this._history = []
332
400
  // AbortController for the active stream so interrupt() can cancel.
333
401
  this._abortController = null
402
+ // #8553: this turn's abort was driven by a parent session (see interrupt()).
403
+ this._abortCascaded = false
334
404
 
335
405
  // PermissionManager + event re-emission via the shared wiring (P2-9) so the
336
406
  // dashboard / mobile permission UI and the audit log work uniformly across
@@ -363,24 +433,20 @@ export class ClaudeByokSession extends BaseSession {
363
433
  // pair" — not "one warn per current model."
364
434
  this._pricingWarnedModels = new Set()
365
435
 
366
- // #4080: Per-stream index→toolUseId map. Populated on
367
- // `content_block_start` with `block.type === 'tool_use'` (where the
368
- // SDK emits both the block index and the tool_use id) and queried on
369
- // `tool_input_delta`, which only carries the index. Entry is deleted
370
- // on `content_block_stop` so the map stays small even on multi-tool
371
- // turns. The full map is cleared after the for-await loop in case
372
- // the stream terminated without emitting a final stop for every
373
- // block — kept inside the session (not the translator) per #4059's
374
- // boundary call: the translator stays pure, stateful tracking lives
375
- // here.
376
- this._streamingIndexToToolUseId = new Map()
377
-
378
- // #6756: per-stream index → thinking messageId, mirroring the toolUseId map
379
- // above. The translated `thinking_delta` events carry only the block index;
380
- // this maps each thinking block's index to the distinct thinking id we open
381
- // on its first delta so subsequent deltas + the content_block_stop route
382
- // correctly. Cleared alongside `_streamingIndexToToolUseId`.
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.)
383
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
384
450
 
385
451
  // #6391 (chat-redesign footer-stat): thinking messageId → performance.now()
386
452
  // when the reasoning block opened, so its content_block_stop can stamp the
@@ -438,6 +504,10 @@ export class ClaudeByokSession extends BaseSession {
438
504
  // leak into a future turn.
439
505
  this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
440
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()
441
511
 
442
512
  // #5018: per-session built-in tool allowlist. Set by _executeTaskTool
443
513
  // ONLY on child sessions spawned with a `subagent_type` profile that
@@ -461,7 +531,21 @@ export class ClaudeByokSession extends BaseSession {
461
531
  // writes back to the SAME file this session read from (a test override or
462
532
  // $CHROXY_CLAUDE_CONFIG must not be bypassed on the write half).
463
533
  this._mcpConfigPath = opts.mcpConfigPath || defaultClaudeConfigPath()
464
- const mcpConfig = loadClaudeMcpConfig(opts.mcpConfigPath)
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 })
465
549
  for (const warning of mcpConfig.warnings) {
466
550
  log.warn(`BYOK MCP config: ${warning}`)
467
551
  }
@@ -535,7 +619,78 @@ export class ClaudeByokSession extends BaseSession {
535
619
  return getModelPricing(model)
536
620
  }
537
621
 
622
+ _buildStreamParams(params) {
623
+ return params
624
+ }
625
+
626
+ /**
627
+ * #7012: lazily construct + start the MCP fleet from whatever is currently in
628
+ * `_mcpServerConfigs`, exactly once. Extracted out of `start()` (which was the
629
+ * ONLY caller pre-#7012) so `addMcpServer` can reach the same construction path:
630
+ * a session that started with zero configured MCP servers never created a
631
+ * fleet, so `addMcpServer`'s old `if (this._mcpFleet)` gate skipped the
632
+ * fleet-attach step entirely — the server was persisted but stayed
633
+ * unconnected until a restart. `addMcpServer` appends the new entry to
634
+ * `_mcpServerConfigs` BEFORE calling this, so the fleet's constructor (which
635
+ * spawns one client per config) picks the new server up directly; no separate
636
+ * `fleet.addServer()` call is needed on that path.
637
+ *
638
+ * Single-flight without extra bookkeeping: `this._mcpFleet` is assigned
639
+ * SYNCHRONOUSLY, before the `await fleet.start()` below — the same
640
+ * synchronous stretch that reads `_mcpServerConfigs` and decides whether to
641
+ * call this method (see `addMcpServer`). JS never preempts mid-synchronous-
642
+ * stretch, so two concurrent `addMcpServer` calls can never both observe
643
+ * `_mcpFleet` as null: whichever runs first sets it before yielding on the
644
+ * `await`, and the other sees it already set and falls through to the
645
+ * existing-fleet `fleet.addServer()` branch instead of racing a second
646
+ * `new MCPFleet(...)`.
647
+ *
648
+ * Guards:
649
+ * - zero configured servers → no fleet (mirrors the pre-#7012 `start()`
650
+ * guard — nothing to spawn).
651
+ * - `_destroying` → no fleet (a session torn down mid-add must not spawn a
652
+ * new MCP child that `destroy()` has already finished looking for).
653
+ */
654
+ async _ensureMcpFleet() {
655
+ if (this._mcpFleet) return this._mcpFleet
656
+ if (this._destroying || this._mcpServerConfigs.length === 0) return null
657
+ // #4457: pass the session's PermissionManager so the fleet can
658
+ // emit a trust prompt for a not-yet-trusted spawn config (#7001: name +
659
+ // command + the full args + env).
660
+ // Tuples already trusted in ~/.chroxy/mcp-trust.json spawn directly
661
+ // with no prompt; denied tuples set state=DEAD without spawning.
662
+ // #4456: forward startCapMs override so operators can tune the
663
+ // session-start wall-clock cap. Passing undefined lets the fleet's
664
+ // constructor default (DEFAULT_FLEET_START_CAP_MS) win — exactly
665
+ // what we want when no override is in play.
666
+ const fleetOpts = { log, permissionManager: this._permissions }
667
+ if (this._mcpStartCapMs !== null) fleetOpts.startCapMs = this._mcpStartCapMs
668
+ // #6824: seed the fleet with the persisted parked set so a respawn skips
669
+ // starting servers the operator disabled before the restart.
670
+ fleetOpts.disabledServers = [...this._disabledMcpServers]
671
+ const fleet = new MCPFleet(this._mcpServerConfigs, fleetOpts)
672
+ this._mcpFleet = fleet
673
+ await fleet.start()
674
+ return fleet
675
+ }
676
+
538
677
  async start() {
678
+ // API-driven BYOK providers have no vendor-native project-file discovery.
679
+ // Compile before client creation so malformed/over-budget policy cannot
680
+ // reach a model. Container cwd mapping is not yet verified.
681
+ if (this._loadProjectInstructions && !this._instructionPolicyLoaded && !this.constructor.capabilities?.containerized) {
682
+ const projection = await this._instructionPolicyLoader({
683
+ cwd: this.cwd,
684
+ ...(this._machineInstructionPath !== undefined
685
+ ? { machinePath: this._machineInstructionPath }
686
+ : {}),
687
+ ...(this._machineInstructionRoot !== undefined
688
+ ? { machineRoot: this._machineInstructionRoot }
689
+ : {}),
690
+ })
691
+ this._installProjectInstructionProjection(projection)
692
+ this._instructionPolicyLoaded = true
693
+ }
539
694
  if (this._client === null) {
540
695
  // Spike (BYOK direct) confirmed the SDK's standard constructor
541
696
  // works fine; baseURL defaults to api.anthropic.com.
@@ -565,24 +720,10 @@ export class ClaudeByokSession extends BaseSession {
565
720
  // tools, identical to a server missing from config. We deliberately
566
721
  // wait for fleet.start() so this.mcpServers + tools list are stable
567
722
  // by the time we emit 'ready'.
568
- if (this._mcpServerConfigs.length > 0 && this._mcpFleet === null) {
569
- // #4457: pass the session's PermissionManager so the fleet can
570
- // emit a trust prompt for a not-yet-trusted spawn config (#7001: name +
571
- // command + the full args + env).
572
- // Tuples already trusted in ~/.chroxy/mcp-trust.json spawn directly
573
- // with no prompt; denied tuples set state=DEAD without spawning.
574
- // #4456: forward startCapMs override so operators can tune the
575
- // session-start wall-clock cap. Passing undefined lets the fleet's
576
- // constructor default (DEFAULT_FLEET_START_CAP_MS) win — exactly
577
- // what we want when no override is in play.
578
- const fleetOpts = { log, permissionManager: this._permissions }
579
- if (this._mcpStartCapMs !== null) fleetOpts.startCapMs = this._mcpStartCapMs
580
- // #6824: seed the fleet with the persisted parked set so a respawn skips
581
- // starting servers the operator disabled before the restart.
582
- fleetOpts.disabledServers = [...this._disabledMcpServers]
583
- this._mcpFleet = new MCPFleet(this._mcpServerConfigs, fleetOpts)
584
- await this._mcpFleet.start()
585
- }
723
+ // #7012: extracted into _ensureMcpFleet so addMcpServer can reach the
724
+ // SAME construction path for a session that started with zero MCP
725
+ // servers configured (previously only start() ever created a fleet).
726
+ await this._ensureMcpFleet()
586
727
 
587
728
  this._processReady = true
588
729
  this.emit('ready', { sessionId: null, model: this.model, tools: [] })
@@ -605,11 +746,14 @@ export class ClaudeByokSession extends BaseSession {
605
746
  if (this._mcpFleet) return this._mcpFleet.getServerStatuses()
606
747
  return this._mcpServerConfigs.map((cfg) => {
607
748
  const disabled = this._disabledMcpServers.has(cfg.name)
749
+ const scope = mcpSourceToWriteScope(cfg.source)
608
750
  return {
609
751
  name: cfg.name,
610
752
  status: disabled ? 'disabled' : 'configured',
611
753
  enabled: !disabled,
612
754
  canToggle: true,
755
+ // #7028: same rule as the fleet's snapshot — present only when known.
756
+ ...(scope ? { scope } : {}),
613
757
  }
614
758
  })
615
759
  }
@@ -738,9 +882,12 @@ export class ClaudeByokSession extends BaseSession {
738
882
  const store = loadTrustStore(trustPath, { log })
739
883
  if (isTrusted(store, cfg)) return { allowed: true, prompted: false }
740
884
  const isRemote = typeof cfg.url === 'string' && cfg.url.length > 0
885
+ // #7939: forward the scope this add targets (see mcpWriteScopeToSource
886
+ // above) so the pre-write trust prompt names where the server is being
887
+ // configured, same as a rediscovered spec's prompt would.
741
888
  const trustReq = isRemote
742
- ? { name: cfg.name, url: cfg.url, headerKeys: Object.keys(cfg.headers || {}).sort() }
743
- : { name: cfg.name, command: cfg.command, args: cfg.args, envKeys: Object.keys(cfg.env || {}).sort() }
889
+ ? { name: cfg.name, url: cfg.url, headerKeys: Object.keys(cfg.headers || {}).sort(), source: cfg.source }
890
+ : { name: cfg.name, command: cfg.command, args: cfg.args, envKeys: Object.keys(cfg.env || {}).sort(), source: cfg.source }
744
891
  const allowed = await pm.requestMcpTrust(trustReq)
745
892
  if (allowed) recordTrust(cfg, trustPath)
746
893
  return { allowed: allowed === true, prompted: true }
@@ -751,8 +898,15 @@ export class ClaudeByokSession extends BaseSession {
751
898
  * Build the in-memory fleet config from a normalized persisted entry, filling
752
899
  * the shape defaults (`args`/`env` for stdio, `headers` for remote) the fleet
753
900
  * and the trust key both read.
901
+ *
902
+ * #7939: optional `source` (an `MCP_SERVER_SOURCE` value) tags where this
903
+ * config came from — a discovered spec already carries one from
904
+ * `discoverMcpServerSpecs`, but a live `addMcpServer` entry has none until
905
+ * the caller derives it from the WRITE scope via `mcpWriteScopeToSource` and
906
+ * passes it here, so both paths converge on the same shape before either
907
+ * reaches the spawn-trust gate.
754
908
  */
755
- static _mcpCfgFromEntry(name, entry) {
909
+ static _mcpCfgFromEntry(name, entry, { source } = {}) {
756
910
  const cfg = { name, ...entry }
757
911
  if (cfg.command !== undefined) {
758
912
  cfg.args = Array.isArray(cfg.args) ? cfg.args : []
@@ -760,6 +914,7 @@ export class ClaudeByokSession extends BaseSession {
760
914
  } else {
761
915
  cfg.headers = cfg.headers && typeof cfg.headers === 'object' ? cfg.headers : {}
762
916
  }
917
+ if (source !== undefined) cfg.source = source
763
918
  return cfg
764
919
  }
765
920
 
@@ -788,7 +943,7 @@ export class ClaudeByokSession extends BaseSession {
788
943
  * duplicate name from a generic validation failure; `code: 'TRUST_DENIED'`
789
944
  * distinguishes "the user said no" from a failure.
790
945
  */
791
- async addMcpServer(name, config, scope = 'user') {
946
+ async addMcpServer(name, config, scope = 'user', { isAuthorized } = {}) {
792
947
  const valid = validateNewMcpServerName(name)
793
948
  if (!valid.ok) return { ok: false, error: valid.error }
794
949
 
@@ -807,7 +962,12 @@ export class ClaudeByokSession extends BaseSession {
807
962
  if (!planned.ok) return { ok: false, error: planned.error, code: planned.code }
808
963
 
809
964
  // The candidate config, exactly as it would be persisted and spawned.
810
- const cfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, planned.entry)
965
+ // #7939: tag it with the scope the user is adding it to (mapped onto the
966
+ // same MCP_SERVER_SOURCE vocabulary discovery uses) so the trust prompt
967
+ // for THIS add names its scope consistently with a rediscovered server.
968
+ const cfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, planned.entry, {
969
+ source: mcpWriteScopeToSource(planned.scope),
970
+ })
811
971
 
812
972
  const trust = await this._decideMcpSpawnTrust(cfg)
813
973
  if (!trust.allowed) {
@@ -818,6 +978,9 @@ export class ClaudeByokSession extends BaseSession {
818
978
  }
819
979
  }
820
980
 
981
+ // The trust prompt above was a wait: the requesting connection may have ended.
982
+ assertAuthorized(isAuthorized)
983
+
821
984
  let written
822
985
  try {
823
986
  written = addMcpServerToConfig({
@@ -847,8 +1010,12 @@ export class ClaudeByokSession extends BaseSession {
847
1010
  // diverge. Normalization is pure over (name, config), so this is structurally
848
1011
  // identical to the `cfg` the trust decision was made against — and if it ever
849
1012
  // were not, the fleet's own gate below would see an untrusted config and
850
- // prompt rather than spawn.
851
- const persistedCfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, written.entry)
1013
+ // prompt rather than spawn. #7939: carries the same write-scope-derived
1014
+ // `source` as `cfg` above, so a live-added server's fleet re-prompt (the
1015
+ // backstop in `MCPFleet.addServer`/`_makeClient`) shows the identical scope.
1016
+ const persistedCfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, written.entry, {
1017
+ source: mcpWriteScopeToSource(written.scope),
1018
+ })
852
1019
  this._mcpServerConfigs = [...this._mcpServerConfigs, persistedCfg]
853
1020
  this._refreshMcpServerMetadata()
854
1021
 
@@ -856,10 +1023,23 @@ export class ClaudeByokSession extends BaseSession {
856
1023
  if (this._mcpFleet) {
857
1024
  const result = await this._mcpFleet.addServer(persistedCfg)
858
1025
  if (result.status) status = result.status
1026
+ } else if (this._processReady) {
1027
+ // #7012: no fleet exists yet — either this is the session's first-ever
1028
+ // MCP server, or start() never spun one up because zero servers were
1029
+ // configured at start. `_mcpServerConfigs` already carries this server
1030
+ // (appended above), so `_ensureMcpFleet`'s constructor picks it up
1031
+ // directly; `fleet.addServer()` is not called on this path — see that
1032
+ // method's docstring for why.
1033
+ const fleet = await this._ensureMcpFleet()
1034
+ if (fleet) {
1035
+ const entry = fleet.getServerStatuses().find((s) => s.name === persistedCfg.name)
1036
+ if (entry?.status) status = entry.status
1037
+ }
859
1038
  }
860
- // No fleet yet (nothing was configured at start, so it was never created):
861
- // the entry is persisted and `start()` will pick it up. Spinning a fleet up
862
- // here would duplicate start()'s wiring for no gain.
1039
+ // else: addMcpServer was called before start() (production only ever
1040
+ // reaches a started session — the WS handler requires one). Leave status
1041
+ // 'configured' and let start() pick the persisted entry up normally,
1042
+ // rather than spawning an MCP child ahead of `_processReady`.
863
1043
  this._emitMcpServers()
864
1044
  const result = { ok: true, status }
865
1045
  if (written.warning) result.warning = written.warning
@@ -890,6 +1070,7 @@ export class ClaudeByokSession extends BaseSession {
890
1070
  scope,
891
1071
  cwd: this.cwd,
892
1072
  configPath: this._mcpConfigPath,
1073
+ _fsync: this._mcpConfigFsync,
893
1074
  })
894
1075
  } catch (err) {
895
1076
  return { ok: false, error: `Failed to write MCP config: ${err?.message || String(err)}` }
@@ -930,19 +1111,39 @@ export class ClaudeByokSession extends BaseSession {
930
1111
  return [...this._disabledMcpServers].sort()
931
1112
  }
932
1113
 
933
- async sendMessage(prompt, attachments, _options = {}) {
1114
+ async sendMessage(prompt, attachments, sendOptions = {}) {
934
1115
  if (this._isBusy) {
935
1116
  this.emit('error', { message: 'Already processing a message' })
1117
+ reportInputAdmission(sendOptions, {
1118
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1119
+ reason: 'busy', message: 'The provider is already processing a message.',
1120
+ })
936
1121
  return
937
1122
  }
938
1123
  if (this._destroying || !this._processReady || !this._client) {
939
1124
  this.emit('error', { message: 'Session not ready' })
1125
+ reportInputAdmission(sendOptions, {
1126
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1127
+ reason: 'not_runnable', message: 'The provider session is not ready to accept input.',
1128
+ })
1129
+ return
1130
+ }
1131
+ if (sendOptions.context && Array.isArray(attachments) && attachments.length > 0) {
1132
+ this.emit('error', {
1133
+ message: `BYOK provider does not yet materialise attachments (${attachments.length} dropped). Track follow-up: file-via-Read tool flow.`,
1134
+ })
1135
+ reportInputAdmission(sendOptions, {
1136
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1137
+ reason: 'unsupported_attachments', message: 'This provider does not support image context.',
1138
+ })
940
1139
  return
941
1140
  }
942
1141
 
943
1142
  // Claim busy up front so the async MCP-prompt resolution below can't race a
944
1143
  // second concurrent send (isRunning stays true across the await window).
945
1144
  this._isBusy = true
1145
+ // #8430: a new turn starts with no user Stop in flight, whatever the last one left.
1146
+ this._permissions.clearUserStopInFlight()
946
1147
 
947
1148
  // #6823: MCP prompt-as-slash-command interception. A leading
948
1149
  // `/mcp__<server>__<prompt>` that matches a connected MCP server's prompt
@@ -955,11 +1156,33 @@ export class ClaudeByokSession extends BaseSession {
955
1156
  if (mcpPromptMatch) {
956
1157
  try {
957
1158
  promptText = await this._resolveMcpPromptToText(mcpPromptMatch)
1159
+ if (!stillAuthorized(sendOptions.isAuthorized)) {
1160
+ this._isBusy = false
1161
+ this._permissions.clearUserStopInFlight()
1162
+ reportInputAdmission(sendOptions, {
1163
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1164
+ reason: 'connection_not_authorized', message: 'The sending connection is no longer authorized; the input was not dispatched.',
1165
+ })
1166
+ return
1167
+ }
1168
+ // #9242: the expansion is an await; re-ask admission before the marker, the
1169
+ // history entry and the stream. Refused: no dispatch, queued follow-ups go on.
1170
+ if (!this._admitPreparedSend(sendOptions)) {
1171
+ this._isBusy = false
1172
+ this._permissions.clearUserStopInFlight()
1173
+ reportInputAdmission(sendOptions, NOT_ADMITTED_ADMISSION)
1174
+ return
1175
+ }
958
1176
  } catch (err) {
959
1177
  this._isBusy = false
1178
+ this._permissions.clearUserStopInFlight() // #8430: this turn ends here, off the _finishTurn path
960
1179
  this.emit('error', {
961
1180
  message: `MCP prompt /${mcpPromptMatch.prefixedName} failed: ${err?.message || String(err)}`,
962
1181
  })
1182
+ reportInputAdmission(sendOptions, {
1183
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1184
+ reason: 'prompt_resolution_failed', message: 'The provider prompt could not be resolved before dispatch.',
1185
+ })
963
1186
  return
964
1187
  }
965
1188
  // #6845: honesty. The raw `/mcp__server__prompt` the user typed is NOT
@@ -1016,6 +1239,7 @@ export class ClaudeByokSession extends BaseSession {
1016
1239
  ? this._buildSystemPrompt()
1017
1240
  : ''
1018
1241
 
1242
+ this._toolResultsEmitted.clear()
1019
1243
  this.emit('stream_start', { messageId })
1020
1244
 
1021
1245
  // Agent loop. Each iteration:
@@ -1055,6 +1279,13 @@ export class ClaudeByokSession extends BaseSession {
1055
1279
  log.warn(`no pricing entry for model=${pricingModel}; result.cost will be 0 — update CLAUDE_PRICING_USD_PER_MTOK in models.js`)
1056
1280
  }
1057
1281
  let lastStopReason = null
1282
+ // #8461: set when the loop spends MAX_TOOL_ROUNDS; the forced summary round's
1283
+ // own `end_turn` overwrites lastStopReason, so the cap needs its own flag.
1284
+ let toolRoundCapReached = false
1285
+ // #7072: an interrupt that landed in the tool phase ends the loop below WITHOUT a
1286
+ // thrown abort, so the stream-phase catch never sees it. (A requested Stop that
1287
+ // lands in the stream phase reaches the same `result` through that catch, #8553.)
1288
+ let stoppedInToolPhase = false
1058
1289
  // Snapshot the pre-turn history length so any stream-init failure (at
1059
1290
  // any round) can rollback the entire turn atomically. We derive it
1060
1291
  // from the current length minus the user message we just pushed at
@@ -1065,13 +1296,20 @@ export class ClaudeByokSession extends BaseSession {
1065
1296
  // `user` turn back-to-back, soft-breaking the alternation invariant
1066
1297
  // the API may tighten on in future.
1067
1298
  const historyLengthBeforeSend = Math.max(0, this._history.length - 1)
1299
+ // #8559: text streamed by the round that is still in flight (not yet committed to
1300
+ // `_history`). A requested Stop mid-stream keeps it as a truncated assistant turn.
1301
+ let streamedText = ''
1302
+ // The summary round's instruction block (appended to the last tool_result turn)
1303
+ // while that round is in flight, so a requested Stop can take it back out.
1304
+ let pendingSummary = null
1068
1305
 
1069
1306
  try {
1070
1307
  for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
1308
+ streamedText = ''
1071
1309
  let stream
1072
1310
  try {
1073
1311
  stream = this._client.messages.stream(
1074
- {
1312
+ this._buildStreamParams({
1075
1313
  model: this.model || this._defaultModel,
1076
1314
  max_tokens: DEFAULT_MAX_TOKENS,
1077
1315
  ...(systemPrompt ? { system: systemPrompt } : {}),
@@ -1081,7 +1319,7 @@ export class ClaudeByokSession extends BaseSession {
1081
1319
  // turn without anything to invalidate.
1082
1320
  tools: this._buildTools(),
1083
1321
  messages: this._history,
1084
- },
1322
+ }),
1085
1323
  { signal: this._abortController.signal },
1086
1324
  )
1087
1325
  } catch (err) {
@@ -1094,14 +1332,25 @@ export class ClaudeByokSession extends BaseSession {
1094
1332
  if (this._history.length > historyLengthBeforeSend) {
1095
1333
  this._history.length = historyLengthBeforeSend
1096
1334
  }
1335
+ if (round === 0) {
1336
+ reportInputAdmission(sendOptions, {
1337
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1338
+ reason: 'stream_start_failed', message: 'The provider rejected the input before streaming began.',
1339
+ })
1340
+ }
1097
1341
  throw err
1098
1342
  }
1099
1343
 
1344
+ if (round === 0) {
1345
+ reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
1346
+ }
1347
+
1100
1348
  for await (const event of stream) {
1101
1349
  const t = translateSdkEvent(event)
1102
1350
  if (!t) continue
1103
1351
  switch (t.kind) {
1104
1352
  case 'stream_delta':
1353
+ streamedText += t.text
1105
1354
  this.emit('stream_delta', { messageId, delta: t.text })
1106
1355
  break
1107
1356
  case 'thinking_delta': {
@@ -1113,7 +1362,18 @@ export class ClaudeByokSession extends BaseSession {
1113
1362
  const idx = typeof t.index === 'number' ? t.index : 0
1114
1363
  let thinkingId = this._streamingIndexToThinkingId.get(idx)
1115
1364
  if (!thinkingId) {
1116
- thinkingId = `${messageId}-thinking-${idx}`
1365
+ // #6630: unique per thinking STREAM in the turn, not per block
1366
+ // index. The index restarts at 0 every tool round while the turn's
1367
+ // `messageId` does not, so `<turn>-thinking-<idx>` named a round-2
1368
+ // thought the same as the round-1 one: live, the client's accumulator
1369
+ // concatenated the two; the history (keyed by id) kept one. A counter
1370
+ // that runs for the whole turn keeps every stream's id its own, and
1371
+ // still ends in `-thinking-<n>` for the legacy classifier.
1372
+ if (this._thinkingSeqTurn !== messageId) {
1373
+ this._thinkingSeqTurn = messageId
1374
+ this._thinkingSeq = 0
1375
+ }
1376
+ thinkingId = `${messageId}-thinking-${this._thinkingSeq++}`
1117
1377
  this._streamingIndexToThinkingId.set(idx, thinkingId)
1118
1378
  // #6391 footer-stat: mark the block's start for the
1119
1379
  // content_block_stop elapsed-time computation. #6943:
@@ -1159,55 +1419,24 @@ export class ClaudeByokSession extends BaseSession {
1159
1419
  tool: t.toolName,
1160
1420
  input: null,
1161
1421
  })
1162
- // #4080: track index→toolUseId so the upcoming
1163
- // tool_input_delta events (which only carry the index)
1164
- // can be re-tagged with the toolUseId before re-emit.
1165
- if (typeof t.index === 'number' && t.toolUseId) {
1166
- this._streamingIndexToToolUseId.set(t.index, t.toolUseId)
1167
- }
1168
1422
  break
1169
1423
  }
1170
- case 'tool_input_delta': {
1171
- // #4080: stream the partial JSON to the dashboard so the
1172
- // tool-call bubble can live-preview the model's evolving
1173
- // input (especially valuable for Bash, where users can
1174
- // early-abort once they see a destructive `command`
1175
- // forming). The translator only carries the block index;
1176
- // resolve to toolUseId via the per-stream map we populated
1177
- // on tool_start.
1178
- const toolUseId = typeof t.index === 'number'
1179
- ? this._streamingIndexToToolUseId.get(t.index)
1180
- : undefined
1181
- if (!toolUseId) {
1182
- // Delta for a content block that wasn't a tool_use
1183
- // (text deltas already went through stream_delta) or
1184
- // for an index we never saw a start for (SDK reorder /
1185
- // malformed event). Drop quietly — the accepted shape
1186
- // for partial input is "may not arrive."
1187
- break
1188
- }
1189
- if (this._pendingPermissionToolUseIds.has(toolUseId)) {
1190
- // A permission prompt is pending for this exact
1191
- // toolUseId — suppress the delta so the bubble doesn't
1192
- // flicker between "running…" and partial-input while
1193
- // the user is mid-decision. See constructor comment.
1194
- break
1195
- }
1196
- this.emit('tool_input_delta', {
1197
- messageId,
1198
- toolUseId,
1199
- partialJson: t.partial,
1200
- })
1424
+ case 'tool_input_delta':
1425
+ // #8137: the SDK's raw `input_json_delta` chunks are
1426
+ // deliberately NOT forwarded — a secret can straddle chunk
1427
+ // boundaries (e.g. "export TOKEN=sk-" in one delta,
1428
+ // "ant-api03-…" in the next), and mid-stream partial JSON
1429
+ // generally isn't valid JSON, so it can't be parsed to run
1430
+ // `sanitizeToolInput`'s structured key/value passes over it
1431
+ // either. Matches the #8135 fix already applied to
1432
+ // cli-session.js / sdk-session.js: the sanitized FULL input
1433
+ // is instead delivered once, as a single `tool_input_delta`,
1434
+ // right after `stream.finalMessage()` resolves below — see
1435
+ // the loop over `toolBlocks` a few dozen lines down. Was
1436
+ // previously forwarded raw here (pre-#8137).
1201
1437
  break
1202
- }
1203
1438
  case 'content_block_stop':
1204
- // #4080: free the per-index slot as soon as the block
1205
- // finishes so a long turn's map doesn't grow unbounded.
1206
- // Safe to delete even if index isn't in the map — that
1207
- // just means we never tracked this block (text) and the
1208
- // lookup is a no-op.
1209
1439
  if (typeof t.index === 'number') {
1210
- this._streamingIndexToToolUseId.delete(t.index)
1211
1440
  // #6756 — close the thinking stream for this block so the
1212
1441
  // client finalises its "Thinking… → Thought" label.
1213
1442
  const thinkingId = this._streamingIndexToThinkingId.get(t.index)
@@ -1251,11 +1480,10 @@ export class ClaudeByokSession extends BaseSession {
1251
1480
  // #4080: defensive cleanup. content_block_stop should have
1252
1481
  // drained every entry above, but if the stream ended on an
1253
1482
  // error path or the SDK ever skips the stop event for a
1254
- // block, the map would leak across rounds and a later
1255
- // tool_input_delta for index N could pick up a STALE
1256
- // toolUseId from the previous round. Clear here so each round
1257
- // starts with an empty per-stream map.
1258
- this._streamingIndexToToolUseId.clear()
1483
+ // block, a thinking entry would leak across rounds and a later
1484
+ // delta for index N could route to a STALE thinking id from the
1485
+ // previous round. Clear here so each round starts with empty
1486
+ // per-stream maps.
1259
1487
  this._streamingIndexToThinkingId.clear()
1260
1488
  this._thinkingStartMs.clear()
1261
1489
  lastStopReason = final.stop_reason
@@ -1277,6 +1505,57 @@ export class ClaudeByokSession extends BaseSession {
1277
1505
  // Append the assistant turn — full content array preserves
1278
1506
  // tool_use blocks for the next round of conversation.
1279
1507
  this._history.push({ role: 'assistant', content: final.content })
1508
+ streamedText = ''
1509
+
1510
+ // Computed once — reused below both for the finalized
1511
+ // tool_input_delta emission (#8137) and, if the round proceeds
1512
+ // past the stop_reason check, for tool execution.
1513
+ const toolBlocks = (final.content || []).filter((b) => b?.type === 'tool_use')
1514
+
1515
+ // #8137: deliver the SANITIZED full input for every tool_use
1516
+ // block as a single `tool_input_delta`, now that
1517
+ // `stream.finalMessage()` has resolved and the complete, parsed
1518
+ // input is known. This REPLACES the raw per-chunk
1519
+ // `input_json_delta` forwarding removed from the
1520
+ // `tool_input_delta` case above — a secret can straddle chunk
1521
+ // boundaries and mid-stream partial JSON can't be sanitized, so
1522
+ // the safe delivery point is "sanitize the complete parsed
1523
+ // value, then send it once" (mirrors the #8135 fix already
1524
+ // applied to cli-session.js's `_captureFinalizedToolInput` /
1525
+ // sdk-session.js's `_handleToolUseBlock`). Runs through
1526
+ // `_recordToolInput` (base-session.js), the same #6029
1527
+ // `sanitizeToolInput` floor already applied on the
1528
+ // permission_request path — BYOK never populates
1529
+ // `_inFlightToolStarts`, so the tracking half of
1530
+ // `_recordToolInput` is a no-op here, but the sanitize call
1531
+ // always runs. Emitted before the `lastStopReason` check below
1532
+ // so the client sees the tool's input even in the
1533
+ // (should-never-happen) case where the API pairs tool_use
1534
+ // content with a non-tool_use stop_reason.
1535
+ for (const block of toolBlocks) {
1536
+ const toolUseId = block?.id
1537
+ if (!toolUseId) continue
1538
+ if (this._pendingPermissionToolUseIds.has(toolUseId)) {
1539
+ // Defensive — mirrors the pre-#8137 per-chunk suppression
1540
+ // (see the constructor comment on
1541
+ // `_pendingPermissionToolUseIds`). Today permission gating
1542
+ // for this toolUseId can't start until AFTER this point in
1543
+ // the same round (`_processToolBlocks` runs later, below),
1544
+ // so this branch is unreachable in production; kept in case
1545
+ // a future refactor requests permission before a round's
1546
+ // tool inputs are surfaced.
1547
+ continue
1548
+ }
1549
+ const sanitizedInput = this._recordToolInput(toolUseId, block.input ?? null)
1550
+ // `null`/`undefined` means "known to have no input" — don't
1551
+ // ship a literal "null" chunk for it (mirrors sdk-session.js).
1552
+ if (sanitizedInput === null || sanitizedInput === undefined) continue
1553
+ this.emit('tool_input_delta', {
1554
+ messageId,
1555
+ toolUseId,
1556
+ partialJson: JSON.stringify(sanitizedInput),
1557
+ })
1558
+ }
1280
1559
 
1281
1560
  if (lastStopReason !== 'tool_use') {
1282
1561
  // Done — model wants no more tools. Break out and emit result.
@@ -1315,7 +1594,6 @@ export class ClaudeByokSession extends BaseSession {
1315
1594
  // 'Interrupted' tool_result (same #4061 invariant). If it trips
1316
1595
  // mid-execution, the shared AbortSignal propagates to
1317
1596
  // executeBuiltinTool and any in-flight tool aborts cleanly.
1318
- const toolBlocks = (final.content || []).filter((b) => b?.type === 'tool_use')
1319
1597
  const toolResults = await this._processToolBlocks({ toolBlocks, messageId })
1320
1598
  if (toolResults.length === 0) {
1321
1599
  // stop_reason was tool_use but no tool_use blocks — defensive
@@ -1325,7 +1603,17 @@ export class ClaudeByokSession extends BaseSession {
1325
1603
  }
1326
1604
  this._history.push({ role: 'user', content: toolResults })
1327
1605
 
1328
- if (this._abortController?.signal?.aborted) break
1606
+ if (this._abortController?.signal?.aborted) {
1607
+ // #7072: the tool results above are committed to history (the #4061
1608
+ // invariant) and the turn's spend is real, so this still ends in a
1609
+ // `result` -- but one that says the turn was STOPPED, not a success. The
1610
+ // stream-phase abort throws into the catch below, which ends a REQUESTED
1611
+ // Stop in the same result (#8553); this path never throws. byok emits no
1612
+ // `stopped` of its own, so the result is the only terminal event an
1613
+ // orchestration TurnDriver hears (BaseSession.emit adds the quiet one).
1614
+ stoppedInToolPhase = true
1615
+ break
1616
+ }
1329
1617
 
1330
1618
  if (round === MAX_TOOL_ROUNDS - 1) {
1331
1619
  // #4063: instead of bailing silently, run ONE more text-only
@@ -1336,6 +1624,7 @@ export class ClaudeByokSession extends BaseSession {
1336
1624
  // content block on the existing tool_result user turn rather
1337
1625
  // than pushing a second user turn back-to-back.
1338
1626
  log.warn(`hit MAX_TOOL_ROUNDS=${MAX_TOOL_ROUNDS} cap; running summary round`)
1627
+ toolRoundCapReached = true
1339
1628
 
1340
1629
  // Emit a non-fatal error so the dashboard can render a warning
1341
1630
  // banner. The session stays alive — the user can keep talking;
@@ -1364,10 +1653,12 @@ export class ClaudeByokSession extends BaseSession {
1364
1653
  break
1365
1654
  }
1366
1655
 
1656
+ pendingSummary = { turn: lastTurn, block: summaryInstruction }
1657
+ streamedText = ''
1367
1658
  let summaryStream
1368
1659
  try {
1369
1660
  summaryStream = this._client.messages.stream(
1370
- {
1661
+ this._buildStreamParams({
1371
1662
  model: this.model || this._defaultModel,
1372
1663
  max_tokens: DEFAULT_MAX_TOKENS,
1373
1664
  ...(systemPrompt ? { system: systemPrompt } : {}),
@@ -1375,7 +1666,7 @@ export class ClaudeByokSession extends BaseSession {
1375
1666
  // tried to tool_use, the API would reject (no tools to
1376
1667
  // dispatch to). Cleaner to just omit.
1377
1668
  messages: this._history,
1378
- },
1669
+ }),
1379
1670
  { signal: this._abortController.signal },
1380
1671
  )
1381
1672
  } catch (err) {
@@ -1401,6 +1692,7 @@ export class ClaudeByokSession extends BaseSession {
1401
1692
  if (!t) continue
1402
1693
  switch (t.kind) {
1403
1694
  case 'stream_delta':
1695
+ streamedText += t.text
1404
1696
  this.emit('stream_delta', { messageId, delta: t.text })
1405
1697
  break
1406
1698
  case 'message_delta':
@@ -1427,6 +1719,8 @@ export class ClaudeByokSession extends BaseSession {
1427
1719
  if (c !== null) { turnCost += c; turnCostKnown = true }
1428
1720
  }
1429
1721
  this._history.push({ role: 'assistant', content: summaryFinal.content })
1722
+ streamedText = ''
1723
+ pendingSummary = null
1430
1724
  break
1431
1725
  }
1432
1726
  }
@@ -1455,27 +1749,17 @@ export class ClaudeByokSession extends BaseSession {
1455
1749
  // keep their previous snapshot.
1456
1750
  const finalRoundOccupancy = ClaudeByokSession._buildFinalRoundOccupancy(lastRoundUsage)
1457
1751
 
1458
- this.emit('stream_end', { messageId })
1459
- this.emit('result', {
1460
- sessionId: null,
1752
+ this._emitTurnResult({
1461
1753
  messageId,
1462
- stopReason: lastStopReason,
1463
- duration: Date.now() - turnStartedAt,
1464
- usage: turnUsage,
1465
- ...(finalRoundOccupancy ? { contextOccupancy: finalRoundOccupancy } : {}),
1466
- // #5630: emit null when no round produced a known cost so the UI
1467
- // shows "n/a" instead of a misleading $0.00.
1468
- cost: turnCostKnown ? turnCost : null,
1469
- // #6692: single-model split. Task-subagent usage is folded into
1470
- // turnUsage under the parent's model, which is CORRECT today because
1471
- // children hard-inherit the parent model (see _executeTaskTool). If a
1472
- // per-profile model override ever lands (#5018's deferred AC), that
1473
- // change must split this map by actual child model (#5020).
1474
- modelUsage: synthesizeModelUsage(
1475
- this.model || this._defaultModel,
1476
- turnUsage,
1477
- turnCostKnown ? turnCost : null,
1478
- ),
1754
+ lastStopReason,
1755
+ toolRoundCapReached,
1756
+ interrupted: stoppedInToolPhase,
1757
+ stopRequested: stoppedInToolPhase, // #9241: the tool-phase abort IS the Stop
1758
+ turnStartedAt,
1759
+ turnUsage,
1760
+ turnCost,
1761
+ turnCostKnown,
1762
+ finalRoundOccupancy,
1479
1763
  })
1480
1764
  } catch (err) {
1481
1765
  // #4118: extend the synchronous stream-init rollback (#4109) to
@@ -1496,7 +1780,17 @@ export class ClaudeByokSession extends BaseSession {
1496
1780
  // Truncating to historyLengthBeforeSend is idempotent: if the
1497
1781
  // inner stream-init catch already truncated (round-0 path), the
1498
1782
  // length is already at or below the snapshot and this is a no-op.
1499
- if (this._history.length > historyLengthBeforeSend) {
1783
+ //
1784
+ // #8559: the exception is a Stop somebody requested while the model was
1785
+ // STREAMING. The tool-phase Stop above keeps the prompt and every completed
1786
+ // round, so this one does too: the user asked for the turn to END, not to be
1787
+ // erased, and the next prompt ("what did I just ask?") needs it. Every other
1788
+ // abort (a destroy, a parent's cascade) and every provider error keeps the
1789
+ // rollback: nobody asked for those turns to count.
1790
+ const requestedStop = this._isRequestedStop(err)
1791
+ if (requestedStop) {
1792
+ this._commitStoppedStream({ streamedText, historyLengthBeforeSend, pendingSummary, messageId })
1793
+ } else if (this._history.length > historyLengthBeforeSend) {
1500
1794
  this._history.length = historyLengthBeforeSend
1501
1795
  }
1502
1796
  // #5020: fold any subagent (Task tool) usage + cost into the
@@ -1512,6 +1806,27 @@ export class ClaudeByokSession extends BaseSession {
1512
1806
  turnUsage.cache_creation_input_tokens += this._subagentUsageThisTurn.cache_creation_input_tokens
1513
1807
  turnCost += this._subagentCostThisTurn
1514
1808
  if (this._subagentCostThisTurn > 0) turnCostKnown = true
1809
+ // #8553: a Stop somebody requested that lands while the model is STREAMING
1810
+ // ends the turn exactly as the tool-phase one does (#7072): one `result`
1811
+ // that says it was stopped, then the quiet `stopped` BaseSession.emit adds
1812
+ // for it, and no `error`. The rollback and the usage fold above already ran
1813
+ // and are the same either way.
1814
+ if (requestedStop) {
1815
+ this._emitTurnResult({
1816
+ messageId,
1817
+ lastStopReason,
1818
+ toolRoundCapReached,
1819
+ interrupted: true,
1820
+ // #9241: only an abort is the Stop; any other error that raced it is not
1821
+ stopRequested: ClaudeByokSession._isGenuineAbort(err),
1822
+ turnStartedAt,
1823
+ turnUsage,
1824
+ turnCost,
1825
+ turnCostKnown,
1826
+ finalRoundOccupancy: ClaudeByokSession._buildFinalRoundOccupancy(lastRoundUsage),
1827
+ })
1828
+ return
1829
+ }
1515
1830
  this.emit('stream_end', { messageId })
1516
1831
  this._emitTurnError(messageId, err, 'STREAM_ERROR', {
1517
1832
  usage: turnUsage,
@@ -1529,12 +1844,11 @@ export class ClaudeByokSession extends BaseSession {
1529
1844
  } finally {
1530
1845
  // #4080: per-turn isolation guarantee. The per-round clear after
1531
1846
  // finalMessage() above runs on the success path; an iteration or
1532
- // finalMessage() throw skips it and would leak stale
1533
- // index→toolUseId entries into the next turn (mis-tagging the
1534
- // next stream's tool_input_delta events). Clearing here drains
1535
- // them on every exit path — success, error, abort, hard timeout.
1536
- // Safe to call when already empty.
1537
- this._streamingIndexToToolUseId.clear()
1847
+ // finalMessage() throw skips it and would leak stale per-index
1848
+ // entries into the next turn (mis-routing the next stream's
1849
+ // thinking deltas). Clearing here drains them on every exit path
1850
+ // — success, error, abort, hard timeout. Safe to call when
1851
+ // already empty.
1538
1852
  this._streamingIndexToThinkingId.clear()
1539
1853
  this._thinkingStartMs.clear()
1540
1854
  this._finishTurn()
@@ -1574,19 +1888,11 @@ export class ClaudeByokSession extends BaseSession {
1574
1888
  // inter-phase guard fires when startIndex === 0, but only the
1575
1889
  // blocks that *would* have executed in phase 2 need filling).
1576
1890
  if (toolResults[j]) continue
1577
- const remaining = toolBlocks[j]
1578
- this.emit('tool_result', {
1891
+ toolResults[j] = this._interruptedToolResult({
1579
1892
  messageId,
1580
- toolUseId: remaining.id,
1581
- result: interrupted,
1582
- isError: true,
1583
- })
1584
- toolResults[j] = {
1585
- type: 'tool_result',
1586
- tool_use_id: remaining.id,
1893
+ toolUseId: toolBlocks[j].id,
1587
1894
  content: interrupted,
1588
- is_error: true,
1589
- }
1895
+ })
1590
1896
  }
1591
1897
  }
1592
1898
 
@@ -1682,6 +1988,8 @@ export class ClaudeByokSession extends BaseSession {
1682
1988
  input,
1683
1989
  signal,
1684
1990
  this.permissionMode,
1991
+ undefined,
1992
+ toolUseId,
1685
1993
  )
1686
1994
  } catch (err) {
1687
1995
  // permission_request was rejected (timeout, abort, etc.). Surface
@@ -1724,7 +2032,7 @@ export class ClaudeByokSession extends BaseSession {
1724
2032
 
1725
2033
  if (resolvedDecision.behavior !== 'allow') {
1726
2034
  const msg = resolvedDecision.message || 'Permission denied by user.'
1727
- this.emit('tool_result', {
2035
+ this._emitToolResult({
1728
2036
  messageId,
1729
2037
  toolUseId,
1730
2038
  result: msg,
@@ -1771,7 +2079,7 @@ export class ClaudeByokSession extends BaseSession {
1771
2079
  }
1772
2080
  const { content, isError } = dispatchResult
1773
2081
 
1774
- this.emit('tool_result', {
2082
+ this._emitToolResult({
1775
2083
  messageId,
1776
2084
  toolUseId,
1777
2085
  result: content,
@@ -1916,10 +2224,12 @@ export class ClaudeByokSession extends BaseSession {
1916
2224
  // `description`, `startedAt`). The toolUseId matches the parent
1917
2225
  // turn's tool_use block id so the dashboard correlates the spawn
1918
2226
  // with the open tool_call bubble.
2227
+ // #7340: byok's Task tool AWAITS its child in-process (the tool result is
2228
+ // the child's answer), so a byok subagent can never outlive its turn —
2229
+ // `background: false` is a statement of fact here, not a default, and it
2230
+ // keeps byok agents eligible for the turn-end orphan sweep.
1919
2231
  const startedAt = Date.now()
1920
- const agentInfo = { toolUseId, description, startedAt }
1921
- this._activeAgents.set(toolUseId, agentInfo)
1922
- this.emit('agent_spawned', agentInfo)
2232
+ this._trackAgent({ toolUseId, description, background: false, startedAt })
1923
2233
 
1924
2234
  // Build a child session. Reuse this session's already-resolved
1925
2235
  // client so the API key resolution + Anthropic constructor only
@@ -1958,7 +2268,14 @@ export class ClaudeByokSession extends BaseSession {
1958
2268
  cwd: this.cwd,
1959
2269
  model: this.model || this._defaultModel,
1960
2270
  mcpConfigPath: null,
2271
+ projectInstructions: this.projectInstructions,
1961
2272
  })
2273
+ if (this.providerInstructionProjection?.status === 'delivered') {
2274
+ child._installProjectInstructionProjection({
2275
+ ...this.providerInstructionProjection,
2276
+ text: this.projectInstructions,
2277
+ })
2278
+ }
1962
2279
  // Skip start()'s credential resolution — share the parent's client
1963
2280
  // so the child uses the same API key path. Also avoids a duplicate
1964
2281
  // credentials.json read which could rate-limit on disk for parallel
@@ -2137,7 +2454,7 @@ export class ClaudeByokSession extends BaseSession {
2137
2454
  // already iterates _subagentSessions, but this listener also
2138
2455
  // catches the micro-race when the signal aborts between the
2139
2456
  // top-of-function check and child.sendMessage's first await.
2140
- const onAbort = () => { try { child.interrupt() } catch { /* noop */ } }
2457
+ const onAbort = () => { try { child.interrupt({ cascaded: true }) } catch { /* noop */ } }
2141
2458
  if (signal) {
2142
2459
  if (signal.aborted) onAbort()
2143
2460
  else signal.addEventListener('abort', onAbort, { once: true })
@@ -2236,10 +2553,19 @@ export class ClaudeByokSession extends BaseSession {
2236
2553
  * @param {object} payload
2237
2554
  */
2238
2555
  _emitAgentEvent(parentToolUseId, type, payload) {
2556
+ let wirePayload = payload ?? {}
2557
+ // #8397: `recordDescription` is an in-process field of the child's
2558
+ // `permission_request` (read by the session that owns the prompt to record
2559
+ // its outcome), not part of the wire shape. Every child relay passes through
2560
+ // here, so it is dropped here, once.
2561
+ if (type === 'permission_request' && wirePayload && typeof wirePayload === 'object' && 'recordDescription' in wirePayload) {
2562
+ const { recordDescription: _internal, ...rest } = wirePayload
2563
+ wirePayload = rest
2564
+ }
2239
2565
  this.emit('agent_event', {
2240
2566
  parentToolUseId,
2241
2567
  type,
2242
- payload: payload ?? {},
2568
+ payload: wirePayload,
2243
2569
  })
2244
2570
  }
2245
2571
 
@@ -2476,7 +2802,7 @@ export class ClaudeByokSession extends BaseSession {
2476
2802
  * PermissionManager which resolves the pending Promise in
2477
2803
  * handlePermission() above.
2478
2804
  */
2479
- respondToPermission(requestId, decision, editedInput, reason) {
2805
+ respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy) {
2480
2806
  // #5056: if this requestId belongs to a Task subagent (its pending
2481
2807
  // entry lives in the CHILD's PermissionManager, not ours), forward
2482
2808
  // the decision to that child. ws-permissions only ever calls the
@@ -2487,23 +2813,30 @@ export class ClaudeByokSession extends BaseSession {
2487
2813
  // already authorized against the parent session by ws-permissions.
2488
2814
  const child = this._subagentPermissionRouting.get(requestId)
2489
2815
  if (child) {
2490
- // Drop the routing entry first so a duplicate/late response can't
2491
- // re-resolve a stale id. The child also emits permission_resolved
2492
- // which our relay listener uses to clear the same entry — deleting
2493
- // here too is idempotent and closes the lifetime tightly.
2494
- this._subagentPermissionRouting.delete(requestId)
2495
2816
  // #6543: forward the operator's per-hunk editedInput to the child too.
2496
2817
  // #6773: the deny `reason` forwards to the child as well.
2497
- return child.respondToPermission(requestId, decision, editedInput, reason)
2818
+ // #8517: so does the session-scope label.
2819
+ const resolved = child.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
2820
+ // Drop the routing entry once the child has taken the response, so a
2821
+ // duplicate/late response can't re-resolve a stale id. The child also emits
2822
+ // permission_resolved which our relay listener uses to clear the same entry
2823
+ // — deleting here too is idempotent and closes the lifetime tightly.
2824
+ // #8446: NOT before the call. A child that REFUSES an edit throws with its
2825
+ // request still pending, and the caller's follow-up deny must find the route
2826
+ // to reach it; a route dropped first sent that deny to this manager, which
2827
+ // does not hold the request, and the child waited out its timeout.
2828
+ this._subagentPermissionRouting.delete(requestId)
2829
+ return resolved
2498
2830
  }
2499
- return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
2831
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
2500
2832
  }
2501
2833
 
2502
2834
  /**
2503
2835
  * Response to an AskUserQuestion tool. Same forwarding pattern.
2504
2836
  */
2505
- respondToQuestion(text, answersMap) {
2506
- this._permissions.respondToQuestion(text, answersMap)
2837
+ respondToQuestion(text, answersMap, toolUseId) {
2838
+ // #8460: the id lets the manager refuse an answer meant for a different question.
2839
+ return this._permissions.respondToQuestion(text, answersMap, toolUseId)
2507
2840
  }
2508
2841
 
2509
2842
  /**
@@ -2544,6 +2877,179 @@ export class ClaudeByokSession extends BaseSession {
2544
2877
  }
2545
2878
  }
2546
2879
 
2880
+ /**
2881
+ * #8553: the one way a turn's terminal `result` is built and sent, for the
2882
+ * normal ending and for a requested Stop alike (tool phase #7072, stream phase
2883
+ * #8553). `interrupted` makes the outcome `stopped` and marks the result
2884
+ * terminal-but-not-successful; BaseSession.emit turns that into the quiet
2885
+ * `stopped` when the Stop was requested. Emits `stream_end` first.
2886
+ */
2887
+ _emitTurnResult({
2888
+ messageId, lastStopReason, toolRoundCapReached, interrupted, stopRequested = false,
2889
+ turnStartedAt, turnUsage, turnCost, turnCostKnown, finalRoundOccupancy,
2890
+ }) {
2891
+ this.emit('stream_end', { messageId })
2892
+ this.emit('result', {
2893
+ sessionId: null,
2894
+ messageId,
2895
+ stopReason: lastStopReason,
2896
+ // #7326: the provider-neutral form of the stop reason above, for the wire.
2897
+ // (A different key on purpose: `stopReason` is the raw Anthropic string.)
2898
+ ...turnOutcomeField(outcomeFromByokTurn({ stopReason: lastStopReason, toolRoundCapReached, interrupted })),
2899
+ // #7072: terminal but not successful (internal; not on the wire).
2900
+ ...(interrupted ? { interrupted: true } : {}),
2901
+ ...(stopRequested ? { stopRequested: true } : {}), // #9241 (internal; stripped by BaseSession.emit)
2902
+ duration: Date.now() - turnStartedAt,
2903
+ usage: turnUsage,
2904
+ ...(finalRoundOccupancy ? { contextOccupancy: finalRoundOccupancy } : {}),
2905
+ // #5630: emit null when no round produced a known cost so the UI
2906
+ // shows "n/a" instead of a misleading $0.00.
2907
+ cost: turnCostKnown ? turnCost : null,
2908
+ // #6692: single-model split. Task-subagent usage is folded into
2909
+ // turnUsage under the parent's model, which is CORRECT today because
2910
+ // children hard-inherit the parent model (see _executeTaskTool). If a
2911
+ // per-profile model override ever lands (#5018's deferred AC), that
2912
+ // change must split this map by actual child model (#5020).
2913
+ modelUsage: synthesizeModelUsage(
2914
+ this.model || this._defaultModel,
2915
+ turnUsage,
2916
+ turnCostKnown ? turnCost : null,
2917
+ ),
2918
+ })
2919
+ }
2920
+
2921
+ /** True when `err` is the abort of an in-flight stream (see _emitTurnError). */
2922
+ _isAbortError(err) {
2923
+ // #9266: an aborted controller used to make ANY error an abort, so an
2924
+ // upstream HTTP 500 that raced a Stop ended as a quiet stopped turn and the
2925
+ // error was never shown. Now an error carrying evidence that it came from
2926
+ // upstream (an SDK APIError with an HTTP status, or an SSE `error` body) is
2927
+ // surfaced even after the Stop. Once the signal IS aborted, every other
2928
+ // error is treated as the Stop's own fallout: the shapes the SDK/undici throw
2929
+ // BECAUSE of the abort (an abort on the `cause` chain, or a bare `terminated`/
2930
+ // connection error with no status, incl. APIConnectionTimeoutError) are
2931
+ // deliberately quiet, so a real Stop never shows a spurious error. With no
2932
+ // Stop, only the error's own top-level abort shape counts (pre-#9266).
2933
+ if (ClaudeByokSession._isUpstreamError(err)) return false
2934
+ return err instanceof APIUserAbortError ||
2935
+ err?.name === 'AbortError' ||
2936
+ !!this._abortController?.signal?.aborted
2937
+ }
2938
+
2939
+ /**
2940
+ * #9266: the error itself says it is an abort: the SDK's APIUserAbortError, a
2941
+ * fetch/DOMException `AbortError`, or either of those anywhere on its `cause`
2942
+ * chain (undici's `terminated` and the SDK's AnthropicError/APIConnectionError
2943
+ * wrappers carry the abort as `cause`). No signal state is consulted.
2944
+ */
2945
+ static _isGenuineAbort(err) {
2946
+ for (let e = err, depth = 0; e && depth < 5; e = e.cause, depth++) {
2947
+ if (e instanceof APIUserAbortError || e.name === 'AbortError') return true
2948
+ }
2949
+ return false
2950
+ }
2951
+
2952
+ /**
2953
+ * #9266: evidence that `err` is a real upstream response, independent of any
2954
+ * abort: an HTTP status, or the body of an SSE `error` event (the SDK keeps it
2955
+ * as the parsed object, or as the raw string when it is not JSON).
2956
+ */
2957
+ static _isUpstreamError(err) {
2958
+ if (ClaudeByokSession._isGenuineAbort(err)) return false
2959
+ if (Number.isInteger(err?.status)) return true
2960
+ const body = err?.error
2961
+ return (body != null && typeof body === 'object') ||
2962
+ (typeof body === 'string' && body.length > 0)
2963
+ }
2964
+
2965
+ /**
2966
+ * #8553: did somebody ASK for the abort `err` reports? True only for an abort
2967
+ * that came through interrupt() (the user, the scheduler, the orchestration
2968
+ * watchdog). Not a teardown (destroy() calls interrupt() too, but nobody is
2969
+ * waiting for a stopped turn), and not the abort a parent's Stop cascades to
2970
+ * its Task subagent, which the parent reports as the subagent's failure.
2971
+ */
2972
+ _isRequestedStop(err) {
2973
+ return this._isAbortError(err) &&
2974
+ this._stopRequestedThisTurn &&
2975
+ !this._destroying &&
2976
+ !this._abortCascaded
2977
+ }
2978
+
2979
+ /**
2980
+ * Emit a `tool_result` event and remember its tool_use id for the turn (#8569).
2981
+ * Every tool_result event this session sends goes through here, so "has this tool
2982
+ * been closed on the client?" has one answer.
2983
+ */
2984
+ _emitToolResult({ messageId, toolUseId, result, isError }) {
2985
+ this._toolResultsEmitted.add(toolUseId)
2986
+ this.emit('tool_result', { messageId, toolUseId, result, isError })
2987
+ }
2988
+
2989
+ /**
2990
+ * The synthesized `is_error` tool_result for a tool the user's Stop kept from
2991
+ * running to a result: emits the closing event for the client's tool row and
2992
+ * returns the content block that answers the tool_use in `_history`. The one
2993
+ * place that shape lives -- the tool-phase Stop (`_processToolBlocks`) and the
2994
+ * Stop that threw between the history pushes (`_commitStoppedStream`) both use it.
2995
+ */
2996
+ _interruptedToolResult({ messageId, toolUseId, content }) {
2997
+ this._emitToolResult({ messageId, toolUseId, result: content, isError: true })
2998
+ return { type: 'tool_result', tool_use_id: toolUseId, content, is_error: true }
2999
+ }
3000
+
3001
+ /**
3002
+ * #8559: settle `_history` after a requested Stop that ended the turn by a throw.
3003
+ *
3004
+ * Whatever the tail is, it leaves `_history` a VALID conversation (the next
3005
+ * request is never rejected for it) and keeps the prompt and the completed work:
3006
+ *
3007
+ * - `user` tail (the stop cut a stream short; the in-flight round's assistant
3008
+ * turn is only committed once its stream finishes): close it with an assistant
3009
+ * turn holding the text that did stream -- what Claude Code keeps -- so the
3010
+ * next request alternates strictly. Only text is kept: a half-streamed
3011
+ * tool_use has no result to pair with. With no text at all a placeholder
3012
+ * stands in, because an empty text block is refused.
3013
+ * - `assistant` tail with tool_use blocks (the stop threw between the round's
3014
+ * assistant push and its tool_result push): the tool_use would be unanswered,
3015
+ * which the API refuses on every later request, so answer each with a
3016
+ * synthesized is_error tool_result, as the tool-phase Stop does (#4061). The
3017
+ * rounds before it stay too; rolling back instead would drop the prompt.
3018
+ * Each also gets the `tool_result` event that closes its row on the client
3019
+ * (#8569), unless its real result already went out.
3020
+ * - `assistant` tail without tool_use: already a valid end, left alone.
3021
+ *
3022
+ * A no-op only when the turn is already rolled back (a stream-init failure).
3023
+ */
3024
+ _commitStoppedStream({ streamedText, historyLengthBeforeSend, pendingSummary, messageId }) {
3025
+ if (this._history.length <= historyLengthBeforeSend) return
3026
+ const tail = this._history[this._history.length - 1]
3027
+ if (tail?.role === 'assistant') {
3028
+ const uses = Array.isArray(tail.content) ? tail.content.filter((b) => b?.type === 'tool_use') : []
3029
+ if (uses.length > 0) {
3030
+ // #8569: the client opened a row for each of these on `tool_start`, and only
3031
+ // a `tool_result` event closes it. Emit the same interrupted result the
3032
+ // tool-phase Stop does, except for a tool whose real result already went out.
3033
+ this._history.push({
3034
+ role: 'user',
3035
+ content: uses.map((b) => (this._toolResultsEmitted.has(b.id)
3036
+ ? { type: 'tool_result', tool_use_id: b.id, content: STOPPED_BEFORE_TOOL, is_error: true }
3037
+ : this._interruptedToolResult({ messageId, toolUseId: b.id, content: STOPPED_BEFORE_TOOL }))),
3038
+ })
3039
+ }
3040
+ return
3041
+ }
3042
+ if (pendingSummary && pendingSummary.turn === tail && Array.isArray(tail.content)) {
3043
+ // The summary round never ran to completion: take its instruction back out so
3044
+ // the next turn is not told to stop using tools.
3045
+ tail.content = tail.content.filter((b) => b !== pendingSummary.block)
3046
+ }
3047
+ this._history.push({
3048
+ role: 'assistant',
3049
+ content: [{ type: 'text', text: streamedText.trim() ? streamedText : STOPPED_BEFORE_TEXT }],
3050
+ })
3051
+ }
3052
+
2547
3053
  _emitTurnError(messageId, err, fallbackCode, partials) {
2548
3054
  // #4057: SDK v0.81+ throws `APIUserAbortError` (not the generic
2549
3055
  // `AbortError`) when an in-flight messages.stream sees its signal
@@ -2563,11 +3069,7 @@ export class ClaudeByokSession extends BaseSession {
2563
3069
  // so additional fields propagate without a wire-side schema change.
2564
3070
  // Optional / undefined-safe: pre-#5020 call sites pass nothing and
2565
3071
  // the fields are simply absent on the event payload.
2566
- const aborted =
2567
- err instanceof APIUserAbortError ||
2568
- err?.name === 'AbortError' ||
2569
- this._abortController?.signal?.aborted
2570
- if (aborted) {
3072
+ if (this._isAbortError(err)) {
2571
3073
  this.emit('error', {
2572
3074
  messageId,
2573
3075
  message: 'Interrupted by user',
@@ -2587,6 +3089,9 @@ export class ClaudeByokSession extends BaseSession {
2587
3089
  }
2588
3090
 
2589
3091
  _finishTurn() {
3092
+ // #8430: a user Stop belongs to the turn it was pressed on; BYOK's teardown
3093
+ // does not go through BaseSession._clearMessageState, so clear it here.
3094
+ this._permissions.clearUserStopInFlight()
2590
3095
  this._isBusy = false
2591
3096
  this._currentMessageId = null
2592
3097
  this._abortController = null
@@ -2595,10 +3100,31 @@ export class ClaudeByokSession extends BaseSession {
2595
3100
  // fired and the fold-in step above was skipped.
2596
3101
  this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
2597
3102
  this._subagentCostThisTurn = 0
3103
+ // #7072/#8461: this teardown skips BaseSession._clearMessageState, so the
3104
+ // turn-scoped Stop request (see interrupt()) is cleared here, or it would tag
3105
+ // the NEXT turn's own abort as a requested Stop.
3106
+ this._stopRequestedThisTurn = false
3107
+ this._abortCascaded = false
3108
+ this._clearIntentionalStop()
2598
3109
  }
2599
3110
 
2600
- interrupt() {
3111
+ /**
3112
+ * @param {{ cascaded?: boolean }} [opts] `cascaded`: the parent session is
3113
+ * stopping this Task subagent (its own Stop reaching it, or a cancel of this
3114
+ * one node), rather than a Stop of this session (#8553).
3115
+ */
3116
+ interrupt({ cascaded = false } = {}) {
2601
3117
  if (!this._isBusy) return
3118
+ if (cascaded) this._abortCascaded = true
3119
+ // #7072/#8461/#8553: a Stop somebody requested (the user, the scheduler, the
3120
+ // orchestration watchdog) is acknowledged by one quiet `stopped` instead of a
3121
+ // "Stopped" chip, exactly as on claude-sdk and claude-cli. Both phases end in a
3122
+ // `result` (see sendMessage): the tool-phase abort never throws, and the
3123
+ // stream-phase one is turned into the same result by the catch, so
3124
+ // BaseSession.emit drops the chip and sends the confirmation, after marking the
3125
+ // result `interrupted`.
3126
+ this.markIntentionalStop()
3127
+ this._noteTurnStopRequested()
2602
3128
  if (this._abortController) {
2603
3129
  this._abortController.abort()
2604
3130
  }
@@ -2608,7 +3134,7 @@ export class ClaudeByokSession extends BaseSession {
2608
3134
  // _executeTaskTool's awaited promise resolve and the parent's
2609
3135
  // outer agent loop can finish the user-facing result event.
2610
3136
  for (const child of this._subagentSessions.values()) {
2611
- try { child.interrupt() } catch (err) {
3137
+ try { child.interrupt({ cascaded: true }) } catch (err) {
2612
3138
  log.warn(`subagent interrupt failed: ${err?.message || err}`)
2613
3139
  }
2614
3140
  }
@@ -2651,7 +3177,9 @@ export class ClaudeByokSession extends BaseSession {
2651
3177
  // optimistically finalize the node, matching the SDK path's best-effort
2652
3178
  // stopTask contract.
2653
3179
  try {
2654
- child.interrupt()
3180
+ // A cancel of one node reaches the subagent like the parent's own Stop
3181
+ // does: the parent reports it as the subagent's failure (#8553).
3182
+ child.interrupt({ cascaded: true })
2655
3183
  } catch (err) {
2656
3184
  log.warn(`subagent cancel failed for ${activityId}: ${err?.message || err}`)
2657
3185
  return { ok: false, reason: 'stop-failed', error: err?.message || String(err) }
@@ -2669,13 +3197,14 @@ export class ClaudeByokSession extends BaseSession {
2669
3197
  * completion don't double-emit. Mirrors SdkSession's helper of the same name
2670
3198
  * (minus the task-id map, which byok doesn't have).
2671
3199
  *
3200
+ * #7340: the body is now BaseSession's `_completeAgent` — same guard, same
3201
+ * emit, ONE implementation shared with SdkSession and CliSession. Kept as a
3202
+ * named wrapper because #5274's callers and the cancel path read by this name.
3203
+ *
2672
3204
  * @param {string} toolUseId
2673
3205
  */
2674
3206
  _finalizeAgentByToolUseId(toolUseId) {
2675
- if (typeof toolUseId !== 'string' || !toolUseId) return
2676
- if (!this._activeAgents.has(toolUseId)) return
2677
- this._activeAgents.delete(toolUseId)
2678
- this.emit('agent_completed', { toolUseId })
3207
+ this._completeAgent(toolUseId)
2679
3208
  }
2680
3209
 
2681
3210
  // #5374: no setModel override needed — BaseSession.setModel updates the
@@ -2750,7 +3279,6 @@ export class ClaudeByokSession extends BaseSession {
2750
3279
  // #4080: same-rationale teardown — both maps are bounded by the
2751
3280
  // active stream / outstanding permission count, but any external
2752
3281
  // reference (test capture, future export) would keep them alive.
2753
- this._streamingIndexToToolUseId.clear()
2754
3282
  this._streamingIndexToThinkingId.clear()
2755
3283
  this._thinkingStartMs.clear()
2756
3284
  this._pendingPermissionToolUseIds.clear()