@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
@@ -1,10 +1,17 @@
1
+ import { assistantResponseText, sdkDeclarationEligible } from './assistant-response.js'
1
2
  import { query, forkSession } from '@anthropic-ai/claude-agent-sdk'
2
- import { join } from 'path'
3
- import { homedir } from 'os'
3
+ import { claudeConfigDir } from './utils/claude-config-dir.js'
4
+ import { claudeSettingSourcesFor, projectSettingsAllowedAsync, projectSettingsDecidedWithoutScan } from './claude-setting-sources.js'
4
5
  import { performance } from 'node:perf_hooks'
5
- import { updateModels, saveModelsCache, updateContextWindow, getModels, ALLOWED_MODEL_IDS } from './models.js'
6
+ import { CLAUDE_BINARY_CANDIDATES, resolveClaudeBinary } from './utils/claude-binary.js'
7
+ import { labelBinarySpawnFailure } from './utils/verify-binary.js'
8
+ import { sdkClaudeCodeVersion, CLAUDE_SDK_MIN_CLI_VERSION } from './utils/agent-sdk-version.js'
9
+ import { CLAUDE_SDK_CUSTOMIZATION } from './provider-customization.js'
10
+ import { updateModels, saveModelsCache, updateContextWindow, getModels, getRosterModelRow, ALLOWED_MODEL_IDS } from './models.js'
11
+ import { isWellFormedThinkingLevel, resolveThinkingLevels, LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
12
+ import { effortRoster, annotateSupportedModels } from './claude-model-refresh.js'
6
13
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
7
- import { BaseSession, buildBaseSessionOpts } from './base-session.js'
14
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission, NOT_ADMITTED_ADMISSION } from './base-session.js'
8
15
  import { normalizeSdkModelUsage } from './usage-normalize.js'
9
16
  import { buildContentBlocks } from './content-blocks.js'
10
17
  import { MessageTransformPipeline } from './message-transform.js'
@@ -15,16 +22,50 @@ import {
15
22
  isRunInBackgroundInput,
16
23
  parseBashOutputShellId,
17
24
  } from './background-shells.js'
18
- import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent } from './claude-stream-parser.js'
25
+ import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent, formatStatusContent } from './claude-stream-parser.js'
19
26
  import { createLogger, loggerForSession } from './logger.js'
20
27
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
21
28
  import { formatBytes } from './utils/format-bytes.js'
22
29
  import { formatIdleDuration } from './session-timeout-manager.js'
23
30
  import { detectThinkingKeyword } from './detect-thinking-keyword.js'
24
31
  import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
32
+ import { CLAUDE_LOGIN_COMMAND } from './utils/claude-login-command.js'
33
+ import { buildSpawnEnv } from './utils/spawn-env.js'
34
+ import { classifyAuthCause } from './utils/auth-cause.js'
35
+ import { turnOutcomeField, outcomeFromSdkResult } from './turn-outcome.js'
25
36
 
26
37
  const log = createLogger('sdk')
27
38
 
39
+ /**
40
+ * #8700: the `value` the Agent SDK's `supportedModels()` gives the row for the
41
+ * CLI's own default model — what a session with no model of its own runs. A
42
+ * model alias, unrelated to the thinking level that happens to share the word.
43
+ */
44
+ const SDK_DEFAULT_MODEL_ALIAS = 'default'
45
+
46
+ // #8223: an authentication failure is surfaced with this code so the clients can
47
+ // render a "sign in" card instead of a raw error line. Same wire code claude-tui
48
+ // emits (claude-tui/pty-driver.js AUTH_REQUIRED_CODE) — kept as a local literal
49
+ // because that module resolves the claude binary at import time, which this one
50
+ // must not do.
51
+ const AUTH_REQUIRED_CODE = 'AUTH_REQUIRED'
52
+ // The SDK reads credentials from ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN or a
53
+ // prior `claude auth login`, and nothing at the point of failure says which one
54
+ // this host meant to use — so the message covers both.
55
+ const AUTH_REQUIRED_MESSAGE = `Claude authentication failed on this host. If you use a Claude subscription, run \`${CLAUDE_LOGIN_COMMAND}\` in a terminal on the host; if you use an API key, check ANTHROPIC_API_KEY. Then retry.`
56
+ // A containerised session has no login command to run (see
57
+ // DockerSdkSession.preflight): its credentials are the container's env.
58
+ const AUTH_REQUIRED_CONTAINER_MESSAGE = 'Claude authentication failed inside the session container. Check that ANTHROPIC_API_KEY is set for it, then retry.'
59
+ // #8273: the session authenticates with ANTHROPIC_API_KEY, so a host login is not
60
+ // the fix. Never interpolates the key.
61
+ const AUTH_REQUIRED_API_KEY_MESSAGE = 'Claude authentication failed: the Anthropic API key (ANTHROPIC_API_KEY) was rejected. Check that it is correct and still active, or replace it, then retry.'
62
+ // #8970: the other mechanisms a session can authenticate through. "Log in" is the
63
+ // wrong advice for each of them, and none of these messages carries a value.
64
+ const AUTH_REQUIRED_BEDROCK_MESSAGE = 'Claude authentication failed through Amazon Bedrock (CLAUDE_CODE_USE_BEDROCK is set). Check the AWS credentials, profile and region this host uses, refresh an expired AWS SSO session if you use one, and confirm the Bedrock model is enabled for the account, then retry.'
65
+ const AUTH_REQUIRED_VERTEX_MESSAGE = 'Claude authentication failed through Google Vertex AI (CLAUDE_CODE_USE_VERTEX is set). Check the Google Cloud credentials, project and region this host uses (for example re-run gcloud auth application-default login), and confirm the Claude model is enabled in Vertex AI, then retry.'
66
+ const AUTH_REQUIRED_AUTH_TOKEN_MESSAGE = 'Claude authentication failed: the bearer token (ANTHROPIC_AUTH_TOKEN) was rejected. Check that it is correct, unexpired and accepted by the endpoint it is sent to, then retry.'
67
+ const AUTH_REQUIRED_API_KEY_HELPER_MESSAGE = 'Claude authentication failed: the key returned by the apiKeyHelper in your Claude settings was rejected, or the helper failed to run. Run the helper yourself to check that it prints a valid, current key, then retry.'
68
+
28
69
  /**
29
70
  * Manages a Claude Code session using the Agent SDK.
30
71
  *
@@ -90,18 +131,159 @@ export const STDIN_DROPPED_ESCALATION_EVERY_N = 10
90
131
  // stuck") with noise control.
91
132
  export const REFUSED_SENDMESSAGE_WARN_INTERVAL_MS = 30 * 1000
92
133
 
134
+ // #8300: the text Claude Code writes into a tool_result when IT cancelled the
135
+ // tool call — the turn had no permission/hook channel left — rather than
136
+ // relaying a decision from this session's PermissionManager. A decision made
137
+ // here always reaches the CLI with chroxy's own reason text, so a tool_result
138
+ // that starts with one of these can only mean the control channel was gone
139
+ // (stdin closed under the CLI, or its permission request stream aborted). The
140
+ // second prefix is the Approve-mode spelling (`canUseTool` could not be asked:
141
+ // "Tool permission request failed: AbortError: Stream closed"). Matched by
142
+ // prefix; the CLI appends nothing stable after the sentence.
143
+ export const SDK_TOOL_CANCELLED_PREFIXES = [
144
+ "The user doesn't want to take this action right now.",
145
+ 'Tool permission request failed:',
146
+ ]
147
+
148
+ // #8936: the sentences Claude Code writes into the error tool_result of a tool
149
+ // that was refused. They address the model ("STOP what you are doing and wait
150
+ // for the user to tell you how to proceed"), so they are never shown to the
151
+ // user. A refusal this session decided is recognised by its tool_use id, not by
152
+ // this wording (the CLI has several spellings and changes them); the prefixes
153
+ // are only the fallback for a refusal block with no decision on record, and the
154
+ // check that makes an unexpected spelling visible in the log.
155
+ export const SDK_TOOL_REJECTED_PREFIXES = [
156
+ "The user doesn't want to proceed with this tool use.",
157
+ 'Permission for this tool use was denied.',
158
+ 'Permission for this action has been denied.',
159
+ ]
160
+
161
+ // Shown when a refusal is recognised but no decision of this session carries a
162
+ // sentence of its own (a refusal the CLI made from its own settings).
163
+ export const SDK_DENIED_FALLBACK_TEXT = 'Tool use was denied.'
164
+
165
+ /**
166
+ * #8936: is this tool_result text one of Claude Code's model-facing refusals?
167
+ * @param {unknown} text
168
+ * @returns {boolean}
169
+ */
170
+ export function isSdkToolRejectionText(text) {
171
+ if (typeof text !== 'string') return false
172
+ const trimmed = text.trimStart()
173
+ return SDK_TOOL_REJECTED_PREFIXES.some((prefix) => trimmed.startsWith(prefix))
174
+ }
175
+
176
+ /**
177
+ * #8300: does this tool_result text mean Claude Code cancelled the tool call
178
+ * itself, without consulting chroxy's permission pipeline?
179
+ * @param {unknown} text
180
+ * @returns {boolean}
181
+ */
182
+ export function isSdkToolCancellationText(text) {
183
+ if (typeof text !== 'string') return false
184
+ const trimmed = text.trimStart()
185
+ return SDK_TOOL_CANCELLED_PREFIXES.some((prefix) => trimmed.startsWith(prefix))
186
+ }
187
+
188
+ /**
189
+ * #7376: did the Claude CLI process die under the query (a crash or an external
190
+ * kill) rather than the query ending on its own? Distinct from
191
+ * {@link isQueryCloseError}, which is a DELIBERATE close.
192
+ * @param {unknown} err
193
+ * @returns {boolean}
194
+ */
195
+ export function isProcessExitError(err) {
196
+ if (!err) return false
197
+ const text = typeof err.message === 'string' ? err.message : String(err)
198
+ // The SDK transport's two shapes for a CLI process that died under the query
199
+ // (sdk.mjs: `Claude Code process exited with code ${code}` and
200
+ // `Claude Code process terminated by signal ${signal}`), ANCHORED to the start
201
+ // of the message so an unrelated error that merely mentions a subprocess
202
+ // exiting ("subprocess exited with code 1", "the Claude Code process exited
203
+ // with code 1 in the hook") is not read as the CLI dying. A CLI that exits 1
204
+ // on an API or auth failure is still a process exit, and is labelled one.
205
+ return /^Claude Code process (?:exited with code -?\d+|terminated by signal SIG[A-Z0-9]+)\b/.test(text)
206
+ }
207
+
208
+ /**
209
+ * #8300: is this the error the SDK's generator throws after the session
210
+ * itself closed the query (`Query.close()` aborts the transport and kills the
211
+ * CLI)? Only these are swallowed after a deliberate close; anything else is
212
+ * still a turn failure and is surfaced.
213
+ * @param {unknown} err
214
+ * @returns {boolean}
215
+ */
216
+ function isQueryCloseError(err) {
217
+ if (!err) return false
218
+ if (err.name === 'AbortError') return true
219
+ const text = typeof err.message === 'string' ? err.message : String(err)
220
+ // The SDK's own shapes for a close: "… aborted …" from the abort controller,
221
+ // and the transport's "terminated by signal SIGTERM/SIGKILL" from the kill
222
+ // close() sends. A nonzero "process exited with code N" is a crash, never a
223
+ // close, and stays surfaced even after a deliberate close.
224
+ return /\baborted?\b|terminated by signal SIG(TERM|KILL)\b/i.test(text)
225
+ }
226
+
227
+ /**
228
+ * #8300/#8302: is this a `task_updated` `patch.status` that closes the task?
229
+ * One predicate for the two sites that care (the live roster and the shell
230
+ * tracker), so they cannot disagree about which statuses are terminal.
231
+ * @param {unknown} status
232
+ * @returns {boolean}
233
+ */
234
+ function isTerminalTaskStatus(status) {
235
+ return status === 'completed' || status === 'failed' || status === 'killed'
236
+ }
237
+
238
+ /**
239
+ * Flatten a tool_result block's content to its text, the same way
240
+ * `emitToolResults` (tool-result.js) does, so a pattern match over the text
241
+ * sees the same string whether the CLI sent a string or a block array.
242
+ * @param {object} block - a `tool_result` content block
243
+ * @returns {string}
244
+ */
245
+ function toolResultText(block) {
246
+ if (typeof block?.content === 'string') return block.content
247
+ if (Array.isArray(block?.content)) {
248
+ return block.content
249
+ .filter((b) => b?.type === 'text')
250
+ .map((b) => b.text)
251
+ .join('\n')
252
+ }
253
+ return ''
254
+ }
255
+
93
256
  export class SdkSession extends BaseSession {
257
+ static canonicalAssistantResponses = true
258
+ static declarationTurnOwnership = true
259
+
94
260
  // #5858: marks this as a Claude-family provider — the single source of truth
95
261
  // for `isClaudeProvider()` (drives the createSession soft-fallback for stale
96
262
  // model ids + the shared models registry). Docker subclasses inherit it.
97
263
  static claudeFamily = true
98
264
 
265
+ static get customizationDescriptor() {
266
+ return CLAUDE_SDK_CUSTOMIZATION
267
+ }
268
+
99
269
  // #6769: cap on how long the end-of-turn getContextUsage() control request
100
270
  // may delay the `result` broadcast. The CLI answers in milliseconds when
101
271
  // alive; the cap only bites when the process is already shutting down —
102
272
  // in which case the snapshot is skipped and the result emits without it.
103
273
  static CONTEXT_USAGE_SNAPSHOT_TIMEOUT_MS = 2000
104
274
 
275
+ // #8300: how long a zero-turn `result` is held before it is taken as the
276
+ // prompt's own. On `--resume`, Claude Code first replays an orphaned
277
+ // background task (a shell or subagent that was still running when the
278
+ // previous turn's process exited) as its own zero-cost turn: `init` →
279
+ // `result` with `num_turns: 0` → a second `init` for the real prompt, about
280
+ // 20–80 ms later. That first result must not end the turn (ending the input
281
+ // there is exactly the lost-channel bug). A real prompt that produces no
282
+ // assistant turn is the other reading of the same message, and the CLI then
283
+ // just waits on stdin — so the held result is confirmed by the next `init`
284
+ // or, failing that, taken as the real one when this window elapses.
285
+ static ORPHAN_NOTICE_CONFIRM_MS = 2000
286
+
105
287
  /**
106
288
  * Human-readable label shown in the startup banner and anywhere else the
107
289
  * server needs to name this provider (#2953). Each provider owns its own
@@ -119,13 +301,18 @@ export class SdkSession extends BaseSession {
119
301
  * hardcoding the path.
120
302
  */
121
303
  static get dataDir() {
122
- return join(homedir(), '.claude')
304
+ return claudeConfigDir()
123
305
  }
124
306
 
125
307
  static get capabilities() {
126
308
  return {
127
309
  permissions: true,
128
310
  inProcessPermissions: true,
311
+ // #7825: Auto installs an SDK PreToolUse callback that routes every tool
312
+ // through PermissionManager. Benign calls short-circuit immediately;
313
+ // protected paths reach the shared interactive floor.
314
+ permissionFloor: true,
315
+ autoPermissionMode: true,
129
316
  modelSwitch: true,
130
317
  permissionModeSwitch: true,
131
318
  // #5609: SDK applies a mid-turn switch to 'auto' in-process (clears
@@ -133,10 +320,35 @@ export class SdkSession extends BaseSession {
133
320
  // killing the turn. Declared false so the capability matrix is uniform —
134
321
  // CliSession is the only provider where the auto-switch is destructive.
135
322
  interruptsTurnOnAutoSwitch: false,
136
- planMode: false,
323
+ // #8153: was `false` since the provider adapter's introduction (#583),
324
+ // stale even then — `_sdkPermissionMode()` has always passed `'plan'`
325
+ // straight through as the SDK's own native `PermissionMode`, which
326
+ // query() forwards as a literal `--permission-mode plan` flag to the
327
+ // same `claude` CLI binary CliSession spawns (query() execs
328
+ // `pathToClaudeCodeExecutable`, #7986) — same binary, same read-only
329
+ // enforcement, same EnterPlanMode/ExitPlanMode tool-use protocol. The
330
+ // only missing piece was event wiring (now added in
331
+ // _handleToolUseBlock + the 'result' case in _callQuery), not a
332
+ // structural gap, so the capability is now `true` to match reality.
333
+ planMode: true,
137
334
  resume: true,
138
335
  terminal: false,
139
336
  thinkingLevel: true,
337
+ // #8700: true where `thinking_level_changed` carries `effective`, the
338
+ // level the provider REPORTS it applied. SdkSession reads it from Claude
339
+ // Code (`get_settings` → `applied.effort`) at the start of every turn; a
340
+ // client shows it beside the picker, or "unknown" while it is null.
341
+ // Every other provider declares false: no report, so no readout.
342
+ thinkingLevelEffective: true,
343
+ // #7725: true ONLY where the SERVER escalates on the magic keywords
344
+ // ("think" / "think hard" / "ultrathink" …). SdkSession is the sole
345
+ // importer of detect-thinking-keyword.js — it maps a detected keyword to
346
+ // a per-turn maxThinkingTokens budget in _callQuery. Every other provider
347
+ // declares false: the keyword is just prose to them, so a client that
348
+ // highlighted it there would promise an escalation that never happens.
349
+ // Separate from `thinkingLevel` on purpose — a provider can accept a
350
+ // reasoning-effort dropdown without honouring the Claude-only keywords.
351
+ thinkingKeywords: true,
140
352
  // #3932: explicit `streaming` so the capability matrix is uniform across
141
353
  // providers — claude-tui sets this to false (deliver-on-complete), all
142
354
  // others stream incremental deltas via stream_delta during a turn.
@@ -162,6 +374,13 @@ export class SdkSession extends BaseSession {
162
374
  // DockerSdkSession overrides this to false — see the instance-level
163
375
  // `supportsConversationFork` getter (transcript lives in-container).
164
376
  conversationFork: true,
377
+ // #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
378
+ // idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
379
+ // cleared by `interrupt()`), and reports admission through
380
+ // `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
381
+ // can travel it as an ordinary user turn. session-wake.js gates on this with
382
+ // strict `=== true`; absent means NOT supported. Never duck-typed.
383
+ daemonTurnInput: true,
165
384
  }
166
385
  }
167
386
 
@@ -177,10 +396,35 @@ export class SdkSession extends BaseSession {
177
396
  * are session-lifetime so a fresh emit on the next drop re-publishes
178
397
  * the running total.
179
398
  *
399
+ * #7346: `tool_input_delta` delivers the SANITIZED full tool input as
400
+ * a single chunk from `_handleToolUseBlock`, once the full
401
+ * assistant-message `block.input` is known — mirroring
402
+ * byok-session.js's wire shape/client handler exactly. Per #8135
403
+ * (review), this does NOT stream raw per-chunk `input_json_delta`
404
+ * partials the way BYOK does — the Agent SDK's `stream_event` does
405
+ * carry those (same `includePartialMessages: true` config CliSession
406
+ * reads), but a secret can straddle chunk boundaries and mid-stream
407
+ * partial JSON can't be run through the sanitizer, so this only ever
408
+ * emits once, already-safe. Listing it here is what makes
409
+ * `session-manager.js`'s `_wireSessionEvents` bridge the emit onto the
410
+ * `session_event` channel at all.
411
+ *
180
412
  * @returns {string[]}
181
413
  */
182
414
  static get customEvents() {
183
- return ['stdin_dropped_totals']
415
+ return ['stdin_dropped_totals', 'tool_input_delta']
416
+ }
417
+
418
+ /**
419
+ * #8301: with stdin forwarding latched off, `sendMessage` emits a
420
+ * user-visible `stdin_disabled` error AND silently discards the user's own
421
+ * queued follow-ups (`clearOutgoingQueue({ emit: false })`). A daemon wake
422
+ * must not trigger either.
423
+ *
424
+ * @returns {string|null}
425
+ */
426
+ daemonTurnRefusal() {
427
+ return this._stdinForwardingDisabled ? 'stdin-disabled' : null
184
428
  }
185
429
 
186
430
  /**
@@ -193,11 +437,47 @@ export class SdkSession extends BaseSession {
193
437
  return true
194
438
  }
195
439
 
440
+ /**
441
+ * #7986 — the exact path `query()` will spawn via `pathToClaudeCodeExecutable`
442
+ * (see the per-turn options builder below). Preflight prefers this over a
443
+ * fresh candidate resolve when a provider exposes it (#6708 defect #3), so
444
+ * the existence/quarantine/provenance/version gates and the real spawn can
445
+ * never diverge onto different binaries. Re-resolves fresh on every access —
446
+ * NOT a frozen module-load const — so a `claude update` after daemon start
447
+ * is picked up on the next session-create.
448
+ */
449
+ static get resolvedBinary() {
450
+ return resolveClaudeBinary()
451
+ }
452
+
196
453
  /**
197
454
  * Preflight dependency spec used by `chroxy doctor`.
198
- * SDK mode spawns the `claude` binary under the hood, so the same
199
- * binary check applies. Credentials can come from ANTHROPIC_API_KEY,
200
- * CLAUDE_CODE_OAUTH_TOKEN, or a prior `claude login` subscription.
455
+ *
456
+ * SDK mode spawns the user's INSTALLED `claude` binary under the hood via
457
+ * `pathToClaudeCodeExecutable` (#7986) — the desktop bundle does not ship
458
+ * the Agent SDK's own platform binary, and `query()` throws if neither is
459
+ * available. So the same binary check every other claude-family provider
460
+ * runs applies here too, using the shared candidate list.
461
+ *
462
+ * Version floor is a HYBRID, hard-min + soft-advisory pair (#8031),
463
+ * replacing the single hard `minVersion` derived straight from the
464
+ * installed SDK's `claudeCodeVersion` field that #7986 originally shipped.
465
+ * That field is the `claude` CLI build the SDK release was *published
466
+ * alongside* — a pairing, not a genuine minimum — and the CLI's patch
467
+ * number is its release counter, so every SDK bump instantly hard-blocked
468
+ * any `claude` on a release channel that hadn't also updated yet (e.g. npm
469
+ * `stable`, which trails `latest`). Now:
470
+ * - `minVersion: CLAUDE_SDK_MIN_CLI_VERSION` — a small, hand-raised,
471
+ * deliberately-conservative constant — is the HARD floor: below it,
472
+ * preflight still throws `ProviderBinaryVersionError` exactly as before.
473
+ * - `recommendedVersion: () => sdkClaudeCodeVersion()` — the SDK's own
474
+ * pairing — is a SOFT floor: below it (but at/above the hard floor),
475
+ * preflight logs a warning and returns an advisory instead of blocking.
476
+ * A `claude` older than what this SDK build was tested against still gets
477
+ * a `claude update` remediation either way — just a throw below the hard
478
+ * floor, an advisory otherwise. Credentials can come from
479
+ * ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN, or a prior `claude login`
480
+ * subscription.
201
481
  */
202
482
  static get preflight() {
203
483
  return {
@@ -205,15 +485,22 @@ export class SdkSession extends BaseSession {
205
485
  binary: {
206
486
  name: 'claude',
207
487
  args: ['--version'],
208
- candidates: [
209
- '/opt/homebrew/bin/claude',
210
- '/usr/local/bin/claude',
211
- ],
212
- installHint: 'install Claude Code CLI (required by the Agent SDK)',
488
+ candidates: CLAUDE_BINARY_CANDIDATES,
489
+ minVersion: CLAUDE_SDK_MIN_CLI_VERSION,
490
+ recommendedVersion: () => sdkClaudeCodeVersion(),
491
+ // #7986 review S2: the Agent SDK spawns `pathToClaudeCodeExecutable`
492
+ // directly via `child_process.spawn`, no shell — a Windows npm shim
493
+ // (`claude.cmd`/`claude.bat`) can never actually run under that. This
494
+ // makes the refusal explicit and unconditional (see isShellShim +
495
+ // ProviderBinaryUnsupportedError in utils/preflight.js) instead of
496
+ // relying on it falling out of the version probe's EINVAL.
497
+ requiresDirectExec: true,
498
+ installHint: 'install Claude Code, or run `claude update` if it is installed — the SDK provider runs your installed claude',
499
+ updateHint: 'run `claude update`',
213
500
  },
214
501
  credentials: {
215
502
  envVars: ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'],
216
- hint: 'run `claude login` or set ANTHROPIC_API_KEY',
503
+ hint: `run \`${CLAUDE_LOGIN_COMMAND}\` or set ANTHROPIC_API_KEY`,
217
504
  optional: true,
218
505
  },
219
506
  }
@@ -235,6 +522,11 @@ export class SdkSession extends BaseSession {
235
522
  const credSpec = this.preflight.credentials
236
523
  const envVars = credSpec.envVars
237
524
  const hint = credSpec.hint || `set ${envVars.join(' or ')}`
525
+ // Built once rather than as a template nested inside the `detail` template below:
526
+ // scripts/lint-session-opt-forwarding.mjs finds class bodies with a bracket matcher
527
+ // that does not understand a template nested in a `${}`, and one went blind to this
528
+ // class (the session-subclass count dropped from 11 to 10) while that was written.
529
+ const fallbackHint = `run \`${CLAUDE_LOGIN_COMMAND}\` or set ANTHROPIC_API_KEY`
238
530
  // Era read at call time so a long-running daemon flips OAuth/credit-pool
239
531
  // copy at the 2026-06-15 boundary without a restart (#5629).
240
532
  const era = isProgrammaticCreditEra()
@@ -292,8 +584,8 @@ export class SdkSession extends BaseSession {
292
584
  source: 'none',
293
585
  envVar: null,
294
586
  envVars,
295
- hint: hint || 'run `claude login` or set ANTHROPIC_API_KEY',
296
- detail: `Not configured — ${hint || 'run \`claude login\` or set ANTHROPIC_API_KEY'}`,
587
+ hint: hint || fallbackHint,
588
+ detail: `Not configured — ${hint || fallbackHint}`,
297
589
  // Unconfigured: default to the era-gated credit-pool class (this is the
298
590
  // claude-sdk default auth path once configured via `claude login`).
299
591
  billingClass: era ? BILLING_CLASSES.PROGRAMMATIC_CREDIT : BILLING_CLASSES.SUBSCRIPTION,
@@ -327,7 +619,12 @@ export class SdkSession extends BaseSession {
327
619
  return claudeModelMetadata(modelId)
328
620
  }
329
621
 
330
- /** Token budgets for thinking levels. null = adaptive (SDK default). */
622
+ /**
623
+ * Token budgets for the legacy levels, for the models that predate Claude
624
+ * Code's effort setting and read only `maxThinkingTokens` (#8700: adaptive
625
+ * models ignore a budget, so a level goes to them as `effort` instead — see
626
+ * `_thinkingOptions`). null = adaptive (SDK default).
627
+ */
331
628
  static THINKING_BUDGETS = { default: null, high: 32000, max: 128000 }
332
629
 
333
630
  /** Error patterns mapped to user-friendly messages. */
@@ -336,8 +633,20 @@ export class SdkSession extends BaseSession {
336
633
  msg: 'Insufficient API credits or billing limit reached. Check your API provider dashboard.' },
337
634
  { test: /rate.limit|too many requests|429/i,
338
635
  msg: 'API rate limit exceeded. Please wait a moment and try again.' },
339
- { test: /authentication|invalid.api.key|401|unauthorized/i,
340
- msg: 'API authentication failed. Check your API key configuration.' },
636
+ // #8223: carries `code: AUTH_REQUIRED`; `msg` is only the fallback — a session
637
+ // swaps in its own host/container wording via `_authRequiredMessage()`.
638
+ // `failed to authenticate` and `oauth session|token … expired|revoked|invalid`
639
+ // are the OAuth-login wording ("Failed to authenticate: OAuth session expired
640
+ // and could not be refreshed"), which the pre-existing alternatives missed.
641
+ // `401` and `unauthorized` are bound, because a match now yields a no-retry
642
+ // sign-in card and these tokens turn up in unrelated text: a hex id
643
+ // (`container 7f3a4018c9e2…`), a request id (`req_011CTx401Qabc`), a port
644
+ // (`127.0.0.1:4010`) and a version path (`versions/2.1.401/claude`). The `401`
645
+ // bound is a lookaround rather than `\b401\b`, since `\b` still matches inside
646
+ // `2.1.401/`: not after a word char or `.`, not before a word char or `.digit`.
647
+ { test: /authentication|invalid.api.key|(?<![\w.])401(?!\w|\.\d)|\bunauthorized\b|failed to authenticate|oauth (?:session|token)\b[^.\n]{0,80}\b(?:expired|revoked|invalid)/i,
648
+ msg: AUTH_REQUIRED_MESSAGE,
649
+ code: AUTH_REQUIRED_CODE },
341
650
  { test: /overloaded|503|529|temporarily unavailable/i,
342
651
  msg: 'The API is temporarily overloaded. Please try again in a few minutes.' },
343
652
  { test: /SIGABRT|SIGKILL|SIGSEGV|terminated by signal/i,
@@ -345,25 +654,104 @@ export class SdkSession extends BaseSession {
345
654
  ]
346
655
 
347
656
  static _enrichErrorMessage(raw) {
348
- if (!raw) return 'Unknown error'
349
- for (const { test, msg } of SdkSession._ERROR_PATTERNS) {
350
- if (test.test(raw)) return msg
657
+ return SdkSession._classifyError(raw).message
658
+ }
659
+
660
+ /**
661
+ * #8223: `_enrichErrorMessage` plus the row's `code`, when it has one. First
662
+ * matching row wins, exactly as before, so a message that reads as a billing or
663
+ * rate-limit failure is never reclassified as an auth one.
664
+ * @returns {{ message: string, code?: string }}
665
+ */
666
+ static _classifyError(raw) {
667
+ if (!raw) return { message: 'Unknown error' }
668
+ for (const { test, msg, code } of SdkSession._ERROR_PATTERNS) {
669
+ if (test.test(raw)) return code ? { message: msg, code } : { message: msg }
670
+ }
671
+ return { message: raw }
672
+ }
673
+
674
+ /**
675
+ * #8273 / #8970: which credential this session authenticates with, so the
676
+ * clients can name the real remedy. See `classifyAuthCause` for the precedence
677
+ * (container, Bedrock, Vertex, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY,
678
+ * apiKeyHelper, then a host login). `undefined` (field omitted): only
679
+ * CLAUDE_CODE_OAUTH_TOKEN is set, where the source is ambiguous and the
680
+ * combined message is kept.
681
+ * @returns {import('@chroxy/protocol').AuthRequiredCause | undefined}
682
+ */
683
+ _authCause() {
684
+ return classifyAuthCause(buildSpawnEnv('claude-sdk'), {
685
+ containerized: !!this.constructor.capabilities?.containerized,
686
+ })
687
+ }
688
+
689
+ /** #8223: the AUTH_REQUIRED text for THIS session — mechanism-aware. */
690
+ _authRequiredMessage(authCause = this._authCause()) {
691
+ switch (authCause) {
692
+ case 'container': return AUTH_REQUIRED_CONTAINER_MESSAGE
693
+ case 'api_key': return AUTH_REQUIRED_API_KEY_MESSAGE
694
+ case 'bedrock': return AUTH_REQUIRED_BEDROCK_MESSAGE
695
+ case 'vertex': return AUTH_REQUIRED_VERTEX_MESSAGE
696
+ case 'auth_token': return AUTH_REQUIRED_AUTH_TOKEN_MESSAGE
697
+ case 'api_key_helper': return AUTH_REQUIRED_API_KEY_HELPER_MESSAGE
698
+ default: return AUTH_REQUIRED_MESSAGE
699
+ }
700
+ }
701
+
702
+ /** #8273: the `error` event payload for an auth failure on THIS session. */
703
+ _authRequiredPayload() {
704
+ const authCause = this._authCause()
705
+ return {
706
+ code: AUTH_REQUIRED_CODE,
707
+ message: this._authRequiredMessage(authCause),
708
+ ...(authCause ? { authCause } : {}),
351
709
  }
352
- return raw
353
710
  }
354
711
 
355
712
  get thinkingLevel() { return this._thinkingLevel }
356
713
 
714
+ /**
715
+ * #8700 — the effort Claude Code reported it applied (`get_settings` →
716
+ * `applied.effort`), read at the start of each turn. null until it reports,
717
+ * and reset to null by a model or level change the running turn has not
718
+ * reported on yet. Put on the wire by `buildThinkingLevelChanged`.
719
+ */
720
+ get effectiveThinkingLevel() { return this._effectiveEffort }
721
+
722
+ /**
723
+ * #8700 — the one-line `model= requested= effective=` summary an operator
724
+ * reads in the daemon log before a send. Both log sites (the
725
+ * `set_thinking_level` handler and session-manager, for a change the session
726
+ * made itself) print this, so the line has one format.
727
+ */
728
+ describeThinkingLevel() {
729
+ const model = this._effectiveModel || this.model || this.bootedModel || 'default'
730
+ const requested = this._thinkingLevel || LEGACY_DEFAULT_THINKING_LEVEL
731
+ return `model=${model} requested=${requested} effective=${this._effectiveEffort || 'unknown'}`
732
+ }
733
+
357
734
  constructor(opts = {}) {
358
735
  super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-sdk' }))
359
736
  // SdkSession-local opts (not BaseSession opts — see buildBaseSessionOpts).
360
737
  const { resumeSessionId, transforms, maxToolInput, sandbox, stdinForwardingDisabled } = opts
738
+ // #8030 / #8035: per-spawn re-verification gate. Stored by BaseSession's
739
+ // constructor as `this._spawnPreflight` (see base-session.js's ctor param
740
+ // doc and `_gatedSpawnBinary`) — moved there so JsonlSubprocessSession's
741
+ // picker subclasses (Gemini/Codex-exec) inherit the same wiring instead of
742
+ // this middle layer reading `opts.spawnPreflight` on its own and silently
743
+ // dropping it for every subclass that forwards opts via the picker.
361
744
  this._maxToolInput = maxToolInput || DEFAULT_MAX_TOOL_INPUT_LENGTH
362
745
  this._transformPipeline = new MessageTransformPipeline(transforms || [])
363
746
  this._sandbox = sandbox || null
364
747
 
365
748
  this._sdkSessionId = resumeSessionId || null
366
749
  this._sessionId = null
750
+ // #8153: plan-mode bookkeeping, mirroring CliSession's _inPlanMode /
751
+ // _planAllowedPrompts (see _handleToolUseBlock + the 'result' case in
752
+ // _callQuery, and _clearMessageState's stale-flag reset).
753
+ this._inPlanMode = false
754
+ this._planAllowedPrompts = null
367
755
  // #4828: session-scoped logger, lazily bound on the SDK's first `init`
368
756
  // message (where session_id becomes known). Pre-init log lines stay on
369
757
  // the module-level `log` — same fallback pattern as ClaudeTuiSession.
@@ -372,7 +760,30 @@ export class SdkSession extends BaseSession {
372
760
  // lifetime; the binding stays valid until destroy() drops the instance.
373
761
  this._log = null
374
762
  this._query = null
763
+ // #8321: the turn whose query() generator is still being consumed, from the
764
+ // moment the query is created until its loop's `finally`. Busy state ends at
765
+ // the prompt's `result`, which is BEFORE the generator does (the CLI exits
766
+ // only once stdin closes), so `_isBusy` alone does not say whether a query
767
+ // is alive. `{ query, waitTimer, forceTimer }`, or null.
768
+ this._drainingTurn = null
375
769
  this._thinkingLevel = null
770
+ // #8700: what Claude Code last reported it applied (see
771
+ // `effectiveThinkingLevel`), the model it reported with it, the last
772
+ // report announced (so an unchanged report each turn stays quiet), and an
773
+ // epoch `_forgetEffortReport` bumps so a report still in flight across a
774
+ // model or level change is dropped.
775
+ this._effectiveEffort = null
776
+ this._effectiveModel = null
777
+ this._lastEffortReport = null
778
+ this._effortEpoch = 0
779
+ // Read order is independent of setting epochs: init can read while a live
780
+ // setter is pending, then that setter reads again within the same epoch.
781
+ this._effortReadSeq = 0
782
+ // #8700: the SDK's own per-model effort answer from `supportedModels()`,
783
+ // keyed by the row's `value` and its `resolvedModel`: 'effort' for a model
784
+ // that takes Claude Code's effort, 'budget' for one that still reads only
785
+ // `maxThinkingTokens`. Absent = this session has not heard.
786
+ this._modelEffortSupport = new Map()
376
787
 
377
788
  // #6766: last SDK transcript message UUID seen this session. Captured from
378
789
  // each full `assistant` message in the query loop and used as the fork
@@ -395,6 +806,20 @@ export class SdkSession extends BaseSession {
395
806
  // destroy().
396
807
  this._taskIdByToolUseId = new Map()
397
808
 
809
+ // #8300: tasks the CLI reported with `task_started` and has not yet closed
810
+ // with `task_notification`, keyed by the SDK `task_id`. Read at the
811
+ // prompt's own `result`: a task still here then would outlive the turn's
812
+ // process, and the SDK provider cannot service it past the turn (its tool
813
+ // calls would be cancelled, see SDK_TOOL_CANCELLED_PREFIXES), so the turn
814
+ // end stops it and says so. Turn-local: cleared alongside
815
+ // `_taskIdByToolUseId` at the start of each turn.
816
+ this._liveBackgroundTasks = new Map()
817
+
818
+ // #8300: the current turn's streaming input handle (`_createTurnInput`),
819
+ // so destroy() can release the CLI's stdin without waiting for the
820
+ // message loop to observe `_destroying`. Null between turns.
821
+ this._turnInput = null
822
+
398
823
  // Permission handling — delegated to PermissionManager. The pause/resume
399
824
  // hooks keep the inactivity timer suspended while a permission is pending:
400
825
  // waiting on user input is NOT inactivity, and without this a session with
@@ -406,6 +831,16 @@ export class SdkSession extends BaseSession {
406
831
  // #6771 — pass the durable rule store so an `allowAlways` decision persists
407
832
  // a project-scoped rule and this session seeds from prior grants for its cwd.
408
833
  this._permissions = new PermissionManager({ log, cwd: this.cwd, ruleStore: this._permissionRuleStore })
834
+ // #8430: a prompt the user's Stop resolved -- including one raised between the
835
+ // Stop and the abort, which the snapshot in `interrupt()` could not see -- marks
836
+ // its tool row stopped. Driven by the `stopped` resolution itself -- the manager
837
+ // attaches `sourceToolUseId` to that resolution only -- so a Deny, a timeout or a
838
+ // rule decision made in the same window keeps its own row.
839
+ this._permissions.on('permission_resolved', (d) => {
840
+ if (typeof d?.sourceToolUseId !== 'string') return
841
+ this._stopCancelledToolUseIds.add(d.sourceToolUseId)
842
+ this._stopResolvedToolUseIds.add(d.sourceToolUseId)
843
+ })
409
844
  wirePermissionManager(this, this._permissions, {
410
845
  onRequest: () => this._pauseResultTimeoutForPermission(),
411
846
  onResolved: () => this._resumeResultTimeoutForPermission(),
@@ -447,6 +882,26 @@ export class SdkSession extends BaseSession {
447
882
  // client UI feedback is unaffected.
448
883
  this._lastRefusedWarnTs = 0
449
884
 
885
+ // #8363: tool_use ids whose permission prompt is awaiting a decision right
886
+ // now (added when the provider asks, dropped when it settles), and the subset
887
+ // that was still waiting when Stop was pressed. Stopping a turn makes the SDK
888
+ // resolve a pending prompt as a denial and write ITS OWN tool_result, whose
889
+ // text says the user did not want to proceed -- but nobody refused anything.
890
+ // The tool_result path (`_terminatedReasonForToolResult`) uses the second set
891
+ // to tag that result as a Stop. A decision the user actually gave never joins
892
+ // it: it leaves `_pendingPermissionToolUseIds` first.
893
+ this._pendingPermissionToolUseIds = new Set()
894
+ this._stopCancelledToolUseIds = new Set()
895
+ // #8430: the subset of those that a Stop-caused RESOLUTION confirmed. The
896
+ // snapshot in `interrupt()` marks a prompt provisionally (the provider can
897
+ // write its own denial before this session's resolution runs); a decision that
898
+ // lands first -- a Deny, a timeout -- is not confirmed and takes the mark off.
899
+ this._stopResolvedToolUseIds = new Set()
900
+ // #8936: the user-facing sentence of each denial this session decided
901
+ // (tool_use id -> PermissionManager's message), read once by the
902
+ // tool_result path to replace the provider's model-facing refusal text.
903
+ this._deniedToolMessages = new Map()
904
+
450
905
  // #4881: provider parity with CliSession's #4602 _intentionalStop flag.
451
906
  // Set by `interrupt()` immediately before aborting the active SDK query
452
907
  // generator, then consumed inside `_callQuery`'s try/catch/finally so a
@@ -614,15 +1069,29 @@ export class SdkSession extends BaseSession {
614
1069
  message: 'Cannot send message — stdin forwarding is disabled; restart this session',
615
1070
  recoverable: false,
616
1071
  })
1072
+ reportInputAdmission(sendOptions, {
1073
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1074
+ reason: 'stdin_disabled', message: 'The provider input channel is disabled; restart the session before retrying.',
1075
+ })
617
1076
  return
618
1077
  }
619
1078
 
620
- if (this._isBusy) {
1079
+ // #8321: a previous turn's query may still be draining after its result
1080
+ // cleared busy. A follow-up then waits in the same outgoing queue and is
1081
+ // flushed by that turn's `finally`, so one query() runs at a time.
1082
+ if (this._isBusy || this._drainingTurn) {
621
1083
  // #5936 (epic #5935): a send-while-busy follow-up goes into the shared
622
1084
  // outgoing queue (BaseSession) — flushed FIFO on the next `result`. The
623
1085
  // overflow cap + the `message_queued` mirror event live in
624
1086
  // enqueueOutgoingMessage; nothing to do here but enqueue and return.
625
- this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
1087
+ const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
1088
+ if (queued && !this._isBusy) this._armDrainRelease()
1089
+ reportInputAdmission(sendOptions, queued
1090
+ ? { status: 'queued', delivery: 'queued' }
1091
+ : {
1092
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1093
+ reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
1094
+ })
626
1095
  return
627
1096
  }
628
1097
 
@@ -638,12 +1107,65 @@ export class SdkSession extends BaseSession {
638
1107
  }
639
1108
 
640
1109
  this._isBusy = true
1110
+ // The project-settings decision for this turn, taken before any query state is
1111
+ // set up. A folder with no trust record is decided at once; a trusted one is
1112
+ // verified by a fresh scan in a worker thread (busy is already set, so a
1113
+ // follow-up queues meanwhile).
1114
+ let projectAllowed = projectSettingsDecidedWithoutScan(this.cwd)
1115
+ if (projectAllowed === null) {
1116
+ // interrupt() clears the token, which is how a Stop during the verification is seen.
1117
+ const decisionToken = {}
1118
+ this._pendingDecision = decisionToken
1119
+ projectAllowed = await projectSettingsAllowedAsync(this.cwd)
1120
+ const stopped = this._pendingDecision !== decisionToken
1121
+ if (!stopped) this._pendingDecision = null
1122
+ if (stopped && !this._destroying) {
1123
+ // Stopped before the query started: the turn does not run.
1124
+ this._isBusy = false
1125
+ this._permissions.clearUserStopInFlight()
1126
+ this.emit('stopped', { stopRequested: true }) // #9241
1127
+ // A send that arrived during the verification was queued: deliver it now, as the
1128
+ // end of a stopped turn does.
1129
+ if (this._outgoingQueue.length) this.dequeueNextOutgoing()
1130
+ return
1131
+ }
1132
+ }
1133
+ if (this._destroying) {
1134
+ this._isBusy = false
1135
+ return
1136
+ }
1137
+ // #9242: the verification above is an await; re-ask admission before any turn state
1138
+ // or the query exists. Refused: no dispatch; follow-ups that queued meanwhile go on.
1139
+ if (!this._admitPreparedSend(sendOptions)) {
1140
+ this._isBusy = false
1141
+ this._permissions.clearUserStopInFlight()
1142
+ reportInputAdmission(sendOptions, NOT_ADMITTED_ADMISSION)
1143
+ if (this._outgoingQueue.length) this.dequeueNextOutgoing()
1144
+ return
1145
+ }
1146
+ // #7376: a turn starts with no Stop requested, whatever the last one did.
1147
+ this._stopRequestedThisTurn = false
1148
+ this._stopCancelledToolUseIds.clear() // #8363
1149
+ this._stopResolvedToolUseIds.clear() // #8430
1150
+ this._deniedToolMessages.clear() // #8936
1151
+ // #8430: ...and with no user Stop in flight, whatever the last turn left (a
1152
+ // turn superseded before its teardown never reaches `_clearMessageState`).
1153
+ this._permissions.clearUserStopInFlight()
1154
+ // #8300: a per-session monotonic turn token. `supersededByNewerTurn`
1155
+ // compares against it: unlike a handle comparison it never reverts once
1156
+ // a follow-up turn has started and ended.
1157
+ this._turnSeq = (this._turnSeq || 0) + 1
1158
+ const turnSeq = this._turnSeq
641
1159
  this._messageCounter++
642
1160
  // `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
643
1161
  // the boot-unique prefix is needed (#3700). Format change does not
644
1162
  // affect the wire schema; clients treat messageId as opaque string.
645
1163
  const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
646
1164
  this._currentMessageId = messageId
1165
+ // This immutable request id remains this query's identity across awaits,
1166
+ // timeout recovery and a successor query taking over the session.
1167
+ const emitTurnEvent = (event, payload) => this.emit(event, { ...payload, declarationTurnId: messageId })
1168
+ this.emit('declaration_turn', { declarationTurnId: messageId })
647
1169
  // Shared ref so _handleResultTimeout can observe the latest value
648
1170
  // when it fires (the timer was armed when hasStreamStarted was still
649
1171
  // false, but the turn may have streamed before the timeout landed).
@@ -695,9 +1217,16 @@ export class SdkSession extends BaseSession {
695
1217
  cwd: this.cwd,
696
1218
  permissionMode: sdkPermMode,
697
1219
  includePartialMessages: true,
698
- settingSources: ['user', 'project', 'local'],
1220
+ settingSources: claudeSettingSourcesFor(projectAllowed),
699
1221
  systemPrompt,
700
1222
  tools: { type: 'preset', preset: 'claude_code' },
1223
+ // The environment for the `claude` child query() spawns, built per turn
1224
+ // by the same spawn-env builder every other provider child goes
1225
+ // through: the full parent env minus the daemon-owned secrets and any
1226
+ // ambiently inherited per-session chroxy values, plus the host
1227
+ // identity. A containerised subclass receives it through
1228
+ // spawnClaudeCodeProcess's `env` and applies its own allowlist.
1229
+ env: buildSpawnEnv('claude-sdk'),
701
1230
  }
702
1231
 
703
1232
  // SDK requires this flag when using bypassPermissions
@@ -709,11 +1238,9 @@ export class SdkSession extends BaseSession {
709
1238
  options.model = this.model
710
1239
  }
711
1240
 
712
- // Apply thinking level if set
713
- if (this._thinkingLevel) {
714
- const budget = SdkSession.THINKING_BUDGETS[this._thinkingLevel]
715
- if (budget != null) options.maxThinkingTokens = budget
716
- }
1241
+ // Apply thinking level if set — as Claude Code's effort, or as the legacy
1242
+ // budget for a model that predates effort (#8700, `_thinkingOptions`).
1243
+ Object.assign(options, this._thinkingOptions())
717
1244
 
718
1245
  // #4306 — magic thinking-keyword escalation. The native Claude Code CLI's
719
1246
  // interactive REPL scans the user's prompt for keywords (`think`,
@@ -749,7 +1276,12 @@ export class SdkSession extends BaseSession {
749
1276
  options.sandbox = this._sandbox
750
1277
  }
751
1278
 
752
- // In-process permission handling (only when not bypassing).
1279
+ // In-process permission handling. In normal modes the SDK's canUseTool
1280
+ // request reaches PermissionManager. `bypassPermissions` suppresses those
1281
+ // native permission requests, so Auto uses the SDK's PreToolUse hook seam
1282
+ // instead: PreToolUse runs before every tool even under bypass, and the
1283
+ // callback routes the same (tool,input) pair through PermissionManager.
1284
+ // That keeps permission-floor.js as the one protected-path predicate.
753
1285
  // We forward the SDK-provided `suggestions` to the permission manager
754
1286
  // so the 'allow always' flow can echo them back via updatedPermissions.
755
1287
  // Without this, respondToPermission('allowAlways') had nothing to
@@ -760,8 +1292,18 @@ export class SdkSession extends BaseSession {
760
1292
  // documentation is { behavior: 'allow', updatedPermissions:
761
1293
  // <suggestions from callback options> }.
762
1294
  if (this.permissionMode !== 'auto') {
763
- options.canUseTool = (toolName, input, { signal, suggestions }) =>
764
- this._handlePermission(toolName, input, signal, suggestions)
1295
+ options.canUseTool = (toolName, input, { signal, suggestions, toolUseID }) =>
1296
+ this._handlePermission(toolName, input, signal, suggestions, toolUseID)
1297
+ } else {
1298
+ options.hooks = {
1299
+ PreToolUse: [{
1300
+ hooks: [(input, toolUseId, { signal }) => this._handleAutoPreToolUse(input, signal, toolUseId)],
1301
+ // PermissionManager's default human-decision timeout is 300s. Give
1302
+ // its hook callback a small completion margin so the manager owns the
1303
+ // timeout result instead of the SDK aborting it first.
1304
+ timeout: 310,
1305
+ }],
1306
+ }
765
1307
  }
766
1308
 
767
1309
  // Resume existing session if we have one
@@ -811,24 +1353,228 @@ export class SdkSession extends BaseSession {
811
1353
  this._resetResultTimeout = resetResultTimeout
812
1354
  resetResultTimeout()
813
1355
 
1356
+ // #8030: declared OUTSIDE the try below so the catch block can see them.
1357
+ // spawnRefused distinguishes "the binary gate refused this spawn before
1358
+ // query() was ever called" from every other turn failure — it must never
1359
+ // be routed through the same error-enrichment/container-classification
1360
+ // path a real query failure gets. spawnPath is the path this turn actually
1361
+ // asked the SDK to spawn (whichever of spawnPreflight()/resolvedBinary won
1362
+ // below), used by the post-preflight spawn-failure backstop further down.
1363
+ let spawnRefused = false
1364
+ let spawnPath = null
1365
+ // #8030: flips true on the first message this turn's `for await` loop
1366
+ // receives. Gates the spawn-failure backstop below: a labelBinarySpawnFailure
1367
+ // re-verify only makes sense for a failure BEFORE any SDK output — once a
1368
+ // message has streamed, the binary plainly launched fine and a later
1369
+ // failure is something else entirely.
1370
+ let receivedAnyMessage = false
1371
+ // #8223: an authentication failure can reach this turn twice — as an assistant
1372
+ // message carrying `error: 'authentication_failed'`, and again as the query
1373
+ // throwing. Declared outside the try for the same reason as the flags above;
1374
+ // the first one to surface it wins, so a turn shows one AUTH_REQUIRED.
1375
+ let authRequiredEmitted = false
1376
+ // #8300: the turn's streaming input handle (set once `_createTurnInput`
1377
+ // runs inside the try); the `finally` ends it on every exit path.
1378
+ let input = null
1379
+ // #8300: a zero-turn `result` held back as a probable orphan-task notice
1380
+ // (see ORPHAN_NOTICE_CONFIRM_MS), the timer that takes it as the real
1381
+ // result if no `init` follows, and whether this turn has seen the prompt
1382
+ // actually run (assistant output, stream events or tool results) — a
1383
+ // result after that is the prompt's own whatever its num_turns says.
1384
+ let heldNoticeResult = null
1385
+ let noticeTimer = null
1386
+ let promptActivitySeen = false
1387
+ // #8300: set when `finishTurn` closed the query on purpose (background
1388
+ // work still live at the prompt's result), so the abort the SDK then
1389
+ // throws is logged, not surfaced as a turn error.
1390
+ let closedAfterResult = false
1391
+ // #8300: the held-result window finalizes the turn itself (see the
1392
+ // timer in `case 'result'`); the loop awaits that work before its finally
1393
+ // runs, so the two can never finish the same turn twice.
1394
+ let timerFinish = null
1395
+ // #8300: this turn's own query handle, so the `finally` only clears
1396
+ // `this._query` when it still points here — a follow-up turn that started
1397
+ // while this one was draining must keep its handle.
1398
+ let turnQuery = null
1399
+ // #8321: this turn's entry in `_drainingTurn`; ended in the `finally`.
1400
+ let turnDrain = null
1401
+ // #8300: the task ids THIS turn saw start. The roster is shared per
1402
+ // session, so a turn that finishes after a follow-up turn has started
1403
+ // must only stop and report the tasks it owns, never the successor's.
1404
+ const turnTaskIds = new Set()
1405
+ // #8302: the background SHELL ids this turn's tool_results announced. A shell
1406
+ // is owned by the process that started it, and on this provider that is the
1407
+ // turn's own per-turn process: once the turn's query is closed nothing can
1408
+ // ever read the shell's output or hear its completion, so it must not keep
1409
+ // the session "running". Kept apart from `turnTaskIds` because a shell can
1410
+ // be tracked without a `task_started` ever naming it (an older CLI build,
1411
+ // `skip_transcript`), and that is exactly the shell no other path releases.
1412
+ const turnShellIds = new Set()
1413
+ // #8302: release every shell this turn started. `clearBackgroundShell` is a
1414
+ // no-op for an id that is not tracked, so this is idempotent and is called
1415
+ // from both the normal turn end and the `finally`. It never touches a shell
1416
+ // another turn tracked: a follow-up turn that took the session owns its own.
1417
+ const reapTurnShells = () => {
1418
+ for (const shellId of turnShellIds) this.clearBackgroundShell(shellId)
1419
+ }
1420
+ // #8302: set when the turn's query threw. Its control channel is then gone,
1421
+ // so a stop request cannot be made (and must not be pretended to have been).
1422
+ let queryFailed = false
1423
+ let queryClosed = false
1424
+ // #8329: set by the catch when the user's Stop is what aborted the turn, so the
1425
+ // shell report says "stopped" rather than "ended abnormally".
1426
+ let endedByUserStop = false
1427
+ // #8302: THE routine that asks the CLI to stop the turn's still-tracked
1428
+ // shells and turns the answers into reports. Used by the prompt's own result
1429
+ // (`finishTurn`, for shells no live task names) AND by the `finally` (every
1430
+ // other exit: a throw, an abort), so an abnormal exit cannot drop a spawned
1431
+ // shell silently. Idempotent: it only sees shells still tracked, and a shell
1432
+ // it handled is released by the caller, so the second call finds nothing.
1433
+ //
1434
+ // `outcome` per shell:
1435
+ // 'stopped' the CLI acknowledged the stop
1436
+ // 'unconfirmed' it did not — rejected (a shell-only id the CLI never
1437
+ // named, a task already gone), timed out, or the channel was
1438
+ // not usable to ask at all. Termination is UNKNOWN, and is
1439
+ // worded that way: "it may still be running" would claim more
1440
+ // than we know, "could not be stopped" more than we tried.
1441
+ const turnShellsToStop = () => [...turnShellIds]
1442
+ .filter((shellId) => this._pendingBackgroundShells.has(shellId))
1443
+ .filter((shellId) => !reportedShellIds.has(shellId))
1444
+ .map((shellId) => ({
1445
+ taskId: shellId,
1446
+ toolUseId: null,
1447
+ taskType: 'local_bash',
1448
+ description: this._pendingBackgroundShells.get(shellId)?.command || shellId,
1449
+ background: true,
1450
+ }))
1451
+ const reportedShellIds = new Set()
1452
+ const stopTurnShells = (shells, channelUsable) => Promise.all(shells.map(async (task) => {
1453
+ if (channelUsable) {
1454
+ ;(this._log || log).warn(`Background shell "${task.description}" (${task.taskId}) was still running at the turn's end; stopping it with the turn`)
1455
+ }
1456
+ const stopped = channelUsable ? await this._stopLiveTask(turnQuery, task.taskId) : false
1457
+ return { task, outcome: stopped ? 'stopped' : 'unconfirmed', asked: channelUsable }
1458
+ }))
1459
+ const reportTurnShells = (results) => {
1460
+ for (const { task, outcome, asked } of results) {
1461
+ if (reportedShellIds.has(task.taskId)) continue
1462
+ reportedShellIds.add(task.taskId)
1463
+ const tail = 'A claude-sdk session runs background work only within the turn that started it.'
1464
+ emitTurnEvent('error', {
1465
+ code: 'background_task_ended_with_turn',
1466
+ message: outcome === 'stopped'
1467
+ ? `Background shell "${task.description}" was still running when the turn ended and was stopped with it; ${tail}`
1468
+ : asked
1469
+ ? `Background shell "${task.description}" was still running when the turn ended; the CLI did not acknowledge a stop request, so its termination is UNCONFIRMED. ${tail}`
1470
+ : `Background shell "${task.description}" was still tracked when the turn ${endedByUserStop ? 'was stopped' : 'ended abnormally'}; the turn's query was no longer usable, so it could not be asked to stop and its termination is UNCONFIRMED. ${tail}`,
1471
+ toolUseId: null,
1472
+ taskId: task.taskId,
1473
+ stopped: outcome === 'stopped',
1474
+ unconfirmed: outcome !== 'stopped',
1475
+ recoverable: true,
1476
+ })
1477
+ }
1478
+ }
1479
+ // #8300: true once a follow-up turn owns the session (it started while
1480
+ // this one was still draining or stopping work, after a hard timeout or
1481
+ // stream stall cleared busy). This turn then only reports and ends its
1482
+ // own process; it must not clear busy state or flush the queue, which
1483
+ // belong to the newer turn.
1484
+ const supersededByNewerTurn = () => this._turnSeq !== turnSeq
1485
+
814
1486
  try {
815
- // Allow subclasses to augment query options (e.g. DockerSdkSession
816
- // injects spawnClaudeCodeProcess here)
817
- this._augmentQueryOptions(options)
1487
+ // #7986 / #8030: point the SDK at the installed `claude` binary on every
1488
+ // turn. The desktop bundle does not ship the SDK's own platform binary,
1489
+ // and without pathToClaudeCodeExecutable query() throws ("Native CLI
1490
+ // binary ... not found") even when a subclass supplies
1491
+ // spawnClaudeCodeProcess. The SDK execs a NEW process per turn, so
1492
+ // "verified at session-create" only covers turn one — `_gatedSpawnBinary`
1493
+ // (BaseSession; the gate is SessionManager's `spawnPreflight` opt)
1494
+ // re-runs the full binary gate against the create-time-pinned path
1495
+ // before every subsequent spawn too. Falls back to a plain
1496
+ // `resolvedBinary` read when no gate was wired (a direct `new
1497
+ // SdkSession(...)` caller that bypassed SessionManager, or a test).
1498
+ // Set BEFORE _augmentQueryOptions so a subclass can read it; a subclass
1499
+ // that CHANGES it is refused below, since the new path was never checked.
1500
+ //
1501
+ // Everything in this inner try runs before query() and decides WHAT would
1502
+ // be exec'd, so any throw here is a pre-dispatch refusal (spawnRefused).
1503
+ try {
1504
+ // #8035: an empty path would leave pathToClaudeCodeExecutable unset,
1505
+ // and the SDK would then fall back to its own bundled binary —
1506
+ // unverified. `_gatedSpawnBinary` (BaseSession) throws
1507
+ // PROVIDER_BINARY_UNVERIFIED for that case; any error the gate itself
1508
+ // throws propagates unchanged.
1509
+ spawnPath = this._gatedSpawnBinary('claude')
1510
+ options.pathToClaudeCodeExecutable = spawnPath
1511
+
1512
+ // Allow subclasses to augment query options (e.g. DockerSdkSession
1513
+ // injects spawnClaudeCodeProcess here)
1514
+ this._augmentQueryOptions(options)
1515
+ if (options.pathToClaudeCodeExecutable !== spawnPath) {
1516
+ const err = new Error('A provider hook changed the claude binary path after it was verified; this turn was not sent.')
1517
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
1518
+ throw err
1519
+ }
1520
+
1521
+ // #8030 review: a containerised subclass runs claude INSIDE its
1522
+ // container through spawnClaudeCodeProcess, and pathToClaudeCodeExecutable
1523
+ // is the HOST binary, which no gate has checked (containerised providers
1524
+ // get no spawnPreflight). Without the hook — e.g. DockerSdkSession before
1525
+ // `docker run` has returned a container id — query() would exec the host
1526
+ // claude outside the container. Refuse instead.
1527
+ if (this.constructor.capabilities?.containerized && typeof options.spawnClaudeCodeProcess !== 'function') {
1528
+ const err = new Error('The session container is not ready, so this turn was not sent (it would otherwise run the host claude outside the container). Retry once the container has started.')
1529
+ err.code = 'CONTAINER_SPAWN_UNAVAILABLE'
1530
+ throw err
1531
+ }
1532
+ } catch (err) {
1533
+ spawnRefused = true
1534
+ throw err
1535
+ }
818
1536
 
819
1537
  // If attachments present, build multimodal content blocks
820
1538
  const promptWithSkills = firstMessagePrefix
821
1539
  ? `${firstMessagePrefix}${transformedPrompt}`
822
1540
  : transformedPrompt
823
- const queryArgs = { prompt: promptWithSkills, options }
824
- if (attachments?.length) {
825
- queryArgs.prompt = buildContentBlocks(promptWithSkills, attachments)
826
- }
1541
+ const promptContent = attachments?.length
1542
+ ? buildContentBlocks(promptWithSkills, attachments)
1543
+ : [{ type: 'text', text: typeof promptWithSkills === 'string' ? promptWithSkills : String(promptWithSkills ?? '') }]
1544
+ // #8300: the prompt goes to query() as a STREAMING input (an async
1545
+ // iterable of one user message), never as a plain string. With a string
1546
+ // the Agent SDK marks the query single-turn and closes the CLI's stdin at
1547
+ // the FIRST `result` it sees — and on `--resume` the first result can be
1548
+ // the orphan-task notice turn, not the prompt's: the prompt then runs
1549
+ // with no channel for `canUseTool`/PreToolUse, every tool call is
1550
+ // cancelled with the generic "user doesn't want to take this action"
1551
+ // text, and no permission_request ever reaches a client. With an
1552
+ // iterable the SDK closes stdin only after the iterable ENDS, and this
1553
+ // turn ends it in `finishTurn` — after the result that answers the
1554
+ // prompt — or in the `finally` below, so stdin is never left open past
1555
+ // the turn either.
1556
+ input = this._createTurnInput({
1557
+ type: 'user',
1558
+ session_id: this._sdkSessionId || '',
1559
+ message: { role: 'user', content: promptContent },
1560
+ parent_tool_use_id: null,
1561
+ })
1562
+ this._turnInput = input
1563
+ const queryArgs = { prompt: input.iterable, options }
827
1564
  this._query = this._callQuery(queryArgs)
1565
+ turnQuery = this._query
1566
+ turnDrain = { query: turnQuery, waitTimer: null, forceTimer: null }
1567
+ this._drainingTurn = turnDrain
1568
+ // A message already waited while busy had cleared before this query existed.
1569
+ if (!this._isBusy && this._outgoingQueue.length) this._armDrainRelease()
1570
+ reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
828
1571
  // #5269: a fresh turn — drop any task_id mappings left over from a prior
829
1572
  // turn (every subagent should clear via task_notification, but a turn
830
1573
  // aborted before its notifications would otherwise strand entries).
831
1574
  this._taskIdByToolUseId.clear()
1575
+ // #8300: the live-task roster is NOT cleared here: a previous turn may
1576
+ // still be finishing (stopping its own tasks) and reads its entries by
1577
+ // the ids it saw start; a stale entry can never match a later turn.
832
1578
 
833
1579
  // _callQuery returned an iterable without throwing — the prepend
834
1580
  // bucket is committed to this turn's prompt, so flip the flag (#3225).
@@ -839,13 +1585,304 @@ export class SdkSession extends BaseSession {
839
1585
  this._skillsPrepended = true
840
1586
  }
841
1587
 
1588
+ // #8300: a held zero-turn result turned out to be the orphan-task
1589
+ // notice — the CLI went on with the prompt in the same process. Called
1590
+ // from the next `init` (the usual confirmation), from any prompt
1591
+ // activity, and from a further result; each is stronger evidence than
1592
+ // the 2 s window, which must never fire under a running prompt.
1593
+ const confirmHeldNotice = (how) => {
1594
+ if (heldNoticeResult === null) return
1595
+ heldNoticeResult = null
1596
+ if (noticeTimer) {
1597
+ clearTimeout(noticeTimer)
1598
+ noticeTimer = null
1599
+ }
1600
+ ;(this._log || log).info(`Claude Code replayed a background task left over from an earlier turn (${how}); the prompt runs in the same process`)
1601
+ this.emit('message', {
1602
+ type: 'system',
1603
+ subtype: 'orphan_task_notice',
1604
+ content: 'A background task from an earlier turn ended with that turn; Claude Code noted it and is now running this prompt.',
1605
+ timestamp: Date.now(),
1606
+ })
1607
+ }
1608
+
1609
+ // #8300: the prompt's own result ends the turn. A closure rather than a
1610
+ // `case` body so the held-notice timer and the post-loop fallback can
1611
+ // run the identical turn end. Idempotent: whichever of the three callers
1612
+ // gets here first finishes the turn, the others return. `heldPath` says
1613
+ // this is a held zero-turn result taken as the prompt's own (the CLI is
1614
+ // idle or already gone), so no context-usage snapshot is requested.
1615
+ let turnFinished = false
1616
+ // #8300: end this turn's own process, once. Used when live work would
1617
+ // keep it alive past the result, when a finished turn keeps receiving
1618
+ // messages (the process lingered), and when destroy() lands mid-stop.
1619
+ // (`queryClosed` itself is declared with the turn's other flags, above the
1620
+ // try, because the `finally` reads it too — #8302.)
1621
+ // #8300: set once finishTurn's stop requests have been answered (or
1622
+ // timed out). A message that lands during the stops must not close the
1623
+ // query first: the real SDK rejects pending control requests on close,
1624
+ // and a stop the CLI had already carried out would be reported as failed.
1625
+ let stopsDone = false
1626
+ const closeTurnQuery = () => {
1627
+ if (queryClosed || !turnQuery) return
1628
+ queryClosed = true
1629
+ closedAfterResult = true
1630
+ try {
1631
+ if (typeof turnQuery.close === 'function') turnQuery.close()
1632
+ } catch (closeErr) {
1633
+ ;(this._log || log).warn(`Query close after result failed: ${closeErr?.message || closeErr}`)
1634
+ }
1635
+ }
1636
+ // #8321: the drain bound closes the query through the turn's own close, so
1637
+ // the abort the SDK then throws is logged, not reported as a turn error.
1638
+ if (turnDrain) turnDrain.close = closeTurnQuery
1639
+ const finishTurn = async (msg, { heldPath = false } = {}) => {
1640
+ if (turnFinished) return
1641
+ turnFinished = true
1642
+ // #8300: background work the CLI started this turn and has not
1643
+ // closed. The turn's process cannot outlive the turn, and the SDK
1644
+ // provider cannot service a task past the result (its tool calls
1645
+ // would be cancelled and its notification turn left unserviced), so
1646
+ // the work is stopped with the turn and each loss is said out loud —
1647
+ // never a silent cancellation.
1648
+ //
1649
+ // Stops go to THIS turn's query (`turnQuery`), never `this._query`,
1650
+ // which a follow-up turn may own by now. Asked in parallel and
1651
+ // bounded, so N hung tasks cost one STOP_TASK_TIMEOUT_MS, not N.
1652
+ const liveWork = this._liveBackgroundWork().filter((task) => turnTaskIds.has(task.taskId))
1653
+ // Only this turn's own tasks leave the roster: a follow-up turn that
1654
+ // took the session owns whatever else is in it.
1655
+ for (const task of liveWork) this._liveBackgroundTasks.delete(task.taskId)
1656
+ // #8302: a shell this turn's tool_result announced that no live task
1657
+ // names (no `task_started`, or a `skip_transcript` one) is still a shell
1658
+ // the CLI spawned, and a spawned shell can outlive the query (verified
1659
+ // live, above). Releasing it silently would leave it running, unreported.
1660
+ // So it goes through the SAME bounded stop pass and the SAME report as a
1661
+ // rostered task, and is released afterwards. Only shells still tracked:
1662
+ // one a notification already closed is gone from the tracker.
1663
+ const rosteredIds = new Set(liveWork.map((task) => task.taskId))
1664
+ const shellOnlyWork = turnShellsToStop().filter((task) => !rosteredIds.has(task.taskId))
1665
+ const stopWork = [...liveWork, ...shellOnlyWork]
1666
+ const [stopResults, shellOnlyResults] = await Promise.all([Promise.all(liveWork.map((task) => {
1667
+ const kind = task.taskType === 'local_bash' ? 'shell' : 'subagent'
1668
+ ;(this._log || log).warn(`Background ${kind} "${task.description}" (${task.taskId}) was still running at the turn's result; stopping it with the turn`)
1669
+ // Ask the CLI to stop the task while the control channel is still
1670
+ // open: closing the query alone ends the CLI, not a shell it spawned
1671
+ // (verified live: the shell outlived `close()`), so the report below
1672
+ // says which of the two happened.
1673
+ return this._stopLiveTask(turnQuery, task.taskId).then((stopped) => ({ task, kind, stopped }))
1674
+ })), stopTurnShells(shellOnlyWork, true)])
1675
+ // destroy() may have landed during the stops: it owns the UX from here
1676
+ // and has removed every listener, so nothing is emitted — but the
1677
+ // process is still ended, or a live task would keep it (and this
1678
+ // parked loop) alive for good.
1679
+ stopsDone = true
1680
+ if (this._destroying) {
1681
+ if (input) input.end()
1682
+ closeTurnQuery()
1683
+ return
1684
+ }
1685
+ // A hard timeout or stream stall during the stops may have cleared
1686
+ // busy and let a follow-up turn start: the session's state is then
1687
+ // that turn's, and this one only reports and ends its own process.
1688
+ const superseded = supersededByNewerTurn()
1689
+ for (const { task, kind, stopped } of stopResults) {
1690
+ emitTurnEvent('error', {
1691
+ code: 'background_task_ended_with_turn',
1692
+ message: stopped
1693
+ ? `Background ${kind} "${task.description}" was still running when the turn ended and was stopped with it; a claude-sdk session runs background work only within the turn that started it.`
1694
+ : `Background ${kind} "${task.description}" was still running when the turn ended; the CLI did not acknowledge a stop request, so its termination is UNCONFIRMED. A claude-sdk session runs background work only within the turn that started it.`,
1695
+ toolUseId: task.toolUseId,
1696
+ taskId: task.taskId,
1697
+ stopped,
1698
+ unconfirmed: !stopped,
1699
+ recoverable: true,
1700
+ })
1701
+ // A background shell's `task_id` is the shell id the tool_result
1702
+ // announced ("Command running in background with ID: <id>"), which
1703
+ // `_recordBackgroundShellsFromToolResults` tracked as pending work
1704
+ // (#4307). The shell dies with the turn's process, so drop it now:
1705
+ // left in place it keeps the roster busy ("waiting on background
1706
+ // work") for a shell nothing will ever read (#8302's shape).
1707
+ if (task.taskType === 'local_bash') this.clearBackgroundShell(task.taskId)
1708
+ }
1709
+ // #8302: and any shell this turn tracked that no live task named (see
1710
+ // `turnShellIds`), reported through the same routine the abnormal-exit
1711
+ // path uses. The process that could report on it ends with the turn.
1712
+ // Before the result is emitted, so the idle snapshot a client takes at
1713
+ // the result already reads idle.
1714
+ reportTurnShells(shellOnlyResults)
1715
+ reapTurnShells()
1716
+
1717
+ if (streamState.hasStreamStarted) {
1718
+ const outcome = outcomeFromSdkResult(msg)
1719
+ this.emit('stream_end', { messageId, ...(msg.is_error === true || (outcome && outcome !== 'completed') ? { interrupted: true } : {}) })
1720
+ }
1721
+
1722
+ if (msg.session_id) {
1723
+ this._sdkSessionId = msg.session_id
1724
+ this._sessionId = msg.session_id
1725
+ }
1726
+
1727
+ // Correct any static context-window guess using the SDK's
1728
+ // authoritative per-model values. Only cache + broadcast when
1729
+ // a value actually changed to avoid thrashy writes / UI churn.
1730
+ let contextWindowChanged = false
1731
+ if (msg.modelUsage && typeof msg.modelUsage === 'object') {
1732
+ const missingIds = []
1733
+ for (const [modelId, usage] of Object.entries(msg.modelUsage)) {
1734
+ if (usage && typeof usage.contextWindow === 'number') {
1735
+ if (updateContextWindow(modelId, usage.contextWindow)) {
1736
+ contextWindowChanged = true
1737
+ }
1738
+ } else {
1739
+ missingIds.push(modelId)
1740
+ }
1741
+ }
1742
+ // Drift signal: at least one modelUsage entry was missing a
1743
+ // numeric contextWindow. Catches both total drift (field renamed
1744
+ // or removed upstream) and partial drift (schema updated for one
1745
+ // model family before another). Log a redacted sample so a
1746
+ // future regression is diagnosable without flooding info-level
1747
+ // output.
1748
+ if (missingIds.length > 0) {
1749
+ const sampleId = missingIds[0]
1750
+ const sampleKeys = Object.keys(msg.modelUsage[sampleId] || {})
1751
+ // #4828: session-scoped (result handler runs strictly post-init).
1752
+ ;(this._log || log).debug(
1753
+ `modelUsage partial drift: contextWindow missing for modelIds=${JSON.stringify(missingIds)} sampleKeys=${JSON.stringify(sampleKeys)}`
1754
+ )
1755
+ }
1756
+ }
1757
+ if (contextWindowChanged) {
1758
+ saveModelsCache()
1759
+ // Notify connected clients so the picker / budget UI picks up
1760
+ // the corrected window without waiting for the next refresh.
1761
+ this.emit('models_updated', { models: getModels() })
1762
+ }
1763
+
1764
+ // #6769: end-of-turn occupancy snapshot via the SDK's
1765
+ // getContextUsage() control API — the same number Claude Code's
1766
+ // own /context shows. Queried while `this._query` is still live
1767
+ // (we're inside the for-await; the CLI process is alive until
1768
+ // the generator completes). `msg.usage` below is the per-turn
1769
+ // BILLING aggregate (summed across agent-loop rounds) and must
1770
+ // never be read as occupancy — see context-window.ts (#6769).
1771
+ // Null on timeout/old-CLI/error → field omitted → clients keep
1772
+ // their previous snapshot (or the honest dash state).
1773
+ // The snapshot asks the session's current query, which a superseding
1774
+ // turn would own; a superseded turn reports without one.
1775
+ const contextUsageSnapshot = (heldPath || superseded) ? null : await this._getContextUsageSnapshot()
1776
+
1777
+ // #8153: emit plan_ready before result — mirrors CliSession's
1778
+ // "the turn that calls ExitPlanMode ends with a normal result
1779
+ // event" ordering. `_planAllowedPrompts` is only non-null once
1780
+ // ExitPlanMode's tool_use block has been parsed (see
1781
+ // _handleToolUseBlock's 'exit_plan' branch above).
1782
+ if (!supersededByNewerTurn() && this._inPlanMode && this._planAllowedPrompts !== null) {
1783
+ this.emit('plan_ready', { allowedPrompts: this._planAllowedPrompts })
1784
+ this._inPlanMode = false
1785
+ this._planAllowedPrompts = null
1786
+ }
1787
+
1788
+ // #4628: sweep any orphan tool_starts before emitting result
1789
+ // so the dashboard's activeTools clears as part of the same
1790
+ // turn-end burst. _clearMessageState (called next) would also
1791
+ // clear the in-flight map but without broadcasting synthetic
1792
+ // tool_results to the dashboard.
1793
+ // A superseded turn emits its result directly: `_emitResult` would
1794
+ // sweep the shared in-flight tool_starts, which are the successor's.
1795
+ ;(supersededByNewerTurn() ? (payload) => emitTurnEvent('result', payload) : (payload, reason, opts) => this._emitResult(payload, reason, opts))({
1796
+ sessionId: msg.session_id || this._sdkSessionId,
1797
+ cost: msg.total_cost_usd,
1798
+ duration: msg.duration_ms,
1799
+ usage: msg.usage,
1800
+ // #6692: surface the per-model split + turn metadata the SDK
1801
+ // already reports instead of discarding them. Additive — every
1802
+ // existing result consumer ignores unknown fields.
1803
+ numTurns: Number.isFinite(msg.num_turns) ? msg.num_turns : null,
1804
+ apiDurationMs: Number.isFinite(msg.duration_api_ms) ? msg.duration_api_ms : null,
1805
+ modelUsage: normalizeSdkModelUsage(msg.modelUsage),
1806
+ // #6769: occupancy snapshot (or absent when unavailable).
1807
+ // Wire field is contextOccupancy — NOT contextUsage — so it can
1808
+ // never be confused with the billing `usage` aggregate above.
1809
+ ...(contextUsageSnapshot ? { contextOccupancy: contextUsageSnapshot } : {}),
1810
+ // #7326: why the turn ended (truncated by max_tokens / max turns /
1811
+ // budget, refused, ...). Omitted when the SDK reported nothing we map.
1812
+ declarationTurnId: messageId,
1813
+ declarationEligible: !supersededByNewerTurn() && !this._stdinForwardingDisabled && sdkDeclarationEligible(msg),
1814
+ ...turnOutcomeField(outcomeFromSdkResult(msg)),
1815
+ // #9241: `aborted_*` is the SDK saying the abort ended the turn.
1816
+ ...(outcomeFromSdkResult(msg) === 'stopped' ? { stopRequested: true } : {}),
1817
+ }, 'turn_ended_with_orphan_tool_start', { completion: 'normal' }) // #7376
1818
+
1819
+ // #7340: NOT `{ turnEndedCleanly: true }`, however much this looks
1820
+ // like CliSession's `result` branch -- and the difference is the
1821
+ // whole reason that flag is opt-in.
1822
+ //
1823
+ // CliSession owns a PERSISTENT stream-json child that spans turns,
1824
+ // so after its `result` a backgrounded subagent's
1825
+ // `task_notification` still arrives. SdkSession creates one
1826
+ // `query()` PER TURN (`sendMessage`: "Each call creates a new
1827
+ // query() with resume"), and this turn ends it a few lines below:
1828
+ // the streaming input is released, and with live background work
1829
+ // the query is closed outright (#8300). No `task_notification` can
1830
+ // arrive for an agent spared here -- and every recovery route is
1831
+ // closed too: `_handleHardTimeout` / `_handleStreamStall`
1832
+ // early-return on `!_isBusy`, `interrupt()` early-returns on a null
1833
+ // `_query`, and `cancelActivity` answers `not-supported`. The agent
1834
+ // would be stranded until `destroy()`, pinning the session as
1835
+ // working -- the failure #7340 names as the worse one.
1836
+ //
1837
+ // The subagent dies with the query, so completing it here is not
1838
+ // merely safe, it is accurate -- and #8300 says so to the client
1839
+ // (the `background_task_ended_with_turn` error above) instead of
1840
+ // leaving the loss silent. Exempting on this path needs the query
1841
+ // kept alive past `result`, which is a much larger change.
1842
+ if (!supersededByNewerTurn()) this._clearMessageState({ completion: 'normal' }) // #7376
1843
+
1844
+ // #8300: the prompt is answered — release the streaming input so the
1845
+ // SDK closes the CLI's stdin and the process exits once idle. With
1846
+ // live background work the process would NOT go idle (the task keeps
1847
+ // it alive with its tools cancelled), so the query is closed outright;
1848
+ // the abort that follows is expected (see `closedAfterResult`).
1849
+ streamState.hasStreamStarted = false
1850
+ if (input) input.end()
1851
+ if (stopWork.length) closeTurnQuery()
1852
+ }
1853
+
842
1854
  for await (const msg of this._query) {
843
1855
  if (this._destroying) break
844
- resetResultTimeout() // Any SDK event = activity, reset inactivity timer
1856
+ // #8300: a finished turn expects nothing more; a message after the
1857
+ // finish means the process lingered (work this turn could not see
1858
+ // kept it alive). It is not relayed into a turn that is over — the
1859
+ // process is ended instead, and the first such message is logged.
1860
+ if (turnFinished) {
1861
+ // Only another turn's traffic means the process lingered: an init,
1862
+ // assistant output, stream events or tool results. Bookkeeping
1863
+ // that routinely follows a result (task_updated/task_notification
1864
+ // after a stop, status, hook events) is dropped quietly.
1865
+ const lingering = msg?.type === 'assistant' || msg?.type === 'stream_event' || msg?.type === 'user' ||
1866
+ (msg?.type === 'system' && msg?.subtype === 'init')
1867
+ if (lingering && stopsDone && !queryClosed) {
1868
+ ;(this._log || log).warn(`SDK message after the turn's result (${msg?.type}/${msg?.subtype || ''}); ending the lingering process`)
1869
+ closeTurnQuery()
1870
+ }
1871
+ continue
1872
+ }
1873
+ receivedAnyMessage = true // #8030: gates the spawn-failure backstop below
1874
+ // A superseded turn's traffic must not re-arm the session's
1875
+ // inactivity timers against the successor.
1876
+ if (!supersededByNewerTurn()) resetResultTimeout() // Any SDK event = activity, reset inactivity timer
845
1877
 
846
1878
  switch (msg.type) {
847
1879
  case 'system': {
848
1880
  if (msg.subtype === 'init') {
1881
+ // #8300: a second `init` right after a zero-turn `result` is the
1882
+ // CLI starting the prompt's own turn in the same process — the
1883
+ // held result was the orphan-task notice. Say so once and keep
1884
+ // the turn open; the prompt's result is still to come.
1885
+ confirmHeldNotice('a second init followed it')
849
1886
  this._sdkSessionId = msg.session_id
850
1887
  this._sessionId = msg.session_id
851
1888
  // #4828: bind the session-scoped logger now that session_id
@@ -875,6 +1912,13 @@ export class SdkSession extends BaseSession {
875
1912
  }
876
1913
  // Fetch dynamic model list from SDK (non-blocking)
877
1914
  this._fetchSupportedModels()
1915
+ // #8700: and the effort this turn actually runs at (non-blocking).
1916
+ // Caught here because nothing awaits it: a throwing listener on the
1917
+ // `thinking_level_changed` it emits must not become an unhandled
1918
+ // rejection, which ends the daemon (#5313).
1919
+ this._readEffectiveEffort().catch((err) => {
1920
+ ;(this._log || log).warn(`Effort report failed: ${err?.message || err}`)
1921
+ })
878
1922
  } else if (msg.subtype === 'task_started') {
879
1923
  // #5269: a Task subagent started. The SDK message carries BOTH
880
1924
  // the subagent's `task_id` (needed by query.stopTask) and the
@@ -883,6 +1927,49 @@ export class SdkSession extends BaseSession {
883
1927
  // activity id back to a stoppable task. No client-facing emit —
884
1928
  // the agent node already exists via agent_spawned.
885
1929
  this._captureTaskId(msg.tool_use_id, msg.task_id)
1930
+ // #8300: remember the task until its `task_notification`. Only a
1931
+ // task the CLI itself flags `is_backgrounded` counts as live work
1932
+ // at the prompt's result: a foreground Bash is ALSO reported as a
1933
+ // `local_bash` task (with `is_backgrounded: false`) and settles
1934
+ // before the result, so the task type alone says nothing. A
1935
+ // `task_updated` patch can flip the flag later (Ctrl+B-style
1936
+ // backgrounding). `skip_transcript` marks ambient housekeeping
1937
+ // work the user never started; it is never reported as a loss.
1938
+ if (typeof msg.task_id === 'string' && msg.task_id && msg.skip_transcript !== true) {
1939
+ turnTaskIds.add(msg.task_id)
1940
+ this._liveBackgroundTasks.set(msg.task_id, {
1941
+ taskId: msg.task_id,
1942
+ toolUseId: typeof msg.tool_use_id === 'string' ? msg.tool_use_id : null,
1943
+ taskType: typeof msg.task_type === 'string' ? msg.task_type : 'unknown',
1944
+ description: typeof msg.description === 'string' && msg.description
1945
+ ? msg.description
1946
+ : 'Background task',
1947
+ background: msg.is_backgrounded === true,
1948
+ })
1949
+ }
1950
+ // #7340: `task_started` is the provider's OWN lifecycle event and
1951
+ // carries `is_backgrounded` — authoritative where the tool input
1952
+ // is only the model's request. It also arrives regardless of what
1953
+ // the subagent tool is NAMED, so tracking survives a future
1954
+ // rename the way the `Task` -> `Agent` one was not survived.
1955
+ // `task_type` distinguishes a subagent (`local_agent`) from a
1956
+ // backgrounded Bash (`local_bash`), which is #4307's surface and
1957
+ // must not be tracked as an agent.
1958
+ if (msg.task_type === 'local_agent') {
1959
+ this._trackAgent({
1960
+ toolUseId: msg.tool_use_id,
1961
+ description: typeof msg.description === 'string' && msg.description
1962
+ ? msg.description
1963
+ : 'Background task',
1964
+ background: msg.is_backgrounded === true,
1965
+ // #7340: authoritative -- this is the provider's own account,
1966
+ // so it overwrites the model's request in BOTH directions.
1967
+ // It is also the evidence that this build emits task
1968
+ // lifecycle messages at all, which is what makes the
1969
+ // turn-end exemption safe: `task_notification` can arrive.
1970
+ authoritative: true,
1971
+ })
1972
+ }
886
1973
  break
887
1974
  } else if (msg.subtype === 'task_notification') {
888
1975
  // #5269: a Task subagent reached a terminal state (completed /
@@ -891,6 +1978,37 @@ export class SdkSession extends BaseSession {
891
1978
  // cancel feels responsive instead of waiting for the turn-end
892
1979
  // sweep. Idempotent (no-op if already finalized).
893
1980
  this._finalizeAgentByToolUseId(msg.tool_use_id)
1981
+ // #8300: the task is closed; it no longer counts as live work at
1982
+ // the prompt's result.
1983
+ if (typeof msg.task_id === 'string') {
1984
+ this._liveBackgroundTasks.delete(msg.task_id)
1985
+ // #8302: a background shell's `task_id` IS the shell id its
1986
+ // tool_result announced, and a terminal notification is the
1987
+ // only completion signal that still exists (current Claude Code
1988
+ // has no `BashOutput` tool, so the acknowledgement clear can
1989
+ // never fire). Untracked ids are a no-op.
1990
+ this.clearBackgroundShell(msg.task_id)
1991
+ }
1992
+ break
1993
+ } else if (msg.subtype === 'task_updated') {
1994
+ // #8300: a task backgrounded after it started (`patch.is_backgrounded`)
1995
+ // becomes live work; a terminal `patch.status` closes it.
1996
+ const live = typeof msg.task_id === 'string' ? this._liveBackgroundTasks.get(msg.task_id) : null
1997
+ const patch = msg.patch && typeof msg.patch === 'object' ? msg.patch : null
1998
+ if (live && patch) {
1999
+ if (patch.is_backgrounded === true) live.background = true
2000
+ if (typeof patch.description === 'string' && patch.description) live.description = patch.description
2001
+ if (isTerminalTaskStatus(patch.status)) {
2002
+ this._liveBackgroundTasks.delete(msg.task_id)
2003
+ }
2004
+ }
2005
+ // #8302: a terminal status closes the task's shell too — whether
2006
+ // or not the roster holds the task (a `skip_transcript` task is
2007
+ // never on it, yet its shell may still be tracked). Same id
2008
+ // equality and same no-op as the `task_notification` branch.
2009
+ if (patch && typeof msg.task_id === 'string' && isTerminalTaskStatus(patch.status)) {
2010
+ this.clearBackgroundShell(msg.task_id)
2011
+ }
894
2012
  break
895
2013
  } else if (msg.subtype === 'compact_boundary') {
896
2014
  // #6768: the SDK compacted the conversation (auto-triggered
@@ -914,6 +2032,24 @@ export class SdkSession extends BaseSession {
914
2032
  timestamp: Date.now(),
915
2033
  })
916
2034
  break
2035
+ } else if (msg.subtype === 'status') {
2036
+ // #8153 (review nit): `SDKStatusMessage` carries no
2037
+ // `message`/`text` field, just `status: 'compacting' |
2038
+ // 'requesting' | null` — the generic fallback below would
2039
+ // otherwise forward the bare literal string "status" as a
2040
+ // chat bubble. `status: null` means the previous status
2041
+ // cleared, nothing new to show, so it's suppressed entirely
2042
+ // rather than emitted as an empty/placeholder bubble.
2043
+ const statusText = formatStatusContent(msg.status)
2044
+ if (statusText) {
2045
+ this.emit('message', {
2046
+ type: 'system',
2047
+ subtype: 'status',
2048
+ content: statusText,
2049
+ timestamp: Date.now(),
2050
+ })
2051
+ }
2052
+ break
917
2053
  } else {
918
2054
  // Forward non-init system events (e.g. /usage, /cost, other
919
2055
  // slash command responses) as system messages to the client
@@ -930,6 +2066,8 @@ export class SdkSession extends BaseSession {
930
2066
  }
931
2067
 
932
2068
  case 'stream_event': {
2069
+ promptActivitySeen = true // #8300: the prompt is running
2070
+ confirmHeldNotice('stream events followed it')
933
2071
  // Handle partial message events (content_block_start/delta/stop)
934
2072
  const event = msg.event
935
2073
  if (!event) break
@@ -1017,6 +2155,13 @@ export class SdkSession extends BaseSession {
1017
2155
  didStreamThinking = true
1018
2156
  this.emit('stream_delta', { messageId: thinkingId, delta: delta.thinking, thinking: true })
1019
2157
  }
2158
+ // #8135 (review on #7346): the Agent SDK's `input_json_delta`
2159
+ // chunks (present, since `includePartialMessages: true` is
2160
+ // set) are deliberately NOT forwarded here — a secret can
2161
+ // straddle chunk boundaries and mid-stream partial JSON
2162
+ // can't be sanitized. The sanitized FULL input is delivered
2163
+ // once instead, from `_handleToolUseBlock` below, once the
2164
+ // complete assistant-message `block.input` is known.
1020
2165
  break
1021
2166
  }
1022
2167
 
@@ -1051,13 +2196,29 @@ export class SdkSession extends BaseSession {
1051
2196
  }
1052
2197
 
1053
2198
  case 'assistant': {
2199
+ // #8223: the SDK marks a synthetic assistant message with the failure
2200
+ // class (`SDKAssistantMessage.error`). For `authentication_failed` its
2201
+ // text block is the raw "Failed to authenticate: …" line; surface the
2202
+ // typed error INSTEAD of that text as a chat response, and do not take
2203
+ // this non-turn message as the fork boundary below.
2204
+ if (msg.error === 'authentication_failed') {
2205
+ if (!authRequiredEmitted) {
2206
+ authRequiredEmitted = true
2207
+ ;(this._log || log).warn('Assistant message reported authentication_failed')
2208
+ emitTurnEvent('error', this._authRequiredPayload())
2209
+ }
2210
+ break
2211
+ }
1054
2212
  // #6766: remember this message's transcript UUID as the fork
1055
2213
  // boundary. A checkpoint auto-created at the start of the NEXT turn
1056
2214
  // captures this as its boundary, so restoring that checkpoint can
1057
2215
  // fork the conversation truncated to exactly this point.
1058
2216
  this._captureBoundaryMessage(msg)
2217
+ promptActivitySeen = true // #8300: the prompt is running
2218
+ confirmHeldNotice('assistant output followed it')
1059
2219
  // Full assistant message — process content blocks for tool detection
1060
2220
  const content = msg.message?.content
2221
+ emitTurnEvent('assistant_response', { responseId: msg.message?.id ?? msg.uuid, text: assistantResponseText(content) })
1061
2222
  if (!Array.isArray(content)) break
1062
2223
 
1063
2224
  for (const block of content) {
@@ -1092,6 +2253,42 @@ export class SdkSession extends BaseSession {
1092
2253
  }
1093
2254
 
1094
2255
  case 'user': {
2256
+ promptActivitySeen = true // #8300: the prompt is running
2257
+ confirmHeldNotice('tool results followed it')
2258
+ // #8300: a tool_result carrying Claude Code's own cancellation text
2259
+ // means the CLI dropped the call WITHOUT asking this session's
2260
+ // PermissionManager — there was no channel to ask on. That is a
2261
+ // runtime fault of the turn, not a decision anyone took, so it is
2262
+ // surfaced as a session error naming the tool and its id (the
2263
+ // tool_result still follows, flagged isError, so the tool_start
2264
+ // it answers is closed). Read BEFORE emitToolResults, which drops
2265
+ // the in-flight entry that carries the tool name.
2266
+ if (Array.isArray(msg.message?.content)) {
2267
+ for (const block of msg.message.content) {
2268
+ if (block?.type !== 'tool_result' || !block.tool_use_id) continue
2269
+ // The CLI's cancellation block is always `is_error: true`; a
2270
+ // tool's OWN output that happens to start with the sentence (a
2271
+ // fetched page, a file, an echo) is not an error block.
2272
+ if (block.is_error !== true) continue
2273
+ // #8363: Stop cancelled this tool's pending prompt; the result is
2274
+ // tagged as a Stop below, and is not a provider-side fault.
2275
+ if (this._stopCancelledToolUseIds.has(block.tool_use_id)) continue
2276
+ const text = toolResultText(block)
2277
+ if (!isSdkToolCancellationText(text)) continue
2278
+ const tool = this._inFlightToolStarts.get(block.tool_use_id)?.tool || 'unknown'
2279
+ const firstLine = text.trim().split('\n')[0].slice(0, 200)
2280
+ ;(this._log || log).error(
2281
+ `Claude Code cancelled the ${tool} tool call ${block.tool_use_id} without consulting the permission pipeline: ${firstLine}`,
2282
+ )
2283
+ emitTurnEvent('error', {
2284
+ code: 'tool_cancelled_by_provider',
2285
+ message: `Claude Code cancelled the ${tool} tool call (${block.tool_use_id}) before it reached the permission pipeline: ${firstLine}`,
2286
+ tool,
2287
+ toolUseId: block.tool_use_id,
2288
+ recoverable: true,
2289
+ })
2290
+ }
2291
+ }
1095
2292
  // Tool result content blocks appear in user-role messages during the tool loop
1096
2293
  emitToolResults(msg.message?.content, this)
1097
2294
  // #4307: scan tool_result blocks for the canonical
@@ -1102,135 +2299,241 @@ export class SdkSession extends BaseSession {
1102
2299
  // truncation surface (tool-result.js is also used by
1103
2300
  // CliSession + GeminiSession, which don't share this
1104
2301
  // BaseSession path).
1105
- this._recordBackgroundShellsFromToolResults(msg.message?.content)
2302
+ this._recordBackgroundShellsFromToolResults(msg.message?.content, turnShellIds)
1106
2303
  break
1107
2304
  }
1108
2305
 
1109
2306
  case 'result': {
1110
- if (streamState.hasStreamStarted) {
1111
- this.emit('stream_end', { messageId })
1112
- }
1113
-
1114
- if (msg.session_id) {
1115
- this._sdkSessionId = msg.session_id
1116
- this._sessionId = msg.session_id
1117
- }
1118
-
1119
- // Correct any static context-window guess using the SDK's
1120
- // authoritative per-model values. Only cache + broadcast when
1121
- // a value actually changed to avoid thrashy writes / UI churn.
1122
- let contextWindowChanged = false
1123
- if (msg.modelUsage && typeof msg.modelUsage === 'object') {
1124
- const missingIds = []
1125
- for (const [modelId, usage] of Object.entries(msg.modelUsage)) {
1126
- if (usage && typeof usage.contextWindow === 'number') {
1127
- if (updateContextWindow(modelId, usage.contextWindow)) {
1128
- contextWindowChanged = true
1129
- }
1130
- } else {
1131
- missingIds.push(modelId)
1132
- }
1133
- }
1134
- // Drift signal: at least one modelUsage entry was missing a
1135
- // numeric contextWindow. Catches both total drift (field renamed
1136
- // or removed upstream) and partial drift (schema updated for one
1137
- // model family before another). Log a redacted sample so a
1138
- // future regression is diagnosable without flooding info-level
1139
- // output.
1140
- if (missingIds.length > 0) {
1141
- const sampleId = missingIds[0]
1142
- const sampleKeys = Object.keys(msg.modelUsage[sampleId] || {})
1143
- // #4828: session-scoped (result handler runs strictly post-init).
1144
- ;(this._log || log).debug(
1145
- `modelUsage partial drift: contextWindow missing for modelIds=${JSON.stringify(missingIds)} sampleKeys=${JSON.stringify(sampleKeys)}`
1146
- )
1147
- }
1148
- }
1149
- if (contextWindowChanged) {
1150
- saveModelsCache()
1151
- // Notify connected clients so the picker / budget UI picks up
1152
- // the corrected window without waiting for the next refresh.
1153
- this.emit('models_updated', { models: getModels() })
2307
+ // #8300: on `--resume` the CLI can run an orphan-task notice as its
2308
+ // own zero-cost turn BEFORE the prompt: `init` → this result with
2309
+ // `num_turns: 0` → a second `init`. Taking it as the prompt's
2310
+ // result would end the turn (and the input) under the prompt.
2311
+ // Hold it: the next `init` confirms the notice; if none comes
2312
+ // within ORPHAN_NOTICE_CONFIRM_MS it was the prompt's own, the
2313
+ // input is released so the CLI exits, and the loop's end finishes
2314
+ // the held result below.
2315
+ // A further result while one is held: the held one was the notice
2316
+ // (the CLI ran another turn after it); this one is judged afresh.
2317
+ confirmHeldNotice('a further result followed it')
2318
+ if (msg.num_turns === 0 && msg.is_error !== true && !promptActivitySeen) {
2319
+ heldNoticeResult = msg
2320
+ ;(this._log || log).info(`Holding a zero-turn result (${msg.duration_ms ?? '?'}ms): probable orphan-task notice; waiting ${SdkSession.ORPHAN_NOTICE_CONFIRM_MS}ms for the prompt's own init`)
2321
+ // On expiry the held result is finished HERE, while the loop is
2322
+ // parked on the generator and the query is still live: finishTurn
2323
+ // releases the input and, if background work is keeping the
2324
+ // process alive, stops it and closes the query — so the turn can
2325
+ // never depend on an EOF that such work would withhold.
2326
+ noticeTimer = setTimeout(() => {
2327
+ noticeTimer = null
2328
+ if (heldNoticeResult === null || this._destroying) return
2329
+ const held = heldNoticeResult
2330
+ heldNoticeResult = null
2331
+ ;(this._log || log).info('No init followed the zero-turn result within the window; taking it as the prompt\'s own')
2332
+ timerFinish = finishTurn(held, { heldPath: true }).catch((err) => {
2333
+ ;(this._log || log).warn(`Finishing the held result failed: ${err?.message || err}`)
2334
+ })
2335
+ }, SdkSession.ORPHAN_NOTICE_CONFIRM_MS)
2336
+ break
1154
2337
  }
1155
-
1156
- // #6769: end-of-turn occupancy snapshot via the SDK's
1157
- // getContextUsage() control API — the same number Claude Code's
1158
- // own /context shows. Queried while `this._query` is still live
1159
- // (we're inside the for-await; the CLI process is alive until
1160
- // the generator completes). `msg.usage` below is the per-turn
1161
- // BILLING aggregate (summed across agent-loop rounds) and must
1162
- // never be read as occupancy — see context-window.ts (#6769).
1163
- // Null on timeout/old-CLI/error → field omitted → clients keep
1164
- // their previous snapshot (or the honest dash state).
1165
- const contextUsageSnapshot = await this._getContextUsageSnapshot()
1166
-
1167
- // #4628: sweep any orphan tool_starts before emitting result
1168
- // so the dashboard's activeTools clears as part of the same
1169
- // turn-end burst. _clearMessageState (called next) would also
1170
- // clear the in-flight map but without broadcasting synthetic
1171
- // tool_results to the dashboard.
1172
- this._emitResult({
1173
- sessionId: msg.session_id || this._sdkSessionId,
1174
- cost: msg.total_cost_usd,
1175
- duration: msg.duration_ms,
1176
- usage: msg.usage,
1177
- // #6692: surface the per-model split + turn metadata the SDK
1178
- // already reports instead of discarding them. Additive — every
1179
- // existing result consumer ignores unknown fields.
1180
- numTurns: Number.isFinite(msg.num_turns) ? msg.num_turns : null,
1181
- apiDurationMs: Number.isFinite(msg.duration_api_ms) ? msg.duration_api_ms : null,
1182
- modelUsage: normalizeSdkModelUsage(msg.modelUsage),
1183
- // #6769: occupancy snapshot (or absent when unavailable).
1184
- // Wire field is contextOccupancy — NOT contextUsage — so it can
1185
- // never be confused with the billing `usage` aggregate above.
1186
- ...(contextUsageSnapshot ? { contextOccupancy: contextUsageSnapshot } : {}),
1187
- }, 'turn_ended_with_orphan_tool_start')
1188
-
1189
- this._clearMessageState()
2338
+ await finishTurn(msg)
1190
2339
  break
1191
2340
  }
1192
2341
  }
1193
2342
  }
2343
+ // #8300: the loop ended (the CLI exited on its own) with a zero-turn
2344
+ // result still held and no init after it — it was the prompt's own.
2345
+ if (timerFinish) await timerFinish
2346
+ if (heldNoticeResult !== null && !this._destroying) {
2347
+ const held = heldNoticeResult
2348
+ heldNoticeResult = null
2349
+ await finishTurn(held, { heldPath: true })
2350
+ }
1194
2351
  } catch (err) {
2352
+ // #8302: the query threw; its control channel is gone (see `queryFailed`).
2353
+ queryFailed = true
2354
+ // #8300: a held zero-turn result dies with the loop — its timer must
2355
+ // not finish a turn that is being reported as failed below.
2356
+ if (noticeTimer) {
2357
+ clearTimeout(noticeTimer)
2358
+ noticeTimer = null
2359
+ }
2360
+ heldNoticeResult = null
2361
+ // #8300: a timer-driven finish may be mid-flight (stopping live work);
2362
+ // let it complete so its result precedes any error surfaced below and
2363
+ // nothing it emits lands after `_clearMessageState`.
2364
+ if (timerFinish) {
2365
+ try { await timerFinish } catch { /* logged where it was started */ }
2366
+ }
1195
2367
  if (streamState.hasStreamStarted) {
1196
2368
  this.emit('stream_end', { messageId })
1197
2369
  }
1198
2370
  // #4881: capture-and-clear before any branch so the flag never leaks
1199
2371
  // past this turn even when _destroying short-circuits the emits below.
1200
2372
  // Mirrors CliSession._handleChildClose (#4602).
1201
- const wasIntentionalStop = this._consumeIntentionalStop()
2373
+ // A superseded turn leaves the Stop flag to the turn it belongs to.
2374
+ const wasIntentionalStop = supersededByNewerTurn() ? false : this._consumeIntentionalStop()
2375
+ // #8430: whether the USER's Stop is what ended this turn is decided NOW, with
2376
+ // `wasIntentionalStop`. The failure handling below can await (container
2377
+ // classification), and a Stop that lands during that await did not end a turn
2378
+ // that had already failed.
2379
+ const userStopEndedTurn = this._permissions.isUserStopInFlight()
2380
+ if (wasIntentionalStop) endedByUserStop = true
1202
2381
  if (!this._destroying) {
1203
- if (wasIntentionalStop) {
2382
+ if (closedAfterResult && isQueryCloseError(err)) {
2383
+ // #8300: finishTurn already emitted this turn's result and closed
2384
+ // the query on purpose (background work was still live); the abort
2385
+ // the SDK throws for that is expected, not a turn failure. Any
2386
+ // OTHER error after the close is still surfaced below.
2387
+ ;(this._log || log).debug(`Query closed after the turn's result: ${err?.message || err}`)
2388
+ } else if (wasIntentionalStop) {
1204
2389
  // #4881: user clicked Stop — interrupt() set the flag, the SDK
1205
2390
  // generator threw an AbortError as a result. Skip the loud "Query
1206
2391
  // error" surface and emit the quiet `stopped` event for parity
1207
2392
  // with CliSession. No `code` because SDK runs in-process — there
1208
2393
  // is no child-process exit status to carry.
1209
2394
  ;(this._log || log).info('Query aborted after user stop')
1210
- this.emit('stopped', {})
2395
+ // #9241: `stopRequested` only for the abort the Stop caused, not any other
2396
+ // error that happened to land after it.
2397
+ emitTurnEvent('stopped', isQueryCloseError(err) ? { stopRequested: true } : {})
2398
+ } else if (spawnRefused) {
2399
+ // #8030: the turn was refused BEFORE query() was ever called — by the
2400
+ // per-spawn binary gate (a block-mode hash mismatch, quarantine, a
2401
+ // vanished pinned binary, …) or because a containerised session has
2402
+ // no in-container spawn hook yet. Two things this branch deliberately
2403
+ // does NOT do:
2404
+ // - route through _enrichErrorMessage: a provenance message
2405
+ // embeds a hex hash prefix (e.g. "...a4291b0c...") that can
2406
+ // match the rate-limit ("429") or auth ("401") patterns in
2407
+ // _ERROR_PATTERNS and get silently rewritten into a wrong,
2408
+ // misleading "rate limit"/"auth failed" message instead of the
2409
+ // real cause.
2410
+ // - run container classification: the turn never reached the
2411
+ // SDK, so there is no container to have vanished.
2412
+ // #8035: hoisted onto BaseSession (`_refuseTurnBeforeDispatch`) so
2413
+ // JsonlSubprocessSession's per-turn spawn gets byte-identical wire
2414
+ // shape instead of a second hand-rolled copy.
2415
+ this._refuseTurnBeforeDispatch(err, sendOptions, this._log || log)
1211
2416
  } else {
1212
- // #4828: session-scoped when init has fired; falls back to module
1213
- // `log` for pre-init query failures (e.g. spawn refused).
1214
- ;(this._log || log).error(`Query error: ${err.message}`)
1215
- this.emit('error', { message: SdkSession._enrichErrorMessage(err.message) })
2417
+ // #7599: let a containerized subclass classify this turn failure as a
2418
+ // vanished container (a distinct, recoverable state) before the
2419
+ // generic query-error surface. Base returns null; DockerSdkSession
2420
+ // probes the container and returns a CONTAINER_VANISHED payload.
2421
+ const containerGone = await this._classifyContainerFailure(err)
2422
+ // #7599: _classifyContainerFailure can await a real `docker exec` probe
2423
+ // (up to 10s). A destroy() landing in that window has already torn the
2424
+ // session down and removed its listeners, so emitting here would fire
2425
+ // on a dead EventEmitter (Node throws on an unhandled 'error'). Re-check
2426
+ // teardown after the await before surfacing anything.
2427
+ if (this._destroying) {
2428
+ // fall through to _clearMessageState below; destroy() owns the UX
2429
+ } else if (containerGone) {
2430
+ ;(this._log || log).warn(`Container vanished during turn: ${containerGone.message}`)
2431
+ emitTurnEvent('error', containerGone)
2432
+ } else {
2433
+ // #8030 backstop: a spawn failure AFTER preflight passed (the
2434
+ // pinned binary was quarantined/moved/removed between the gate
2435
+ // call above and the actual exec, or the gate wasn't wired at
2436
+ // all) surfaces from the SDK as generic text ("native binary ...
2437
+ // failed to launch"). Re-verify the ATTEMPTED path and label the
2438
+ // real cause + fix, the same backstop cli-session.js /
2439
+ // jsonl-subprocess-session.js run for their own spawns — but only
2440
+ // when this is plausibly a launch failure: no SDK message has
2441
+ // arrived yet this turn, a path was actually attempted, and the
2442
+ // provider isn't containerised (its binary lives inside a
2443
+ // container a host-side verify can't see).
2444
+ const labeled = (!receivedAnyMessage && spawnPath && !this.constructor.capabilities?.containerized)
2445
+ ? labelBinarySpawnFailure({ attemptedPath: spawnPath, binary: 'claude' })
2446
+ : null
2447
+ // #4828: session-scoped when init has fired; falls back to module
2448
+ // `log` for pre-init query failures (e.g. spawn refused).
2449
+ ;(this._log || log).error(`Query error: ${err.message}`)
2450
+ // #8223: an auth-shaped failure carries AUTH_REQUIRED (so the clients
2451
+ // render the sign-in card) unless this turn already surfaced one from
2452
+ // the assistant message. A binary-launch label wins over classification,
2453
+ // exactly as it wins over enrichment.
2454
+ const classified = labeled ? { message: labeled } : SdkSession._classifyError(err.message)
2455
+ if (classified.code === AUTH_REQUIRED_CODE) {
2456
+ if (!authRequiredEmitted) {
2457
+ authRequiredEmitted = true
2458
+ emitTurnEvent('error', this._authRequiredPayload())
2459
+ }
2460
+ } else {
2461
+ emitTurnEvent('error', { message: classified.message })
2462
+ }
2463
+ }
1216
2464
  }
1217
2465
  }
1218
- this._clearMessageState()
2466
+ // #7376: a Stop that aborted the query leaves its in-flight tools "stopped",
2467
+ // and a CLI process that exited under the query leaves them cut off by the
2468
+ // exit; neither is a failed command. Any other throw has no considered
2469
+ // cause and keeps the generic sweep.
2470
+ if (!supersededByNewerTurn()) {
2471
+ this._clearMessageState({
2472
+ ...(wasIntentionalStop
2473
+ ? { terminatedReason: 'user_stop' }
2474
+ : isProcessExitError(err) ? { terminatedReason: 'process_exit' } : {}),
2475
+ userStop: userStopEndedTurn,
2476
+ })
2477
+ }
1219
2478
  } finally {
1220
- this._query = null
2479
+ // #8300: whatever ended the loop — the prompt's result, a throw, a
2480
+ // destroy() break — the streaming input is released here, so the SDK
2481
+ // closes the CLI's stdin and the process can exit. Idempotent; the
2482
+ // normal path already ended it in finishTurn. A still-pending notice
2483
+ // timer is dropped with the turn.
2484
+ if (noticeTimer) {
2485
+ clearTimeout(noticeTimer)
2486
+ noticeTimer = null
2487
+ }
2488
+ if (timerFinish) {
2489
+ try { await timerFinish } catch { /* logged where it was started */ }
2490
+ }
2491
+ if (input) input.end()
2492
+ if (this._turnInput === input) this._turnInput = null
2493
+ if (this._query === turnQuery) this._query = null
2494
+ // #8300: whatever this turn saw start is gone with its process.
2495
+ for (const taskId of turnTaskIds) this._liveBackgroundTasks.delete(taskId)
2496
+ // #8302: ...and so is every shell it started, whatever ended the loop (a
2497
+ // throw, a destroy, a result with no live task to report). Without this a
2498
+ // shell that died or was never acknowledged left the session reading busy
2499
+ // forever on a provider that has no `BashOutput` to clear it.
2500
+ //
2501
+ // On the normal path `finishTurn` has already stopped, reported and
2502
+ // released them. What reaches here are the abnormal exits (an AbortError, a
2503
+ // crash): ask the CLI to stop each still-tracked shell while the channel is
2504
+ // still usable, and where it is not, SAY each one is unconfirmed instead of
2505
+ // forgetting it. destroy() owns its own UX and reports nothing.
2506
+ // #8321: the drain is held until just before the flush below, whatever
2507
+ // happens here, so a send during these awaits queues behind older ones
2508
+ // instead of overtaking them.
2509
+ try {
2510
+ if (!this._destroying) {
2511
+ const leftover = turnShellsToStop()
2512
+ if (leftover.length > 0) {
2513
+ const channelUsable = !queryFailed && !queryClosed && !!turnQuery
2514
+ const results = await stopTurnShells(leftover, channelUsable)
2515
+ if (!this._destroying) reportTurnShells(results)
2516
+ }
2517
+ }
2518
+ reapTurnShells()
1221
2519
  // #4881: safety-net clear of _intentionalStop. The catch block clears
1222
2520
  // it on the throw path (AbortError after interrupt()), but if
1223
2521
  // query.interrupt() races a `result` message arriving first, the
1224
2522
  // for-await loop exits normally, skipping the catch. Without this
1225
2523
  // clear, the flag would stay armed until the next turn's catch and
1226
2524
  // mis-trigger a spurious `stopped` emit there. Idempotent — the
1227
- // catch path already cleared it on the throw path.
1228
- this._clearIntentionalStop()
2525
+ // catch path already cleared it on the throw path. Not for a
2526
+ // superseded turn: the flag is then the successor's.
2527
+ if (!supersededByNewerTurn()) this._clearIntentionalStop()
2528
+ } finally {
2529
+ // The generator has ended; a follow-up queued behind it may now run.
2530
+ if (turnDrain) this._endDrain(turnDrain)
2531
+ }
1229
2532
  // Dequeue any follow-up messages that arrived while busy (#5936: the
1230
2533
  // shared `_outgoingQueue`; flush one item via dequeueNextOutgoing, whose
1231
2534
  // re-dispatched sendMessage re-sets _isBusy so the next `result` drains
1232
2535
  // the following item — FIFO, one turn at a time).
1233
- if (this._outgoingQueue.length && !this._destroying) {
2536
+ if (this._outgoingQueue.length && !this._destroying && !supersededByNewerTurn()) {
1234
2537
  // #3562: if the SidecarProcess latched stdin_disabled mid-turn (e.g.
1235
2538
  // the PassThrough closed while _callQuery was still streaming), the
1236
2539
  // entry-gate at the top of sendMessage has already been bypassed
@@ -1265,6 +2568,111 @@ export class SdkSession extends BaseSession {
1265
2568
  return query(queryArgs)
1266
2569
  }
1267
2570
 
2571
+ /**
2572
+ * #8300: the turn's streaming input — an async iterable that yields the
2573
+ * prompt's user message once and then stays open until `end()` is called.
2574
+ *
2575
+ * The Agent SDK decides when to close the CLI's stdin from the SHAPE of
2576
+ * `prompt`: a string marks the query single-turn and stdin closes at the
2577
+ * first `result`; an iterable keeps stdin open until the iterable ends. The
2578
+ * turn therefore owns the close: `finishTurn` ends the iterable once the
2579
+ * result that answers the prompt has been processed, and `sendMessage`'s
2580
+ * `finally` ends it on every other exit so the CLI is never left waiting.
2581
+ *
2582
+ * @param {object} userMessage - the SDKUserMessage to send
2583
+ * @returns {{ iterable: AsyncIterable<object>, end: () => void, readonly ended: boolean }}
2584
+ */
2585
+ _createTurnInput(userMessage) {
2586
+ let release
2587
+ const released = new Promise((resolve) => { release = resolve })
2588
+ let ended = false
2589
+ const end = () => {
2590
+ if (ended) return
2591
+ ended = true
2592
+ release()
2593
+ }
2594
+ const iterable = (async function* () {
2595
+ yield userMessage
2596
+ await released
2597
+ })()
2598
+ return {
2599
+ iterable,
2600
+ end,
2601
+ get ended() { return ended },
2602
+ }
2603
+ }
2604
+
2605
+ /**
2606
+ * #8300: background work the CLI reported as started and never closed. Read
2607
+ * at the prompt's result; anything still here would outlive the turn's
2608
+ * process.
2609
+ *
2610
+ * @returns {Array<{taskId:string,toolUseId:string|null,taskType:string,description:string,background:boolean}>}
2611
+ */
2612
+ _liveBackgroundWork() {
2613
+ // A `local_bash` task whose shell the tool_result announced ("Command
2614
+ // running in background with ID: <id>", tracked by
2615
+ // `_recordBackgroundShellsFromToolResults`) is background work whatever
2616
+ // `task_started` said: a foreground Bash never produces that text. This
2617
+ // keeps shell detection working if a CLI build stops sending the
2618
+ // undocumented `is_backgrounded` field on `task_started`.
2619
+ return [...this._liveBackgroundTasks.values()].filter((task) =>
2620
+ task.background === true ||
2621
+ (task.taskType === 'local_bash' && this._pendingBackgroundShells.has(task.taskId)))
2622
+ }
2623
+
2624
+ // #8300: bound on `Query.stopTask()` at the turn's result. The CLI answers
2625
+ // the control request in milliseconds when alive; the cap only bites when
2626
+ // it is already gone, in which case the task is reported as not stopped.
2627
+ static STOP_TASK_TIMEOUT_MS = 3000
2628
+ // #8321: how long a follow-up may wait behind a previous query's generator
2629
+ // that is still draining after the turn's result, before that query is
2630
+ // closed, and the further grace after the close before the hold is dropped.
2631
+ static DRAIN_WAIT_MS = 10000
2632
+ static DRAIN_FORCE_GRACE_MS = 3000
2633
+
2634
+ /**
2635
+ * #8300: ask the CLI to stop a task that would outlive the turn, via the
2636
+ * SDK's `stopTask` control request. Resolves true when the CLI acknowledged
2637
+ * the stop, false when the query has no `stopTask`, it threw, or it did not
2638
+ * answer within STOP_TASK_TIMEOUT_MS. Never throws.
2639
+ *
2640
+ * @param {object|null} q - the turn's own query handle
2641
+ * @param {string} taskId
2642
+ * @returns {Promise<boolean>}
2643
+ */
2644
+ async _stopLiveTask(q, taskId) {
2645
+ if (!q || typeof q.stopTask !== 'function') return false
2646
+ let timer = null
2647
+ try {
2648
+ const timeout = new Promise((resolve) => {
2649
+ timer = setTimeout(() => resolve(false), SdkSession.STOP_TASK_TIMEOUT_MS)
2650
+ })
2651
+ const ok = await Promise.race([q.stopTask(taskId).then(() => true), timeout])
2652
+ if (!ok) (this._log || log).warn(`stopTask(${taskId}) did not answer within ${SdkSession.STOP_TASK_TIMEOUT_MS}ms`)
2653
+ return ok === true
2654
+ } catch (err) {
2655
+ ;(this._log || log).warn(`stopTask(${taskId}) failed: ${err?.message || err}`)
2656
+ return false
2657
+ } finally {
2658
+ if (timer) clearTimeout(timer)
2659
+ }
2660
+ }
2661
+
2662
+ /**
2663
+ * #7599 — hook for a containerized subclass to classify a turn failure as a
2664
+ * vanished container. Called from the query catch before the generic error
2665
+ * surface. The base in-process SdkSession has no container, so it never
2666
+ * classifies a failure this way.
2667
+ *
2668
+ * @param {Error} _err the error the query threw
2669
+ * @returns {Promise<{code:string,message:string,recoverable?:boolean}|null>}
2670
+ * a session-error payload to emit instead of the generic one, or null
2671
+ */
2672
+ async _classifyContainerFailure(_err) {
2673
+ return null
2674
+ }
2675
+
1268
2676
  /**
1269
2677
  * #6769: fetch the end-of-turn context-window OCCUPANCY snapshot from the
1270
2678
  * SDK's `getContextUsage()` control API (verified on
@@ -1501,10 +2909,39 @@ export class SdkSession extends BaseSession {
1501
2909
  ;(this._log || log).warn(`Tool input for ${block.name} exceeded ${this._maxToolInput} bytes, skipping`)
1502
2910
  this.emit('error', {
1503
2911
  message: `Tool input too large (>${Math.round(this._maxToolInput / 1024)}KB) for ${block.name} — tool use was skipped`,
2912
+ declarationTurnId: messageId,
1504
2913
  })
1505
2914
  return
1506
2915
  }
1507
2916
 
2917
+ // #7346: backfill the finalized input onto the in-flight tool_start
2918
+ // tracking entry (`_trackToolStart` / base-session.js
2919
+ // `_recordToolInput`, which sanitizes + size-caps it — see
2920
+ // #8135/#8136) so `tool-result.js`'s `emitToolResults` can attach it
2921
+ // to the matching `tool_result` (`_getTrackedToolInput`). Runs for
2922
+ // EVERY tool_use block, not just the Task/plan-mode ones handled
2923
+ // below: the full "assistant" message this function is called from
2924
+ // always carries the complete `block.input`, so (unlike CliSession,
2925
+ // which must accumulate `input_json_delta` chunks) no buffering is
2926
+ // needed. Mirrors the `${messageId}-tool` fallback `buildToolStartData`
2927
+ // uses (and the Task branch below reuses) so the id always matches
2928
+ // whatever `_trackToolStart` was called with at `content_block_start`.
2929
+ const toolUseId = block.id || `${messageId}-tool`
2930
+ const sanitizedInput = this._recordToolInput(toolUseId, block.input ?? null)
2931
+ // #8135 (review): deliver the SANITIZED input as a single-shot
2932
+ // `tool_input_delta` here — this is the earliest point SdkSession
2933
+ // knows the full value, milliseconds after the block finalized and
2934
+ // well before the tool finishes executing. `null`/`undefined` means
2935
+ // "known to have no input" (the placeholder logic covers that on
2936
+ // its own); don't ship a literal "null" chunk for it.
2937
+ if (sanitizedInput !== null && sanitizedInput !== undefined) {
2938
+ this.emit('tool_input_delta', {
2939
+ messageId,
2940
+ toolUseId,
2941
+ partialJson: JSON.stringify(sanitizedInput),
2942
+ })
2943
+ }
2944
+
1508
2945
  // #4307: stash the command text against the tool_use_id so the
1509
2946
  // matching tool_result (carrying the shellId Claude prints) can
1510
2947
  // recover it. Strict-boolean run_in_background check; non-Bash
@@ -1537,18 +2974,34 @@ export class SdkSession extends BaseSession {
1537
2974
  // agent_spawned toolUseId + _activeAgents key match the wire-emitted
1538
2975
  // tool_start id. Without this, _activeAgents.set(undefined, ...)
1539
2976
  // collides on undefined for any fallback-path Task spawn.
1540
- const toolUseId = block.id || `${messageId}-tool`
1541
- const agentInfo = {
2977
+ // (#7346: reuses the same `toolUseId` computed above — one fallback
2978
+ // derivation, not two.)
2979
+ // #7340: this records the MODEL'S REQUEST (`run_in_background`) into
2980
+ // `background`. It does NOT exempt the agent from the turn-end sweep —
2981
+ // `backgroundConfirmed` does, and only `task_started` can set that.
2982
+ // (On this provider nothing is exempted at all; see the `result` branch.)
2983
+ // Whichever signal lands first wins via `_trackAgent`'s upgrade.
2984
+ this._trackAgent({
1542
2985
  toolUseId,
1543
2986
  description: semantics.payload.description,
1544
- startedAt: Date.now(),
1545
- }
1546
- this._activeAgents.set(toolUseId, agentInfo)
1547
- this.emit('agent_spawned', agentInfo)
2987
+ background: semantics.payload.background,
2988
+ })
2989
+ }
2990
+ // #8153: EnterPlanMode / ExitPlanMode wiring, mirroring CliSession's
2991
+ // _applyToolInputSemantics. `permissionMode: 'plan'` is a literal
2992
+ // `--permission-mode plan` pass-through to the same `claude` CLI binary
2993
+ // CliSession spawns (query() execs `pathToClaudeCodeExecutable`, #7986),
2994
+ // so the native read-only enforcement and EnterPlanMode/ExitPlanMode tool
2995
+ // calls are identical on both providers — only the event wiring was
2996
+ // missing here. Unlike CliSession (which buffers `toolInputChunks` across
2997
+ // stream deltas), SdkSession receives the full `block.input` directly, so
2998
+ // there is no overflow-discard case to special-case.
2999
+ if (semantics.kind === 'enter_plan') {
3000
+ this._inPlanMode = true
3001
+ this.emit('plan_started')
3002
+ } else if (semantics.kind === 'exit_plan') {
3003
+ this._planAllowedPrompts = semantics.payload.allowedPrompts
1548
3004
  }
1549
- // EnterPlanMode / ExitPlanMode are not currently surfaced by SdkSession
1550
- // (plan-mode flow is CliSession-only today). Extracting via the shared
1551
- // parser leaves the door open without changing observable behavior.
1552
3005
  }
1553
3006
 
1554
3007
  /**
@@ -1562,9 +3015,11 @@ export class SdkSession extends BaseSession {
1562
3015
  * (no-op) — the standard tool-loop flow always populates both.
1563
3016
  *
1564
3017
  * @param {unknown} content
3018
+ * @param {Set<string>|null} [ownedShellIds] - #8302: the calling turn's set;
3019
+ * every shell newly tracked here is added to it.
1565
3020
  * @private
1566
3021
  */
1567
- _recordBackgroundShellsFromToolResults(content) {
3022
+ _recordBackgroundShellsFromToolResults(content, ownedShellIds = null) {
1568
3023
  if (!Array.isArray(content)) return
1569
3024
  for (const block of content) {
1570
3025
  if (block?.type !== 'tool_result' || !block.tool_use_id) continue
@@ -1586,7 +3041,8 @@ export class SdkSession extends BaseSession {
1586
3041
  // #5177: capture the output file path from the same tool_result so the
1587
3042
  // completion sweep can reap the shell on quiescence without a poll.
1588
3043
  const outputPath = parseBackgroundShellOutputPath(text)
1589
- this.trackBackgroundShell({ shellId, command, outputPath })
3044
+ // #8302: remember which turn started it, so that turn's end can release it.
3045
+ if (this.trackBackgroundShell({ shellId, command, outputPath })) ownedShellIds?.add(shellId)
1590
3046
  }
1591
3047
  }
1592
3048
 
@@ -1594,16 +3050,146 @@ export class SdkSession extends BaseSession {
1594
3050
  * In-process permission handler for canUseTool callback.
1595
3051
  * Delegates to the PermissionManager.
1596
3052
  */
1597
- _handlePermission(toolName, input, signal, suggestions) {
1598
- return this._permissions.handlePermission(toolName, input, signal, this.permissionMode, suggestions)
3053
+ _handlePermission(toolName, input, signal, suggestions, toolUseId = undefined) {
3054
+ return this._trackPermissionDecision(
3055
+ toolUseId,
3056
+ this._permissions.handlePermission(toolName, input, signal, this.permissionMode, suggestions, toolUseId),
3057
+ )
3058
+ }
3059
+
3060
+ /**
3061
+ * #8363: follow a permission decision from the moment the provider asks until
3062
+ * it settles, so `interrupt()` knows which tool calls Stop caught mid-prompt.
3063
+ * Passes the decision through unchanged. An `allow` removes the call from the
3064
+ * stopped set again: if the user approved it in the instant between Stop and
3065
+ * the abort, the tool may run and its result is a real one.
3066
+ * @param {string|undefined} toolUseId
3067
+ * @param {Promise<{behavior: string}>} decision
3068
+ * @returns {Promise<{behavior: string}>}
3069
+ */
3070
+ _trackPermissionDecision(toolUseId, decision) {
3071
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) return decision
3072
+ this._pendingPermissionToolUseIds.add(toolUseId)
3073
+ const settled = (result) => {
3074
+ this._pendingPermissionToolUseIds.delete(toolUseId)
3075
+ if (result?.behavior === 'deny' && typeof result.message === 'string' && result.message.trim()) {
3076
+ this._deniedToolMessages.set(toolUseId, result.message.trim())
3077
+ } else {
3078
+ this._deniedToolMessages.delete(toolUseId)
3079
+ }
3080
+ if (result?.behavior === 'allow') {
3081
+ this._stopCancelledToolUseIds.delete(toolUseId)
3082
+ this._stopResolvedToolUseIds.delete(toolUseId)
3083
+ } else if (!this._stopResolvedToolUseIds.has(toolUseId)) {
3084
+ // #8430: settled by something other than the Stop (the user's Deny, a
3085
+ // timeout, a rule): the tool row keeps that decision's own reading.
3086
+ this._stopCancelledToolUseIds.delete(toolUseId)
3087
+ }
3088
+ }
3089
+ return Promise.resolve(decision).then(
3090
+ (result) => { settled(result); return result },
3091
+ (err) => { settled(undefined); throw err },
3092
+ )
3093
+ }
3094
+
3095
+ /**
3096
+ * #8936: the user-facing text for a provider `tool_result` that is a refusal,
3097
+ * or undefined. Consulted by `emitToolResults` for every result block.
3098
+ *
3099
+ * Keyed on this session's own decision: an error block whose tool_use id has a
3100
+ * recorded denial shows that denial's message, whatever wording the CLI chose.
3101
+ * Without a record, only a block that reads as one of the CLI's refusals gets
3102
+ * the generic sentence; any other error (a real tool failure) is untouched. A
3103
+ * non-error block never consumes the record.
3104
+ * @param {string} toolUseId
3105
+ * @param {{is_error?: boolean}} block
3106
+ * @returns {string|undefined}
3107
+ */
3108
+ _deniedTextForToolResult(toolUseId, block) {
3109
+ if (block?.is_error !== true) return undefined
3110
+ const text = toolResultText(block)
3111
+ const message = this._deniedToolMessages.get(toolUseId)
3112
+ if (message !== undefined) {
3113
+ this._deniedToolMessages.delete(toolUseId)
3114
+ if (!isSdkToolRejectionText(text)) {
3115
+ ;(this._log || log).warn(
3116
+ `Denied ${toolUseId} came back with an unrecognised refusal text: ${text.trim().split('\n')[0].slice(0, 120)}`,
3117
+ )
3118
+ }
3119
+ return message
3120
+ }
3121
+ return isSdkToolRejectionText(text) ? SDK_DENIED_FALLBACK_TEXT : undefined
3122
+ }
3123
+
3124
+ /**
3125
+ * #8363: the termination reason for a provider `tool_result`, or undefined.
3126
+ * Consulted by `emitToolResults` for every result block. A result is a Stop's
3127
+ * when the call's permission prompt was still pending at the moment Stop was
3128
+ * pressed and the provider's block is an error (the denial it wrote itself).
3129
+ * Single-use: the id is dropped on the way out.
3130
+ * @param {string} toolUseId
3131
+ * @param {{is_error?: boolean}} block
3132
+ * @returns {string|undefined}
3133
+ */
3134
+ _terminatedReasonForToolResult(toolUseId, block) {
3135
+ this._stopResolvedToolUseIds.delete(toolUseId)
3136
+ if (!this._stopCancelledToolUseIds.delete(toolUseId)) return undefined
3137
+ return block?.is_error === true ? 'user_stop_before_run' : undefined
3138
+ }
3139
+
3140
+ /**
3141
+ * SDK PreToolUse bridge for Auto turns (#7825). The hook contract supplies
3142
+ * the same tool name/input that canUseTool receives, but its response uses
3143
+ * hookSpecificOutput rather than PermissionResult.
3144
+ */
3145
+ async _handleAutoPreToolUse(hookInput, signal, hookToolUseId = undefined) {
3146
+ const toolName = hookInput?.tool_name
3147
+ const input = hookInput?.tool_input
3148
+ if (typeof toolName !== 'string' || !input || typeof input !== 'object' || Array.isArray(input)) {
3149
+ return {
3150
+ continue: true,
3151
+ hookSpecificOutput: {
3152
+ hookEventName: 'PreToolUse',
3153
+ permissionDecision: 'deny',
3154
+ permissionDecisionReason: 'Malformed tool request',
3155
+ },
3156
+ }
3157
+ }
3158
+
3159
+ // #8336: the provider's id for this tool call -- the hook's second argument,
3160
+ // else the same id on the hook payload.
3161
+ const toolUseId = typeof hookToolUseId === 'string' && hookToolUseId.length > 0
3162
+ ? hookToolUseId
3163
+ : hookInput?.tool_use_id
3164
+ // This callback is the only gate on an Auto turn (the SDK itself runs in
3165
+ // bypassPermissions), and a callback that rejects gives the SDK no decision.
3166
+ // So a permission check that throws, or whose promise rejects, becomes a
3167
+ // deny RESULT here, before it is tracked: it then goes through the same
3168
+ // bookkeeping as any other deny (the tool row shows this reason).
3169
+ const check = (async () => this._permissions.handlePermission(toolName, input, signal, this.permissionMode, undefined, toolUseId))()
3170
+ .catch((err) => {
3171
+ ;(this._log || log).warn(`Auto-mode permission check failed for ${toolName}; denying: ${err?.message || err}`)
3172
+ return { behavior: 'deny', message: 'Chroxy could not complete the permission check for this tool call. Failing closed (denied).' }
3173
+ })
3174
+ const result = await this._trackPermissionDecision(toolUseId, check)
3175
+ const allow = result?.behavior === 'allow'
3176
+ return {
3177
+ continue: true,
3178
+ hookSpecificOutput: {
3179
+ hookEventName: 'PreToolUse',
3180
+ permissionDecision: allow ? 'allow' : 'deny',
3181
+ ...(allow && result.updatedInput ? { updatedInput: result.updatedInput } : {}),
3182
+ ...(!allow ? { permissionDecisionReason: result?.message || 'Permission denied' } : {}),
3183
+ },
3184
+ }
1599
3185
  }
1600
3186
 
1601
3187
  /**
1602
3188
  * Resolve a pending permission request (called by WsServer when
1603
3189
  * the app sends permission_response).
1604
3190
  */
1605
- respondToPermission(requestId, decision, editedInput, reason) {
1606
- return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
3191
+ respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy) {
3192
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
1607
3193
  }
1608
3194
 
1609
3195
  /**
@@ -1611,8 +3197,9 @@ export class SdkSession extends BaseSession {
1611
3197
  * In SDK mode, the canUseTool callback is holding a Promise open.
1612
3198
  * This method resolves it with the user's answer as structured updatedInput.
1613
3199
  */
1614
- respondToQuestion(text, answersMap) {
1615
- this._permissions.respondToQuestion(text, answersMap)
3200
+ respondToQuestion(text, answersMap, toolUseId) {
3201
+ // #8460: the id lets the manager refuse an answer meant for a different question.
3202
+ return this._permissions.respondToQuestion(text, answersMap, toolUseId)
1616
3203
  }
1617
3204
 
1618
3205
  /**
@@ -1622,15 +3209,29 @@ export class SdkSession extends BaseSession {
1622
3209
  _onModelChanged() {
1623
3210
  // #4828: session-scoped when init has fired.
1624
3211
  ;(this._log || log).info(`Model changed to ${this.model || 'default'}`)
3212
+ // #8700: the level was chosen against the PREVIOUS model's roster. One the
3213
+ // new model does not offer would reach `--effort` anyway and be silently
3214
+ // downgraded (or, for a budget level, ignored), so it goes back to the
3215
+ // model default, announced rather than kept on a header it no longer
3216
+ // describes. Whatever was reported belonged to the old model too: with no
3217
+ // level of our own, Claude Code applies the effort saved for the NEW model
3218
+ // (`modelSettings.<model>.effortLevel`), so it is unknown until the next
3219
+ // turn reports it.
3220
+ let reason = 'the model changed; the effort is reported when the next turn starts'
3221
+ const dropped = this._thinkingLevel
3222
+ if (dropped && !this._offeredThinkingLevels().includes(dropped)) {
3223
+ this._thinkingLevel = null
3224
+ reason = `the model changed and ${this.model || 'the default model'} does not offer ${dropped}, so the session is back on the model default`
3225
+ }
3226
+ this._forgetEffortReport()
3227
+ this.emit('thinking_level_changed', { reason })
1625
3228
  }
1626
3229
 
1627
3230
  _onPermissionModeChanged(mode) {
1628
3231
  this._permissions.clearRules()
1629
- // #3729: switching TO auto is a "panic button" — drain any pending
1630
- // permission prompts so the user isn't left staring at modals after
1631
- // declaring "approve everything". Without this, prompts that were
1632
- // emitted under the previous mode hang until the user resolves them
1633
- // or they hit the 5-min timeout, contradicting the bypass semantics.
3232
+ // #3729: switching TO auto drains ordinary pending permission prompts so
3233
+ // the user isn't left staring at stale modals. PermissionManager preserves
3234
+ // protected-path prompts because the floor still applies in Auto.
1634
3235
  if (mode === 'auto') {
1635
3236
  this._permissions.autoAllowPending()
1636
3237
  }
@@ -1692,25 +3293,200 @@ export class SdkSession extends BaseSession {
1692
3293
  }
1693
3294
 
1694
3295
  /**
1695
- * Set thinking level by adjusting max thinking tokens.
1696
- * @param {string} level - 'default' | 'high' | 'max'
3296
+ * Set the session's thinking level: Claude Code's effort for a model that
3297
+ * has one, the legacy `maxThinkingTokens` budget for one that predates it
3298
+ * (#8700, `_thinkingOptions`). Never rejects: the per-model membership
3299
+ * decision belongs to the `set_thinking_level` handler, which knows the
3300
+ * session's model (#7730).
3301
+ *
3302
+ * Between turns the level simply rides on the next turn's `query()`
3303
+ * options, and the last report is dropped: it described a turn that ran at
3304
+ * the old level. Mid-turn the running process is asked to switch (the flag
3305
+ * settings layer for an effort, `setMaxThinkingTokens` for a budget) and then
3306
+ * asked what it now applies, so the reported level is the CLI's answer, not
3307
+ * this method's hope — `max` cannot be set that way (Claude Code's settings
3308
+ * do not take it) and reaches the CLI at the next turn.
3309
+ * @param {string} level
1697
3310
  */
1698
3311
  async setThinkingLevel(level) {
3312
+ this._thinkingLevel = level === LEGACY_DEFAULT_THINKING_LEVEL ? null : level
3313
+ // Invalidate pending reads and the previous answer before any live setter
3314
+ // can yield. Even Auto, Max and budget-only changes leave that answer behind.
3315
+ this._forgetEffortReport()
3316
+ // Note: thinking_level_changed is broadcast by the WS handler, not emitted here
3317
+ const query = this._query
3318
+ const turnSeq = this._turnSeq
3319
+ const epoch = this._effortEpoch
3320
+ if (!query) return
3321
+
3322
+ // The same choice `_thinkingOptions` makes for the next turn, made live:
3323
+ // the effort is set when the next turn would send one, and cleared at
3324
+ // Auto; the budget is set when the next turn would send one, and cleared
3325
+ // at Auto or where the model reads no effort (a level with no budget then
3326
+ // means none). An unknown model gets both, as its next turn will. Each
3327
+ // setter fails on its own, so one the CLI refuses cannot keep the other
3328
+ // from landing, and the report is asked for last.
3329
+ const opts = this._thinkingOptions()
3330
+ const setsEffort = opts.effort !== undefined || !this._thinkingLevel
3331
+ const setsBudget = opts.effort === undefined || opts.maxThinkingTokens !== undefined
3332
+ const asksEffort = setsEffort && this._thinkingLevel !== 'max' && typeof query.applyFlagSettings === 'function'
3333
+ if (asksEffort) {
3334
+ try {
3335
+ await query.applyFlagSettings({ effortLevel: this._thinkingLevel })
3336
+ } catch (err) {
3337
+ ;(this._log || log).warn(`Failed to apply effort ${level ?? 'default (cleared)'} to the running turn: ${err?.message || err}`)
3338
+ }
3339
+ }
3340
+ if (setsBudget && typeof query.setMaxThinkingTokens === 'function') {
3341
+ try {
3342
+ await query.setMaxThinkingTokens(opts.maxThinkingTokens ?? null)
3343
+ } catch (err) {
3344
+ ;(this._log || log).warn(`Failed to apply the thinking budget for ${level ?? 'default (cleared)'} to the running turn: ${err?.message || err}`)
3345
+ }
3346
+ }
3347
+ // Capture ownership before the setters await: an older continuation must
3348
+ // not start a read under a newer setting, model, turn or query's identity.
3349
+ if (asksEffort && this._query === query && this._turnSeq === turnSeq && this._effortEpoch === epoch) {
3350
+ try {
3351
+ await this._readEffectiveEffort('after a mid-turn change')
3352
+ } catch (err) {
3353
+ ;(this._log || log).warn(`Effort report failed: ${err?.message || err}`)
3354
+ }
3355
+ }
3356
+ }
3357
+
3358
+ /**
3359
+ * #8700 — the levels the session's current model offers, by the SAME
3360
+ * resolution the `set_thinking_level` gate and the dashboard picker use (the
3361
+ * model's roster row, else the legacy triple: SdkSession is Claude-family),
3362
+ * so a model switch keeps exactly the levels the gate would accept.
3363
+ * @returns {string[]}
3364
+ */
3365
+ _offeredThinkingLevels() {
3366
+ const modelId = this.model || this.bootedModel
3367
+ let row = null
3368
+ try {
3369
+ row = modelId ? getRosterModelRow(this._provider, modelId) : null
3370
+ } catch (err) {
3371
+ ;(this._log || log).warn(`Thinking-level roster lookup failed for model '${modelId}': ${err?.message || err}`)
3372
+ }
3373
+ return resolveThinkingLevels(row, { legacyFallback: true }).levels
3374
+ }
3375
+
3376
+ /**
3377
+ * #8700 — does `modelId` take Claude Code's effort, a token budget, or is
3378
+ * that not known yet? The SDK's own `supportedModels()` answer for this
3379
+ * session comes first; failing that, a roster row that advertises levels
3380
+ * (stamped from that same answer by any session, and kept across restarts
3381
+ * in the models cache) means effort.
3382
+ * @returns {'effort'|'budget'|'unknown'}
3383
+ */
3384
+ _effortSupportFor(modelId) {
3385
+ const heard = this._modelEffortSupport.get(modelId || SDK_DEFAULT_MODEL_ALIAS)
3386
+ if (heard) return heard
3387
+ let row = null
3388
+ try {
3389
+ row = modelId ? getRosterModelRow(this._provider, modelId) : null
3390
+ } catch {
3391
+ row = null
3392
+ }
3393
+ return Array.isArray(row?.reasoningLevels) && row.reasoningLevels.length > 0 ? 'effort' : 'unknown'
3394
+ }
3395
+
3396
+ /**
3397
+ * #8700 — the per-turn `query()` options for the session's level.
3398
+ *
3399
+ * An adaptive model (every current one) ignores `maxThinkingTokens`, which
3400
+ * is all a level used to set, so High and Max did nothing and a session ran
3401
+ * at Claude Code's default effort whatever the header said. A level now goes
3402
+ * to such a model as `effort` (the CLI's `--effort`). A model that predates
3403
+ * effort still reads the budget, and gets it alone. When neither is known
3404
+ * yet (no model list heard and no roster row that says), the level is sent
3405
+ * as an effort — the CLI drops `--effort` on a model without it — and a
3406
+ * legacy level's budget rides along exactly as it did before #8700, for the
3407
+ * pre-adaptive model that reads only that. No level (`default`) sends
3408
+ * neither, so Claude Code applies the user's own setting for the model.
3409
+ * @returns {{effort?: string, maxThinkingTokens?: number}}
3410
+ */
3411
+ _thinkingOptions() {
3412
+ const level = this._thinkingLevel
3413
+ if (!level) return {}
1699
3414
  const budget = SdkSession.THINKING_BUDGETS[level] ?? null
1700
- this._thinkingLevel = level === 'default' ? null : level
3415
+ const support = this._effortSupportFor(this.model || this.bootedModel)
3416
+ if (support === 'budget') return budget != null ? { maxThinkingTokens: budget } : {}
3417
+ if (support === 'effort' || budget == null) return { effort: level }
3418
+ return { effort: level, maxThinkingTokens: budget }
3419
+ }
1701
3420
 
1702
- if (this._query && typeof this._query.setMaxThinkingTokens === 'function') {
3421
+ /** #8700: drop the last effort report — it described a model or level the session has left. */
3422
+ _forgetEffortReport() {
3423
+ this._effortEpoch += 1
3424
+ this._effectiveEffort = null
3425
+ this._effectiveModel = null
3426
+ this._lastEffortReport = null
3427
+ }
3428
+
3429
+ /**
3430
+ * #8700 — ask the running turn's Claude Code what it applies
3431
+ * (`get_settings` → `applied: { model, effort }`) and announce it when it
3432
+ * changed. `query.getSettings()` is in the Agent SDK's runtime, not its
3433
+ * typings; a CLI or SDK without it, or a failed request, leaves the level
3434
+ * unknown and says so once. `applied.effort: null` (a model without effort,
3435
+ * or an environment override that turns it off) is shown as unknown and is
3436
+ * NOT read as "this model takes a budget": which parameter a model reads is
3437
+ * the `supportedModels()` answer's call alone (`_effortSupportFor`).
3438
+ * @param {string} [when] - for the log line
3439
+ */
3440
+ async _readEffectiveEffort(when = 'when the turn started') {
3441
+ const readSeq = ++this._effortReadSeq
3442
+ const query = this._query
3443
+ const turnSeq = this._turnSeq
3444
+ const epoch = this._effortEpoch
3445
+ let applied = null
3446
+ let reason
3447
+ if (!query || typeof query.getSettings !== 'function') {
3448
+ reason = 'this Claude Code cannot report the effort it applies'
3449
+ } else {
1703
3450
  try {
1704
- await this._query.setMaxThinkingTokens(budget)
1705
- // #4828: session-scoped (setThinkingLevel only takes effect with
1706
- // an active query — strictly post-init).
1707
- ;(this._log || log).info(`Thinking level set to ${level} (${budget ?? 'adaptive'} tokens)`)
3451
+ applied = (await query.getSettings())?.applied ?? null
3452
+ reason = applied ? `reported by Claude Code ${when}` : 'Claude Code did not report the effort it applies'
1708
3453
  } catch (err) {
1709
- ;(this._log || log).warn(`Failed to set thinking level: ${err.message}`)
3454
+ reason = `Claude Code could not report the effort it applies (${err?.message || err})`
1710
3455
  }
1711
3456
  }
3457
+ // A report that lands after the session went away, after a newer turn
3458
+ // started (which makes its own), or after a model or level change
3459
+ // (`_forgetEffortReport`) is not this session's current answer. Within one
3460
+ // epoch only the latest read owns the answer, even when an init read races
3461
+ // the live setter's read. A latest read that lands after its own turn ended,
3462
+ // with nothing changed since, still is current.
3463
+ if (this._destroying || this._turnSeq !== turnSeq || this._effortEpoch !== epoch || this._effortReadSeq !== readSeq) return
3464
+ const effort = isWellFormedThinkingLevel(applied?.effort) ? applied.effort : null
3465
+ const model = typeof applied?.model === 'string' && applied.model.length > 0 ? applied.model : null
3466
+ if (applied && applied.effort === null) {
3467
+ reason = `Claude Code reports no effort level for ${model || 'this model'}`
3468
+ }
3469
+ this._effectiveEffort = effort
3470
+ this._effectiveModel = model
3471
+ const report = `${model}|${effort}|${applied ? 'reported' : reason}`
3472
+ if (report === this._lastEffortReport) return
3473
+ this._lastEffortReport = report
3474
+ this.emit('thinking_level_changed', { reason })
3475
+ }
1712
3476
 
1713
- // Note: thinking_level_changed is broadcast by the WS handler, not emitted here
3477
+ /**
3478
+ * #8700 — the SDK's per-model effort answer (`supportsEffort` +
3479
+ * `supportedEffortLevels`, which the CLI already narrows per model) as the
3480
+ * registry's `reasoningLevels` roster, the same translation
3481
+ * codex-model-catalog.js does for `supportedReasoningEfforts`. The model
3482
+ * default leads the list so the picker's first option is "Auto" — no effort
3483
+ * of our own, the user's saved one applies. null for a model without effort,
3484
+ * which keeps the legacy roster.
3485
+ * @param {object} modelInfo - one `supportedModels()` row
3486
+ * @returns {{reasoningLevels: string[], defaultReasoningLevel: string} | null}
3487
+ */
3488
+ static effortRoster(modelInfo) {
3489
+ return effortRoster(modelInfo)
1714
3490
  }
1715
3491
 
1716
3492
  /**
@@ -1733,7 +3509,11 @@ export class SdkSession extends BaseSession {
1733
3509
 
1734
3510
  try {
1735
3511
  const sdkModels = await this._query.supportedModels()
1736
- const converted = updateModels(sdkModels)
3512
+ // #8700: each row's effort roster rides into the registry as its
3513
+ // `reasoningLevels`; this session also remembers the per-model answer
3514
+ // for `_thinkingOptions` (see annotateSupportedModels).
3515
+ const withEffort = annotateSupportedModels(sdkModels, this._modelEffortSupport)
3516
+ const converted = updateModels(withEffort)
1737
3517
  if (converted && converted.length > 0) {
1738
3518
  // #4828: session-scoped (called from init handler so _log is set).
1739
3519
  ;(this._log || log).info(`Dynamic model list: ${converted.map(m => m.id).join(', ')}`)
@@ -1741,7 +3521,7 @@ export class SdkSession extends BaseSession {
1741
3521
  this.emit('models_updated', { models: converted })
1742
3522
  }
1743
3523
  } catch (err) {
1744
- ;(this._log || log).warn(`Failed to fetch supported models: ${err.message}`)
3524
+ ;(this._log || log).warn(`Failed to fetch supported models: ${err?.message || err}`)
1745
3525
  }
1746
3526
  }
1747
3527
 
@@ -1773,10 +3553,10 @@ export class SdkSession extends BaseSession {
1773
3553
  _finalizeAgentByToolUseId(toolUseId) {
1774
3554
  if (typeof toolUseId !== 'string' || !toolUseId) return
1775
3555
  this._taskIdByToolUseId.delete(toolUseId)
1776
- if (this._activeAgents.has(toolUseId)) {
1777
- this._activeAgents.delete(toolUseId)
1778
- this.emit('agent_completed', { toolUseId })
1779
- }
3556
+ // #7340: the agent half is BaseSession's `_completeAgent` (idempotent, and
3557
+ // the single implementation shared with CliSession and ByokSession). This
3558
+ // wrapper adds only the SDK-specific task-id mapping cleanup above.
3559
+ this._completeAgent(toolUseId)
1780
3560
  }
1781
3561
 
1782
3562
  /**
@@ -1841,13 +3621,47 @@ export class SdkSession extends BaseSession {
1841
3621
  // already settling) so an interrupt never strands a queued message.
1842
3622
  this.clearOutgoingQueue()
1843
3623
 
1844
- if (!this._query) return
3624
+ if (this._pendingDecision) {
3625
+ // A Stop while the turn is still verifying the folder: sendMessage sees the
3626
+ // cleared token and does not start the query.
3627
+ this._pendingDecision = null
3628
+ return
3629
+ }
3630
+
3631
+ if (!this._query) {
3632
+ // #8430: a Stop with nothing to interrupt -- no query yet -- and no prompt
3633
+ // open has nothing to label; do not leave it armed for the rest of the turn.
3634
+ if (!this._permissions.hasPendingPrompt()) this._permissions.clearUserStopInFlight()
3635
+ return
3636
+ }
1845
3637
 
1846
3638
  // #4881: mark the imminent query teardown as user-initiated so the
1847
3639
  // _callQuery catch block suppresses the AbortError-flavored "Query error"
1848
3640
  // emit and instead surfaces a quiet `stopped` event. Cleared in the
1849
3641
  // catch/finally (single-use, mirrors CliSession#4602).
1850
3642
  this.markIntentionalStop()
3643
+ this._noteTurnStopRequested() // #7376
3644
+ // #8363: every permission prompt still waiting is about to be resolved by the
3645
+ // abort, not by the user. Snapshot them BEFORE the abort -- the SDK writes the
3646
+ // tool_result for each as soon as it sees the interrupt, which can be before
3647
+ // this session's abort listeners have run.
3648
+ //
3649
+ // #8430: only for a USER Stop. Any other interrupt (an orchestration deadline,
3650
+ // the scheduler) is not one, and its prompts' rows must not read as the user's
3651
+ // doing. The mark is provisional: the prompt's own resolution confirms it (a
3652
+ // Stop-caused one) or removes it (a Deny or timeout that won first), see
3653
+ // `_trackPermissionDecision`.
3654
+ //
3655
+ // Only a prompt that is STILL waiting. A decision delivered in this same
3656
+ // synchronous tick (the scheduler denies, then interrupts, back to back) has
3657
+ // already left the permission manager's pending state, though its id leaves
3658
+ // `_pendingPermissionToolUseIds` a microtask later; that call was refused,
3659
+ // not stopped.
3660
+ if (this._permissions.isUserStopInFlight()) {
3661
+ for (const id of this._pendingPermissionToolUseIds) {
3662
+ if (this._permissions.hasPendingForToolUse(id)) this._stopCancelledToolUseIds.add(id)
3663
+ }
3664
+ }
1851
3665
 
1852
3666
  // #4828: session-scoped (interrupt() only meaningful with an active query).
1853
3667
  ;(this._log || log).info('Interrupting query')
@@ -1916,8 +3730,11 @@ export class SdkSession extends BaseSession {
1916
3730
  // into a cleared message. Best-effort — the SDK's generator may not
1917
3731
  // support .return()/.throw() uniformly.
1918
3732
  this._abortActiveQuery()
1919
- this._clearMessageState()
1920
- this.emit('error', { message: `Response timed out after ${friendly} of inactivity` })
3733
+ this._abandonDrain() // #8321
3734
+ // #7376: name the cause so a tool left in flight reads as "the turn was
3735
+ // terminated under it", not as a failed command.
3736
+ this._clearMessageState({ terminatedReason: 'hard_timeout' })
3737
+ this.emit('error', { message: `Response timed out after ${friendly} of inactivity`, declarationTurnId: messageId })
1921
3738
  }
1922
3739
 
1923
3740
  /**
@@ -1950,10 +3767,11 @@ export class SdkSession extends BaseSession {
1950
3767
  // Attempt to abort the SDK query generator so no further events land
1951
3768
  // into a cleared message context. Best-effort — matches _handleHardTimeout.
1952
3769
  this._abortActiveQuery()
3770
+ this._abandonDrain() // #8321
1953
3771
  // #4616: snapshot sessionId BEFORE _clearMessageState wipes it so the
1954
3772
  // synthetic `result` event below carries the correct identifier.
1955
3773
  const sessionId = this._sdkSessionId || this._sessionId
1956
- this._clearMessageState()
3774
+ this._clearMessageState({ terminatedReason: 'stream_stall' }) // #7376
1957
3775
  // #4616: emit a synthetic `result` so event-normalizer fans it to
1958
3776
  // `agent_idle`. Per #4308 handleAgentIdle clears `activeTools: []`
1959
3777
  // as a safety net, which is what stops the dashboard's footer pill
@@ -1961,13 +3779,79 @@ export class SdkSession extends BaseSession {
1961
3779
  // _emitInterruptedTurnResult (stream_end + result); the SDK was
1962
3780
  // previously missing the `result` half of the pair. cost:null skips
1963
3781
  // session-manager billing accumulation (mirrors CLI).
1964
- this.emit('result', { cost: null, duration: this._streamStallTimeoutMs, usage: null, sessionId })
3782
+ const message = `Stream stalled — no response for ${friendly}. Try sending again.`
3783
+ // #7072: `interrupted` + `failureMessage` are internal (event-normalizer
3784
+ // whitelists the wire fields). An orchestration TurnDriver settles on the FIRST
3785
+ // terminal event, this result, and drops the `error` below at its epoch guard;
3786
+ // without the mark a stalled turn reads as a completed one and the caller never
3787
+ // sees TURN_ERROR. The result itself stays: it is what clears activeTools.
3788
+ this.emit('result', { cost: null, duration: this._streamStallTimeoutMs, usage: null, sessionId, interrupted: true, failureMessage: message, declarationTurnId: messageId })
1965
3789
  this.emit('error', {
1966
3790
  code: 'stream_stall',
1967
- message: `Stream stalled — no response for ${friendly}. Try sending again.`,
3791
+ message,
3792
+ declarationTurnId: messageId,
1968
3793
  })
1969
3794
  }
1970
3795
 
3796
+ /**
3797
+ * #8321: stop timing a drain and forget it. Idempotent, and a no-op for a
3798
+ * drain that is no longer the session's current one.
3799
+ */
3800
+ _endDrain(drain) {
3801
+ if (drain.waitTimer) clearTimeout(drain.waitTimer)
3802
+ if (drain.forceTimer) clearTimeout(drain.forceTimer)
3803
+ drain.waitTimer = null
3804
+ drain.forceTimer = null
3805
+ if (this._drainingTurn === drain) this._drainingTurn = null
3806
+ }
3807
+
3808
+ /**
3809
+ * #8321: a hard timeout or stream stall gives up on the query: it was told to
3810
+ * abort and is not answering, and the point of the recovery is that the next
3811
+ * send runs now. Waiting behind such a query would only add the drain bound to
3812
+ * every retry, so the hold is dropped; the abandoned loop is superseded by the
3813
+ * next turn and touches nothing of its.
3814
+ */
3815
+ _abandonDrain() {
3816
+ if (this._drainingTurn) this._endDrain(this._drainingTurn)
3817
+ }
3818
+
3819
+ /**
3820
+ * #8321: a drain has an end. Once a follow-up is waiting AND busy has cleared
3821
+ * (whichever happens last starts the clock; nothing waiting, nothing armed), the generator gets
3822
+ * `DRAIN_WAIT_MS` to finish; then its query is closed; and if even that does
3823
+ * not end it within `DRAIN_FORCE_GRACE_MS`, the hold is released anyway and
3824
+ * the next queued follow-up runs (the late loop is superseded by it, and its
3825
+ * own `finally` then touches nothing of the successor's). Without the bound
3826
+ * a generator that never ended would block the session forever.
3827
+ */
3828
+ _armDrainRelease() {
3829
+ const drain = this._drainingTurn
3830
+ if (!drain || drain.waitTimer || drain.forceTimer) return
3831
+ drain.waitTimer = setTimeout(() => {
3832
+ drain.waitTimer = null
3833
+ if (this._drainingTurn !== drain || this._destroying) return
3834
+ // The follow-up it was held for may be gone (interrupt); a lingering
3835
+ // query with nothing waiting behind it is left as it always was.
3836
+ if (this._outgoingQueue.length === 0) return
3837
+ ;(this._log || log).warn(`Previous query still draining after ${SdkSession.DRAIN_WAIT_MS}ms; closing it`)
3838
+ try {
3839
+ if (typeof drain.close === 'function') drain.close()
3840
+ else if (typeof drain.query?.close === 'function') drain.query.close()
3841
+ } catch (err) {
3842
+ ;(this._log || log).warn(`Failed to close draining query: ${err?.message || err}`)
3843
+ }
3844
+ drain.forceTimer = setTimeout(() => {
3845
+ drain.forceTimer = null
3846
+ if (this._drainingTurn !== drain || this._destroying) return
3847
+ ;(this._log || log).warn('Draining query did not end after close; releasing queued follow-ups anyway')
3848
+ this._endDrain(drain)
3849
+ if (this._query === drain.query) this._query = null
3850
+ if (this._outgoingQueue.length && !this._isBusy) this.dequeueNextOutgoing()
3851
+ }, SdkSession.DRAIN_FORCE_GRACE_MS)
3852
+ }, SdkSession.DRAIN_WAIT_MS)
3853
+ }
3854
+
1971
3855
  /**
1972
3856
  * Best-effort abort of the active SDK query generator. Used when the
1973
3857
  * session times out mid-turn so tool results don't stream into a
@@ -2038,14 +3922,35 @@ export class SdkSession extends BaseSession {
2038
3922
  /**
2039
3923
  * Clear per-message state, marking us as ready for the next message.
2040
3924
  */
2041
- _clearMessageState() {
2042
- super._clearMessageState()
2043
- this._permissions.clearAll()
3925
+ // #7340: forward the opts to super. `turnEndedCleanly` decides whether a
3926
+ // confirmed-backgrounded subagent survives BaseSession's turn-end sweep;
3927
+ // an override that drops it silently disables the exemption.
3928
+ _clearMessageState(opts) {
3929
+ // #8430: read the user Stop BEFORE the base teardown clears it. A live Stop
3930
+ // ends the turn on the generator's AbortError, so the prompts still open are
3931
+ // resolved by `clearAll()` below, not by the abort listener.
3932
+ // The teardown of a failed query passes the cause it established earlier.
3933
+ const userStop = opts?.userStop ?? this._permissions.isUserStopInFlight()
3934
+ super._clearMessageState(opts)
3935
+ this._permissions.clearAll({ userStop })
3936
+ this._deniedToolMessages.clear() // #8936
3937
+ // #8321: busy ends here, possibly with the turn's generator still alive.
3938
+ // Bound how long a follow-up can be held behind it.
3939
+ if (this._drainingTurn && !this._destroying && this._outgoingQueue.length) this._armDrainRelease()
2044
3940
  // Pause counter is tied to the previous message — reset so the next
2045
3941
  // message starts with a fresh counter.
2046
3942
  this._permissionPauseCount = 0
2047
3943
  this._resultTimeoutPaused = false
2048
3944
  this._resetResultTimeout = null
3945
+ // #8153: mirrors CliSession's stale-flag reset. If plan mode is active
3946
+ // but ExitPlanMode never arrived (interrupt/crash), the flag is stale —
3947
+ // reset it. In normal flow, _planAllowedPrompts is non-null (set by
3948
+ // ExitPlanMode) and plan_ready has already been emitted + both flags
3949
+ // reset before we reach here (see the 'result' case in _callQuery).
3950
+ if (this._inPlanMode && this._planAllowedPrompts === null) {
3951
+ this._inPlanMode = false
3952
+ }
3953
+ this._planAllowedPrompts = null
2049
3954
  }
2050
3955
 
2051
3956
  /**
@@ -2053,6 +3958,8 @@ export class SdkSession extends BaseSession {
2053
3958
  */
2054
3959
  destroy() {
2055
3960
  this._destroying = true
3961
+ this._deniedToolMessages.clear() // #8936
3962
+ if (this._drainingTurn) this._endDrain(this._drainingTurn)
2056
3963
  // #5936: tear down the shared outgoing queue silently — no message_dequeued
2057
3964
  // (which signals "sent") for a session that's going away.
2058
3965
  this.clearOutgoingQueue({ emit: false })
@@ -2077,13 +3984,32 @@ export class SdkSession extends BaseSession {
2077
3984
  this._streamStallTimeout = null
2078
3985
  }
2079
3986
 
2080
- // Interrupt active query
3987
+ // #8300: release the turn's streaming input first, so the CLI's stdin
3988
+ // closes even if the message loop never gets to observe `_destroying`
3989
+ // (it is parked on the generator's next message).
3990
+ if (this._turnInput) {
3991
+ this._turnInput.end()
3992
+ this._turnInput = null
3993
+ }
3994
+
3995
+ // Interrupt active query, then close it: with the input released an idle
3996
+ // CLI exits on its own, but one kept alive by background work would not,
3997
+ // and the parked message loop would never end (#8300).
2081
3998
  if (this._query) {
2082
- this._query.interrupt().catch((err) => {
3999
+ const q = this._query
4000
+ this._query = null
4001
+ q.interrupt().catch((err) => {
4002
+ // The close below rejects the pending interrupt ("Query closed
4003
+ // before response received"); that is the expected outcome here.
4004
+ const expected = /closed before/i.test(err?.message || '')
2083
4005
  // #4828: session-scoped when init has fired.
2084
- ;(this._log || log).warn(`Failed to interrupt active query: ${err.message} (non-critical, session destroying)`)
4006
+ ;(this._log || log)[expected ? 'debug' : 'warn'](`Failed to interrupt active query: ${err.message} (non-critical, session destroying)`)
2085
4007
  })
2086
- this._query = null
4008
+ try {
4009
+ if (typeof q.close === 'function') q.close()
4010
+ } catch (err) {
4011
+ ;(this._log || log).warn(`Failed to close query on destroy: ${err?.message || err}`)
4012
+ }
2087
4013
  }
2088
4014
 
2089
4015
  // Emit completions for any tracked agents and clear busy state