@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -1,9 +1,17 @@
1
- import { query } from '@anthropic-ai/claude-agent-sdk'
2
- import { join } from 'path'
3
- import { homedir } from 'os'
4
- import { updateModels, saveModelsCache, updateContextWindow, getModels, ALLOWED_MODEL_IDS } from './models.js'
1
+ import { assistantResponseText, sdkDeclarationEligible } from './assistant-response.js'
2
+ import { query, forkSession } from '@anthropic-ai/claude-agent-sdk'
3
+ import { claudeConfigDir } from './utils/claude-config-dir.js'
4
+ import { performance } from 'node:perf_hooks'
5
+ import { CLAUDE_BINARY_CANDIDATES, resolveClaudeBinary } from './utils/claude-binary.js'
6
+ import { labelBinarySpawnFailure } from './utils/verify-binary.js'
7
+ import { sdkClaudeCodeVersion, CLAUDE_SDK_MIN_CLI_VERSION } from './utils/agent-sdk-version.js'
8
+ import { CLAUDE_SDK_CUSTOMIZATION } from './provider-customization.js'
9
+ import { updateModels, saveModelsCache, updateContextWindow, getModels, getRosterModelRow, ALLOWED_MODEL_IDS } from './models.js'
10
+ import { isWellFormedThinkingLevel, resolveThinkingLevels, LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
11
+ import { effortRoster, annotateSupportedModels } from './claude-model-refresh.js'
5
12
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
6
- import { BaseSession, buildBaseSessionOpts } from './base-session.js'
13
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission } from './base-session.js'
14
+ import { normalizeSdkModelUsage } from './usage-normalize.js'
7
15
  import { buildContentBlocks } from './content-blocks.js'
8
16
  import { MessageTransformPipeline } from './message-transform.js'
9
17
  import { emitToolResults } from './tool-result.js'
@@ -13,16 +21,50 @@ import {
13
21
  isRunInBackgroundInput,
14
22
  parseBashOutputShellId,
15
23
  } from './background-shells.js'
16
- import { buildToolStartData, extractToolInputSemantics } from './claude-stream-parser.js'
24
+ import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent, formatStatusContent } from './claude-stream-parser.js'
17
25
  import { createLogger, loggerForSession } from './logger.js'
18
26
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
19
27
  import { formatBytes } from './utils/format-bytes.js'
20
28
  import { formatIdleDuration } from './session-timeout-manager.js'
21
29
  import { detectThinkingKeyword } from './detect-thinking-keyword.js'
22
30
  import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
31
+ import { CLAUDE_LOGIN_COMMAND } from './utils/claude-login-command.js'
32
+ import { buildSpawnEnv } from './utils/spawn-env.js'
33
+ import { classifyAuthCause } from './utils/auth-cause.js'
34
+ import { turnOutcomeField, outcomeFromSdkResult } from './turn-outcome.js'
23
35
 
24
36
  const log = createLogger('sdk')
25
37
 
38
+ /**
39
+ * #8700: the `value` the Agent SDK's `supportedModels()` gives the row for the
40
+ * CLI's own default model — what a session with no model of its own runs. A
41
+ * model alias, unrelated to the thinking level that happens to share the word.
42
+ */
43
+ const SDK_DEFAULT_MODEL_ALIAS = 'default'
44
+
45
+ // #8223: an authentication failure is surfaced with this code so the clients can
46
+ // render a "sign in" card instead of a raw error line. Same wire code claude-tui
47
+ // emits (claude-tui/pty-driver.js AUTH_REQUIRED_CODE) — kept as a local literal
48
+ // because that module resolves the claude binary at import time, which this one
49
+ // must not do.
50
+ const AUTH_REQUIRED_CODE = 'AUTH_REQUIRED'
51
+ // The SDK reads credentials from ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN or a
52
+ // prior `claude auth login`, and nothing at the point of failure says which one
53
+ // this host meant to use — so the message covers both.
54
+ 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.`
55
+ // A containerised session has no login command to run (see
56
+ // DockerSdkSession.preflight): its credentials are the container's env.
57
+ const AUTH_REQUIRED_CONTAINER_MESSAGE = 'Claude authentication failed inside the session container. Check that ANTHROPIC_API_KEY is set for it, then retry.'
58
+ // #8273: the session authenticates with ANTHROPIC_API_KEY, so a host login is not
59
+ // the fix. Never interpolates the key.
60
+ 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.'
61
+ // #8970: the other mechanisms a session can authenticate through. "Log in" is the
62
+ // wrong advice for each of them, and none of these messages carries a value.
63
+ 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.'
64
+ 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.'
65
+ 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.'
66
+ 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.'
67
+
26
68
  /**
27
69
  * Manages a Claude Code session using the Agent SDK.
28
70
  *
@@ -88,12 +130,159 @@ export const STDIN_DROPPED_ESCALATION_EVERY_N = 10
88
130
  // stuck") with noise control.
89
131
  export const REFUSED_SENDMESSAGE_WARN_INTERVAL_MS = 30 * 1000
90
132
 
133
+ // #8300: the text Claude Code writes into a tool_result when IT cancelled the
134
+ // tool call — the turn had no permission/hook channel left — rather than
135
+ // relaying a decision from this session's PermissionManager. A decision made
136
+ // here always reaches the CLI with chroxy's own reason text, so a tool_result
137
+ // that starts with one of these can only mean the control channel was gone
138
+ // (stdin closed under the CLI, or its permission request stream aborted). The
139
+ // second prefix is the Approve-mode spelling (`canUseTool` could not be asked:
140
+ // "Tool permission request failed: AbortError: Stream closed"). Matched by
141
+ // prefix; the CLI appends nothing stable after the sentence.
142
+ export const SDK_TOOL_CANCELLED_PREFIXES = [
143
+ "The user doesn't want to take this action right now.",
144
+ 'Tool permission request failed:',
145
+ ]
146
+
147
+ // #8936: the sentences Claude Code writes into the error tool_result of a tool
148
+ // that was refused. They address the model ("STOP what you are doing and wait
149
+ // for the user to tell you how to proceed"), so they are never shown to the
150
+ // user. A refusal this session decided is recognised by its tool_use id, not by
151
+ // this wording (the CLI has several spellings and changes them); the prefixes
152
+ // are only the fallback for a refusal block with no decision on record, and the
153
+ // check that makes an unexpected spelling visible in the log.
154
+ export const SDK_TOOL_REJECTED_PREFIXES = [
155
+ "The user doesn't want to proceed with this tool use.",
156
+ 'Permission for this tool use was denied.',
157
+ 'Permission for this action has been denied.',
158
+ ]
159
+
160
+ // Shown when a refusal is recognised but no decision of this session carries a
161
+ // sentence of its own (a refusal the CLI made from its own settings).
162
+ export const SDK_DENIED_FALLBACK_TEXT = 'Tool use was denied.'
163
+
164
+ /**
165
+ * #8936: is this tool_result text one of Claude Code's model-facing refusals?
166
+ * @param {unknown} text
167
+ * @returns {boolean}
168
+ */
169
+ export function isSdkToolRejectionText(text) {
170
+ if (typeof text !== 'string') return false
171
+ const trimmed = text.trimStart()
172
+ return SDK_TOOL_REJECTED_PREFIXES.some((prefix) => trimmed.startsWith(prefix))
173
+ }
174
+
175
+ /**
176
+ * #8300: does this tool_result text mean Claude Code cancelled the tool call
177
+ * itself, without consulting chroxy's permission pipeline?
178
+ * @param {unknown} text
179
+ * @returns {boolean}
180
+ */
181
+ export function isSdkToolCancellationText(text) {
182
+ if (typeof text !== 'string') return false
183
+ const trimmed = text.trimStart()
184
+ return SDK_TOOL_CANCELLED_PREFIXES.some((prefix) => trimmed.startsWith(prefix))
185
+ }
186
+
187
+ /**
188
+ * #7376: did the Claude CLI process die under the query (a crash or an external
189
+ * kill) rather than the query ending on its own? Distinct from
190
+ * {@link isQueryCloseError}, which is a DELIBERATE close.
191
+ * @param {unknown} err
192
+ * @returns {boolean}
193
+ */
194
+ export function isProcessExitError(err) {
195
+ if (!err) return false
196
+ const text = typeof err.message === 'string' ? err.message : String(err)
197
+ // The SDK transport's two shapes for a CLI process that died under the query
198
+ // (sdk.mjs: `Claude Code process exited with code ${code}` and
199
+ // `Claude Code process terminated by signal ${signal}`), ANCHORED to the start
200
+ // of the message so an unrelated error that merely mentions a subprocess
201
+ // exiting ("subprocess exited with code 1", "the Claude Code process exited
202
+ // with code 1 in the hook") is not read as the CLI dying. A CLI that exits 1
203
+ // on an API or auth failure is still a process exit, and is labelled one.
204
+ return /^Claude Code process (?:exited with code -?\d+|terminated by signal SIG[A-Z0-9]+)\b/.test(text)
205
+ }
206
+
207
+ /**
208
+ * #8300: is this the error the SDK's generator throws after the session
209
+ * itself closed the query (`Query.close()` aborts the transport and kills the
210
+ * CLI)? Only these are swallowed after a deliberate close; anything else is
211
+ * still a turn failure and is surfaced.
212
+ * @param {unknown} err
213
+ * @returns {boolean}
214
+ */
215
+ function isQueryCloseError(err) {
216
+ if (!err) return false
217
+ if (err.name === 'AbortError') return true
218
+ const text = typeof err.message === 'string' ? err.message : String(err)
219
+ // The SDK's own shapes for a close: "… aborted …" from the abort controller,
220
+ // and the transport's "terminated by signal SIGTERM/SIGKILL" from the kill
221
+ // close() sends. A nonzero "process exited with code N" is a crash, never a
222
+ // close, and stays surfaced even after a deliberate close.
223
+ return /\baborted?\b|terminated by signal SIG(TERM|KILL)\b/i.test(text)
224
+ }
225
+
226
+ /**
227
+ * #8300/#8302: is this a `task_updated` `patch.status` that closes the task?
228
+ * One predicate for the two sites that care (the live roster and the shell
229
+ * tracker), so they cannot disagree about which statuses are terminal.
230
+ * @param {unknown} status
231
+ * @returns {boolean}
232
+ */
233
+ function isTerminalTaskStatus(status) {
234
+ return status === 'completed' || status === 'failed' || status === 'killed'
235
+ }
236
+
237
+ /**
238
+ * Flatten a tool_result block's content to its text, the same way
239
+ * `emitToolResults` (tool-result.js) does, so a pattern match over the text
240
+ * sees the same string whether the CLI sent a string or a block array.
241
+ * @param {object} block - a `tool_result` content block
242
+ * @returns {string}
243
+ */
244
+ function toolResultText(block) {
245
+ if (typeof block?.content === 'string') return block.content
246
+ if (Array.isArray(block?.content)) {
247
+ return block.content
248
+ .filter((b) => b?.type === 'text')
249
+ .map((b) => b.text)
250
+ .join('\n')
251
+ }
252
+ return ''
253
+ }
254
+
91
255
  export class SdkSession extends BaseSession {
256
+ static canonicalAssistantResponses = true
257
+ static declarationTurnOwnership = true
258
+
92
259
  // #5858: marks this as a Claude-family provider — the single source of truth
93
260
  // for `isClaudeProvider()` (drives the createSession soft-fallback for stale
94
261
  // model ids + the shared models registry). Docker subclasses inherit it.
95
262
  static claudeFamily = true
96
263
 
264
+ static get customizationDescriptor() {
265
+ return CLAUDE_SDK_CUSTOMIZATION
266
+ }
267
+
268
+ // #6769: cap on how long the end-of-turn getContextUsage() control request
269
+ // may delay the `result` broadcast. The CLI answers in milliseconds when
270
+ // alive; the cap only bites when the process is already shutting down —
271
+ // in which case the snapshot is skipped and the result emits without it.
272
+ static CONTEXT_USAGE_SNAPSHOT_TIMEOUT_MS = 2000
273
+
274
+ // #8300: how long a zero-turn `result` is held before it is taken as the
275
+ // prompt's own. On `--resume`, Claude Code first replays an orphaned
276
+ // background task (a shell or subagent that was still running when the
277
+ // previous turn's process exited) as its own zero-cost turn: `init` →
278
+ // `result` with `num_turns: 0` → a second `init` for the real prompt, about
279
+ // 20–80 ms later. That first result must not end the turn (ending the input
280
+ // there is exactly the lost-channel bug). A real prompt that produces no
281
+ // assistant turn is the other reading of the same message, and the CLI then
282
+ // just waits on stdin — so the held result is confirmed by the next `init`
283
+ // or, failing that, taken as the real one when this window elapses.
284
+ static ORPHAN_NOTICE_CONFIRM_MS = 2000
285
+
97
286
  /**
98
287
  * Human-readable label shown in the startup banner and anywhere else the
99
288
  * server needs to name this provider (#2953). Each provider owns its own
@@ -111,13 +300,18 @@ export class SdkSession extends BaseSession {
111
300
  * hardcoding the path.
112
301
  */
113
302
  static get dataDir() {
114
- return join(homedir(), '.claude')
303
+ return claudeConfigDir()
115
304
  }
116
305
 
117
306
  static get capabilities() {
118
307
  return {
119
308
  permissions: true,
120
309
  inProcessPermissions: true,
310
+ // #7825: Auto installs an SDK PreToolUse callback that routes every tool
311
+ // through PermissionManager. Benign calls short-circuit immediately;
312
+ // protected paths reach the shared interactive floor.
313
+ permissionFloor: true,
314
+ autoPermissionMode: true,
121
315
  modelSwitch: true,
122
316
  permissionModeSwitch: true,
123
317
  // #5609: SDK applies a mid-turn switch to 'auto' in-process (clears
@@ -125,20 +319,67 @@ export class SdkSession extends BaseSession {
125
319
  // killing the turn. Declared false so the capability matrix is uniform —
126
320
  // CliSession is the only provider where the auto-switch is destructive.
127
321
  interruptsTurnOnAutoSwitch: false,
128
- planMode: false,
322
+ // #8153: was `false` since the provider adapter's introduction (#583),
323
+ // stale even then — `_sdkPermissionMode()` has always passed `'plan'`
324
+ // straight through as the SDK's own native `PermissionMode`, which
325
+ // query() forwards as a literal `--permission-mode plan` flag to the
326
+ // same `claude` CLI binary CliSession spawns (query() execs
327
+ // `pathToClaudeCodeExecutable`, #7986) — same binary, same read-only
328
+ // enforcement, same EnterPlanMode/ExitPlanMode tool-use protocol. The
329
+ // only missing piece was event wiring (now added in
330
+ // _handleToolUseBlock + the 'result' case in _callQuery), not a
331
+ // structural gap, so the capability is now `true` to match reality.
332
+ planMode: true,
129
333
  resume: true,
130
334
  terminal: false,
131
335
  thinkingLevel: true,
336
+ // #8700: true where `thinking_level_changed` carries `effective`, the
337
+ // level the provider REPORTS it applied. SdkSession reads it from Claude
338
+ // Code (`get_settings` → `applied.effort`) at the start of every turn; a
339
+ // client shows it beside the picker, or "unknown" while it is null.
340
+ // Every other provider declares false: no report, so no readout.
341
+ thinkingLevelEffective: true,
342
+ // #7725: true ONLY where the SERVER escalates on the magic keywords
343
+ // ("think" / "think hard" / "ultrathink" …). SdkSession is the sole
344
+ // importer of detect-thinking-keyword.js — it maps a detected keyword to
345
+ // a per-turn maxThinkingTokens budget in _callQuery. Every other provider
346
+ // declares false: the keyword is just prose to them, so a client that
347
+ // highlighted it there would promise an escalation that never happens.
348
+ // Separate from `thinkingLevel` on purpose — a provider can accept a
349
+ // reasoning-effort dropdown without honouring the Claude-only keywords.
350
+ thinkingKeywords: true,
132
351
  // #3932: explicit `streaming` so the capability matrix is uniform across
133
352
  // providers — claude-tui sets this to false (deliver-on-complete), all
134
353
  // others stream incremental deltas via stream_delta during a turn.
135
354
  streaming: true,
355
+ // #6888: true when an operator's free-text deny reason (PermissionPrompt's
356
+ // "sent with Deny" textarea) actually reaches the agent. The in-process
357
+ // PermissionManager path feeds it back as the tool's denial message
358
+ // (permission-manager.js buildDenyMessage) on the very next turn — the SDK
359
+ // honors this end to end. Gates the dashboard's deny-reason affordance so
360
+ // it isn't shown on providers that silently drop it (legacy-CLI, codex).
361
+ denyReason: true,
136
362
  // #3209/#3246: SDK rebuilds systemPrompt.append on every turn
137
363
  // (see sdk-session.js#_callQuery), so a runtime toggle of
138
364
  // _activeManualSkills + _loadSkills() takes effect on the next
139
365
  // user message. Subprocess providers don't get this for free —
140
366
  // they snapshot the skills text at session start.
141
367
  skillToggle: true,
368
+ // #6767: the SDK can fork/truncate a resumed conversation to a message
369
+ // boundary (`forkSession({ upToMessageId })`), so a checkpoint restore
370
+ // can branch the conversation ('conversation' / 'both' modes), not just
371
+ // the files. Advertised so the checkpoint UI enables the "Conversation"
372
+ // restore-mode option only where the server can actually honor it.
373
+ // DockerSdkSession overrides this to false — see the instance-level
374
+ // `supportsConversationFork` getter (transcript lives in-container).
375
+ conversationFork: true,
376
+ // #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
377
+ // idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
378
+ // cleared by `interrupt()`), and reports admission through
379
+ // `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
380
+ // can travel it as an ordinary user turn. session-wake.js gates on this with
381
+ // strict `=== true`; absent means NOT supported. Never duck-typed.
382
+ daemonTurnInput: true,
142
383
  }
143
384
  }
144
385
 
@@ -154,10 +395,35 @@ export class SdkSession extends BaseSession {
154
395
  * are session-lifetime so a fresh emit on the next drop re-publishes
155
396
  * the running total.
156
397
  *
398
+ * #7346: `tool_input_delta` delivers the SANITIZED full tool input as
399
+ * a single chunk from `_handleToolUseBlock`, once the full
400
+ * assistant-message `block.input` is known — mirroring
401
+ * byok-session.js's wire shape/client handler exactly. Per #8135
402
+ * (review), this does NOT stream raw per-chunk `input_json_delta`
403
+ * partials the way BYOK does — the Agent SDK's `stream_event` does
404
+ * carry those (same `includePartialMessages: true` config CliSession
405
+ * reads), but a secret can straddle chunk boundaries and mid-stream
406
+ * partial JSON can't be run through the sanitizer, so this only ever
407
+ * emits once, already-safe. Listing it here is what makes
408
+ * `session-manager.js`'s `_wireSessionEvents` bridge the emit onto the
409
+ * `session_event` channel at all.
410
+ *
157
411
  * @returns {string[]}
158
412
  */
159
413
  static get customEvents() {
160
- return ['stdin_dropped_totals']
414
+ return ['stdin_dropped_totals', 'tool_input_delta']
415
+ }
416
+
417
+ /**
418
+ * #8301: with stdin forwarding latched off, `sendMessage` emits a
419
+ * user-visible `stdin_disabled` error AND silently discards the user's own
420
+ * queued follow-ups (`clearOutgoingQueue({ emit: false })`). A daemon wake
421
+ * must not trigger either.
422
+ *
423
+ * @returns {string|null}
424
+ */
425
+ daemonTurnRefusal() {
426
+ return this._stdinForwardingDisabled ? 'stdin-disabled' : null
161
427
  }
162
428
 
163
429
  /**
@@ -170,11 +436,47 @@ export class SdkSession extends BaseSession {
170
436
  return true
171
437
  }
172
438
 
439
+ /**
440
+ * #7986 — the exact path `query()` will spawn via `pathToClaudeCodeExecutable`
441
+ * (see the per-turn options builder below). Preflight prefers this over a
442
+ * fresh candidate resolve when a provider exposes it (#6708 defect #3), so
443
+ * the existence/quarantine/provenance/version gates and the real spawn can
444
+ * never diverge onto different binaries. Re-resolves fresh on every access —
445
+ * NOT a frozen module-load const — so a `claude update` after daemon start
446
+ * is picked up on the next session-create.
447
+ */
448
+ static get resolvedBinary() {
449
+ return resolveClaudeBinary()
450
+ }
451
+
173
452
  /**
174
453
  * Preflight dependency spec used by `chroxy doctor`.
175
- * SDK mode spawns the `claude` binary under the hood, so the same
176
- * binary check applies. Credentials can come from ANTHROPIC_API_KEY,
177
- * CLAUDE_CODE_OAUTH_TOKEN, or a prior `claude login` subscription.
454
+ *
455
+ * SDK mode spawns the user's INSTALLED `claude` binary under the hood via
456
+ * `pathToClaudeCodeExecutable` (#7986) — the desktop bundle does not ship
457
+ * the Agent SDK's own platform binary, and `query()` throws if neither is
458
+ * available. So the same binary check every other claude-family provider
459
+ * runs applies here too, using the shared candidate list.
460
+ *
461
+ * Version floor is a HYBRID, hard-min + soft-advisory pair (#8031),
462
+ * replacing the single hard `minVersion` derived straight from the
463
+ * installed SDK's `claudeCodeVersion` field that #7986 originally shipped.
464
+ * That field is the `claude` CLI build the SDK release was *published
465
+ * alongside* — a pairing, not a genuine minimum — and the CLI's patch
466
+ * number is its release counter, so every SDK bump instantly hard-blocked
467
+ * any `claude` on a release channel that hadn't also updated yet (e.g. npm
468
+ * `stable`, which trails `latest`). Now:
469
+ * - `minVersion: CLAUDE_SDK_MIN_CLI_VERSION` — a small, hand-raised,
470
+ * deliberately-conservative constant — is the HARD floor: below it,
471
+ * preflight still throws `ProviderBinaryVersionError` exactly as before.
472
+ * - `recommendedVersion: () => sdkClaudeCodeVersion()` — the SDK's own
473
+ * pairing — is a SOFT floor: below it (but at/above the hard floor),
474
+ * preflight logs a warning and returns an advisory instead of blocking.
475
+ * A `claude` older than what this SDK build was tested against still gets
476
+ * a `claude update` remediation either way — just a throw below the hard
477
+ * floor, an advisory otherwise. Credentials can come from
478
+ * ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN, or a prior `claude login`
479
+ * subscription.
178
480
  */
179
481
  static get preflight() {
180
482
  return {
@@ -182,15 +484,22 @@ export class SdkSession extends BaseSession {
182
484
  binary: {
183
485
  name: 'claude',
184
486
  args: ['--version'],
185
- candidates: [
186
- '/opt/homebrew/bin/claude',
187
- '/usr/local/bin/claude',
188
- ],
189
- installHint: 'install Claude Code CLI (required by the Agent SDK)',
487
+ candidates: CLAUDE_BINARY_CANDIDATES,
488
+ minVersion: CLAUDE_SDK_MIN_CLI_VERSION,
489
+ recommendedVersion: () => sdkClaudeCodeVersion(),
490
+ // #7986 review S2: the Agent SDK spawns `pathToClaudeCodeExecutable`
491
+ // directly via `child_process.spawn`, no shell — a Windows npm shim
492
+ // (`claude.cmd`/`claude.bat`) can never actually run under that. This
493
+ // makes the refusal explicit and unconditional (see isShellShim +
494
+ // ProviderBinaryUnsupportedError in utils/preflight.js) instead of
495
+ // relying on it falling out of the version probe's EINVAL.
496
+ requiresDirectExec: true,
497
+ installHint: 'install Claude Code, or run `claude update` if it is installed — the SDK provider runs your installed claude',
498
+ updateHint: 'run `claude update`',
190
499
  },
191
500
  credentials: {
192
501
  envVars: ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'],
193
- hint: 'run `claude login` or set ANTHROPIC_API_KEY',
502
+ hint: `run \`${CLAUDE_LOGIN_COMMAND}\` or set ANTHROPIC_API_KEY`,
194
503
  optional: true,
195
504
  },
196
505
  }
@@ -212,6 +521,11 @@ export class SdkSession extends BaseSession {
212
521
  const credSpec = this.preflight.credentials
213
522
  const envVars = credSpec.envVars
214
523
  const hint = credSpec.hint || `set ${envVars.join(' or ')}`
524
+ // Built once rather than as a template nested inside the `detail` template below:
525
+ // scripts/lint-session-opt-forwarding.mjs finds class bodies with a bracket matcher
526
+ // that does not understand a template nested in a `${}`, and one went blind to this
527
+ // class (the session-subclass count dropped from 11 to 10) while that was written.
528
+ const fallbackHint = `run \`${CLAUDE_LOGIN_COMMAND}\` or set ANTHROPIC_API_KEY`
215
529
  // Era read at call time so a long-running daemon flips OAuth/credit-pool
216
530
  // copy at the 2026-06-15 boundary without a restart (#5629).
217
531
  const era = isProgrammaticCreditEra()
@@ -269,8 +583,8 @@ export class SdkSession extends BaseSession {
269
583
  source: 'none',
270
584
  envVar: null,
271
585
  envVars,
272
- hint: hint || 'run `claude login` or set ANTHROPIC_API_KEY',
273
- detail: `Not configured — ${hint || 'run \`claude login\` or set ANTHROPIC_API_KEY'}`,
586
+ hint: hint || fallbackHint,
587
+ detail: `Not configured — ${hint || fallbackHint}`,
274
588
  // Unconfigured: default to the era-gated credit-pool class (this is the
275
589
  // claude-sdk default auth path once configured via `claude login`).
276
590
  billingClass: era ? BILLING_CLASSES.PROGRAMMATIC_CREDIT : BILLING_CLASSES.SUBSCRIPTION,
@@ -304,7 +618,12 @@ export class SdkSession extends BaseSession {
304
618
  return claudeModelMetadata(modelId)
305
619
  }
306
620
 
307
- /** Token budgets for thinking levels. null = adaptive (SDK default). */
621
+ /**
622
+ * Token budgets for the legacy levels, for the models that predate Claude
623
+ * Code's effort setting and read only `maxThinkingTokens` (#8700: adaptive
624
+ * models ignore a budget, so a level goes to them as `effort` instead — see
625
+ * `_thinkingOptions`). null = adaptive (SDK default).
626
+ */
308
627
  static THINKING_BUDGETS = { default: null, high: 32000, max: 128000 }
309
628
 
310
629
  /** Error patterns mapped to user-friendly messages. */
@@ -313,8 +632,20 @@ export class SdkSession extends BaseSession {
313
632
  msg: 'Insufficient API credits or billing limit reached. Check your API provider dashboard.' },
314
633
  { test: /rate.limit|too many requests|429/i,
315
634
  msg: 'API rate limit exceeded. Please wait a moment and try again.' },
316
- { test: /authentication|invalid.api.key|401|unauthorized/i,
317
- msg: 'API authentication failed. Check your API key configuration.' },
635
+ // #8223: carries `code: AUTH_REQUIRED`; `msg` is only the fallback — a session
636
+ // swaps in its own host/container wording via `_authRequiredMessage()`.
637
+ // `failed to authenticate` and `oauth session|token … expired|revoked|invalid`
638
+ // are the OAuth-login wording ("Failed to authenticate: OAuth session expired
639
+ // and could not be refreshed"), which the pre-existing alternatives missed.
640
+ // `401` and `unauthorized` are bound, because a match now yields a no-retry
641
+ // sign-in card and these tokens turn up in unrelated text: a hex id
642
+ // (`container 7f3a4018c9e2…`), a request id (`req_011CTx401Qabc`), a port
643
+ // (`127.0.0.1:4010`) and a version path (`versions/2.1.401/claude`). The `401`
644
+ // bound is a lookaround rather than `\b401\b`, since `\b` still matches inside
645
+ // `2.1.401/`: not after a word char or `.`, not before a word char or `.digit`.
646
+ { 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,
647
+ msg: AUTH_REQUIRED_MESSAGE,
648
+ code: AUTH_REQUIRED_CODE },
318
649
  { test: /overloaded|503|529|temporarily unavailable/i,
319
650
  msg: 'The API is temporarily overloaded. Please try again in a few minutes.' },
320
651
  { test: /SIGABRT|SIGKILL|SIGSEGV|terminated by signal/i,
@@ -322,25 +653,104 @@ export class SdkSession extends BaseSession {
322
653
  ]
323
654
 
324
655
  static _enrichErrorMessage(raw) {
325
- if (!raw) return 'Unknown error'
326
- for (const { test, msg } of SdkSession._ERROR_PATTERNS) {
327
- if (test.test(raw)) return msg
656
+ return SdkSession._classifyError(raw).message
657
+ }
658
+
659
+ /**
660
+ * #8223: `_enrichErrorMessage` plus the row's `code`, when it has one. First
661
+ * matching row wins, exactly as before, so a message that reads as a billing or
662
+ * rate-limit failure is never reclassified as an auth one.
663
+ * @returns {{ message: string, code?: string }}
664
+ */
665
+ static _classifyError(raw) {
666
+ if (!raw) return { message: 'Unknown error' }
667
+ for (const { test, msg, code } of SdkSession._ERROR_PATTERNS) {
668
+ if (test.test(raw)) return code ? { message: msg, code } : { message: msg }
669
+ }
670
+ return { message: raw }
671
+ }
672
+
673
+ /**
674
+ * #8273 / #8970: which credential this session authenticates with, so the
675
+ * clients can name the real remedy. See `classifyAuthCause` for the precedence
676
+ * (container, Bedrock, Vertex, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY,
677
+ * apiKeyHelper, then a host login). `undefined` (field omitted): only
678
+ * CLAUDE_CODE_OAUTH_TOKEN is set, where the source is ambiguous and the
679
+ * combined message is kept.
680
+ * @returns {import('@chroxy/protocol').AuthRequiredCause | undefined}
681
+ */
682
+ _authCause() {
683
+ return classifyAuthCause(buildSpawnEnv('claude-sdk'), {
684
+ containerized: !!this.constructor.capabilities?.containerized,
685
+ })
686
+ }
687
+
688
+ /** #8223: the AUTH_REQUIRED text for THIS session — mechanism-aware. */
689
+ _authRequiredMessage(authCause = this._authCause()) {
690
+ switch (authCause) {
691
+ case 'container': return AUTH_REQUIRED_CONTAINER_MESSAGE
692
+ case 'api_key': return AUTH_REQUIRED_API_KEY_MESSAGE
693
+ case 'bedrock': return AUTH_REQUIRED_BEDROCK_MESSAGE
694
+ case 'vertex': return AUTH_REQUIRED_VERTEX_MESSAGE
695
+ case 'auth_token': return AUTH_REQUIRED_AUTH_TOKEN_MESSAGE
696
+ case 'api_key_helper': return AUTH_REQUIRED_API_KEY_HELPER_MESSAGE
697
+ default: return AUTH_REQUIRED_MESSAGE
698
+ }
699
+ }
700
+
701
+ /** #8273: the `error` event payload for an auth failure on THIS session. */
702
+ _authRequiredPayload() {
703
+ const authCause = this._authCause()
704
+ return {
705
+ code: AUTH_REQUIRED_CODE,
706
+ message: this._authRequiredMessage(authCause),
707
+ ...(authCause ? { authCause } : {}),
328
708
  }
329
- return raw
330
709
  }
331
710
 
332
711
  get thinkingLevel() { return this._thinkingLevel }
333
712
 
713
+ /**
714
+ * #8700 — the effort Claude Code reported it applied (`get_settings` →
715
+ * `applied.effort`), read at the start of each turn. null until it reports,
716
+ * and reset to null by a model or level change the running turn has not
717
+ * reported on yet. Put on the wire by `buildThinkingLevelChanged`.
718
+ */
719
+ get effectiveThinkingLevel() { return this._effectiveEffort }
720
+
721
+ /**
722
+ * #8700 — the one-line `model= requested= effective=` summary an operator
723
+ * reads in the daemon log before a send. Both log sites (the
724
+ * `set_thinking_level` handler and session-manager, for a change the session
725
+ * made itself) print this, so the line has one format.
726
+ */
727
+ describeThinkingLevel() {
728
+ const model = this._effectiveModel || this.model || this.bootedModel || 'default'
729
+ const requested = this._thinkingLevel || LEGACY_DEFAULT_THINKING_LEVEL
730
+ return `model=${model} requested=${requested} effective=${this._effectiveEffort || 'unknown'}`
731
+ }
732
+
334
733
  constructor(opts = {}) {
335
734
  super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-sdk' }))
336
735
  // SdkSession-local opts (not BaseSession opts — see buildBaseSessionOpts).
337
736
  const { resumeSessionId, transforms, maxToolInput, sandbox, stdinForwardingDisabled } = opts
737
+ // #8030 / #8035: per-spawn re-verification gate. Stored by BaseSession's
738
+ // constructor as `this._spawnPreflight` (see base-session.js's ctor param
739
+ // doc and `_gatedSpawnBinary`) — moved there so JsonlSubprocessSession's
740
+ // picker subclasses (Gemini/Codex-exec) inherit the same wiring instead of
741
+ // this middle layer reading `opts.spawnPreflight` on its own and silently
742
+ // dropping it for every subclass that forwards opts via the picker.
338
743
  this._maxToolInput = maxToolInput || DEFAULT_MAX_TOOL_INPUT_LENGTH
339
744
  this._transformPipeline = new MessageTransformPipeline(transforms || [])
340
745
  this._sandbox = sandbox || null
341
746
 
342
747
  this._sdkSessionId = resumeSessionId || null
343
748
  this._sessionId = null
749
+ // #8153: plan-mode bookkeeping, mirroring CliSession's _inPlanMode /
750
+ // _planAllowedPrompts (see _handleToolUseBlock + the 'result' case in
751
+ // _callQuery, and _clearMessageState's stale-flag reset).
752
+ this._inPlanMode = false
753
+ this._planAllowedPrompts = null
344
754
  // #4828: session-scoped logger, lazily bound on the SDK's first `init`
345
755
  // message (where session_id becomes known). Pre-init log lines stay on
346
756
  // the module-level `log` — same fallback pattern as ClaudeTuiSession.
@@ -349,7 +759,42 @@ export class SdkSession extends BaseSession {
349
759
  // lifetime; the binding stays valid until destroy() drops the instance.
350
760
  this._log = null
351
761
  this._query = null
762
+ // #8321: the turn whose query() generator is still being consumed, from the
763
+ // moment the query is created until its loop's `finally`. Busy state ends at
764
+ // the prompt's `result`, which is BEFORE the generator does (the CLI exits
765
+ // only once stdin closes), so `_isBusy` alone does not say whether a query
766
+ // is alive. `{ query, waitTimer, forceTimer }`, or null.
767
+ this._drainingTurn = null
352
768
  this._thinkingLevel = null
769
+ // #8700: what Claude Code last reported it applied (see
770
+ // `effectiveThinkingLevel`), the model it reported with it, the last
771
+ // report announced (so an unchanged report each turn stays quiet), and an
772
+ // epoch `_forgetEffortReport` bumps so a report still in flight across a
773
+ // model or level change is dropped.
774
+ this._effectiveEffort = null
775
+ this._effectiveModel = null
776
+ this._lastEffortReport = null
777
+ this._effortEpoch = 0
778
+ // Read order is independent of setting epochs: init can read while a live
779
+ // setter is pending, then that setter reads again within the same epoch.
780
+ this._effortReadSeq = 0
781
+ // #8700: the SDK's own per-model effort answer from `supportedModels()`,
782
+ // keyed by the row's `value` and its `resolvedModel`: 'effort' for a model
783
+ // that takes Claude Code's effort, 'budget' for one that still reads only
784
+ // `maxThinkingTokens`. Absent = this session has not heard.
785
+ this._modelEffortSupport = new Map()
786
+
787
+ // #6766: last SDK transcript message UUID seen this session. Captured from
788
+ // each full `assistant` message in the query loop and used as the fork
789
+ // boundary (`upToMessageId`) when a checkpoint created just after this
790
+ // point is later restored — so rewind truncates the conversation to the
791
+ // checkpoint instead of resuming the full latest transcript. Only the SDK
792
+ // provider tracks this; subprocess providers leave `lastMessageUuid` null.
793
+ this._lastMessageUuid = null
794
+ // #6766: injectable handle for the SDK's standalone `forkSession` so tests
795
+ // can stub the on-disk transcript fork without a live session (mirrors the
796
+ // instance-level `_query` injection the rest of the suite uses).
797
+ this._forkSessionImpl = forkSession
353
798
 
354
799
  // #5269 (Control Room Phase 2a): map a Task subagent's tool_use_id (the id
355
800
  // chroxy keys activity/agent nodes by) → the SDK's separate `task_id`,
@@ -360,13 +805,41 @@ export class SdkSession extends BaseSession {
360
805
  // destroy().
361
806
  this._taskIdByToolUseId = new Map()
362
807
 
808
+ // #8300: tasks the CLI reported with `task_started` and has not yet closed
809
+ // with `task_notification`, keyed by the SDK `task_id`. Read at the
810
+ // prompt's own `result`: a task still here then would outlive the turn's
811
+ // process, and the SDK provider cannot service it past the turn (its tool
812
+ // calls would be cancelled, see SDK_TOOL_CANCELLED_PREFIXES), so the turn
813
+ // end stops it and says so. Turn-local: cleared alongside
814
+ // `_taskIdByToolUseId` at the start of each turn.
815
+ this._liveBackgroundTasks = new Map()
816
+
817
+ // #8300: the current turn's streaming input handle (`_createTurnInput`),
818
+ // so destroy() can release the CLI's stdin without waiting for the
819
+ // message loop to observe `_destroying`. Null between turns.
820
+ this._turnInput = null
821
+
363
822
  // Permission handling — delegated to PermissionManager. The pause/resume
364
823
  // hooks keep the inactivity timer suspended while a permission is pending:
365
824
  // waiting on user input is NOT inactivity, and without this a session with
366
825
  // a pending prompt silently goes unresponsive after 5 min (#2831). The
367
826
  // pause uses a reference count so concurrent prompts keep the timer
368
827
  // suspended until the last one resolves. (Shared wiring extracted in P2-9.)
369
- this._permissions = new PermissionManager({ log })
828
+ // #6794 — pass cwd so the protected-path floor can resolve relative tool
829
+ // targets (.git/.claude/.env…) against this session's working directory.
830
+ // #6771 — pass the durable rule store so an `allowAlways` decision persists
831
+ // a project-scoped rule and this session seeds from prior grants for its cwd.
832
+ this._permissions = new PermissionManager({ log, cwd: this.cwd, ruleStore: this._permissionRuleStore })
833
+ // #8430: a prompt the user's Stop resolved -- including one raised between the
834
+ // Stop and the abort, which the snapshot in `interrupt()` could not see -- marks
835
+ // its tool row stopped. Driven by the `stopped` resolution itself -- the manager
836
+ // attaches `sourceToolUseId` to that resolution only -- so a Deny, a timeout or a
837
+ // rule decision made in the same window keeps its own row.
838
+ this._permissions.on('permission_resolved', (d) => {
839
+ if (typeof d?.sourceToolUseId !== 'string') return
840
+ this._stopCancelledToolUseIds.add(d.sourceToolUseId)
841
+ this._stopResolvedToolUseIds.add(d.sourceToolUseId)
842
+ })
370
843
  wirePermissionManager(this, this._permissions, {
371
844
  onRequest: () => this._pauseResultTimeoutForPermission(),
372
845
  onResolved: () => this._resumeResultTimeoutForPermission(),
@@ -408,6 +881,26 @@ export class SdkSession extends BaseSession {
408
881
  // client UI feedback is unaffected.
409
882
  this._lastRefusedWarnTs = 0
410
883
 
884
+ // #8363: tool_use ids whose permission prompt is awaiting a decision right
885
+ // now (added when the provider asks, dropped when it settles), and the subset
886
+ // that was still waiting when Stop was pressed. Stopping a turn makes the SDK
887
+ // resolve a pending prompt as a denial and write ITS OWN tool_result, whose
888
+ // text says the user did not want to proceed -- but nobody refused anything.
889
+ // The tool_result path (`_terminatedReasonForToolResult`) uses the second set
890
+ // to tag that result as a Stop. A decision the user actually gave never joins
891
+ // it: it leaves `_pendingPermissionToolUseIds` first.
892
+ this._pendingPermissionToolUseIds = new Set()
893
+ this._stopCancelledToolUseIds = new Set()
894
+ // #8430: the subset of those that a Stop-caused RESOLUTION confirmed. The
895
+ // snapshot in `interrupt()` marks a prompt provisionally (the provider can
896
+ // write its own denial before this session's resolution runs); a decision that
897
+ // lands first -- a Deny, a timeout -- is not confirmed and takes the mark off.
898
+ this._stopResolvedToolUseIds = new Set()
899
+ // #8936: the user-facing sentence of each denial this session decided
900
+ // (tool_use id -> PermissionManager's message), read once by the
901
+ // tool_result path to replace the provider's model-facing refusal text.
902
+ this._deniedToolMessages = new Map()
903
+
411
904
  // #4881: provider parity with CliSession's #4602 _intentionalStop flag.
412
905
  // Set by `interrupt()` immediately before aborting the active SDK query
413
906
  // generator, then consumed inside `_callQuery`'s try/catch/finally so a
@@ -430,6 +923,69 @@ export class SdkSession extends BaseSession {
430
923
  return this._sdkSessionId
431
924
  }
432
925
 
926
+ /**
927
+ * #6766: the transcript UUID of the last full assistant message seen this
928
+ * session, or null before the first turn completes. Checkpoint creation reads
929
+ * this to record a fork boundary; `null` on providers that don't track it.
930
+ * @returns {string|null}
931
+ */
932
+ get lastMessageUuid() {
933
+ return this._lastMessageUuid || null
934
+ }
935
+
936
+ /**
937
+ * #6766: whether this provider can fork/truncate a resumed conversation to a
938
+ * message boundary. True for the SDK provider (the Agent SDK exposes
939
+ * `forkSession({ upToMessageId })`); overridden false where the transcript is
940
+ * not reachable by the host-side fork (see DockerSdkSession — the transcript
941
+ * lives inside the container). The checkpoint restore path gates the real
942
+ * conversation rewind on this; when false it degrades to a files-only restore.
943
+ * @returns {boolean}
944
+ */
945
+ get supportsConversationFork() {
946
+ return true
947
+ }
948
+
949
+ /**
950
+ * #6766: record the fork boundary from a full SDK message. Guarded so a
951
+ * message without a string `uuid` leaves the previous boundary intact.
952
+ * Extracted from the query loop so it can be unit-tested directly.
953
+ * @param {object} msg - An SDK stream message (expects a `uuid` field).
954
+ */
955
+ _captureBoundaryMessage(msg) {
956
+ if (msg && typeof msg.uuid === 'string' && msg.uuid) {
957
+ this._lastMessageUuid = msg.uuid
958
+ }
959
+ }
960
+
961
+ /**
962
+ * #6766: fork a conversation into a new, independent SDK session truncated to
963
+ * a message boundary. Wraps the Agent SDK's standalone `forkSession`, which
964
+ * copies the source transcript (remapping UUIDs) up to and including
965
+ * `upToMessageId`, then returns the new session's id — resumable like any
966
+ * other conversation id. This is what makes checkpoint "Rewind" actually
967
+ * branch the conversation (not just the files) for the SDK provider.
968
+ *
969
+ * @param {object} params
970
+ * @param {string} [params.sessionId] - Source conversation id to fork.
971
+ * Defaults to this session's current SDK id.
972
+ * @param {string} [params.upToMessageId] - Fork boundary (inclusive). Omitted
973
+ * → full copy.
974
+ * @returns {Promise<string|null>} The forked conversation id, or null if the
975
+ * SDK returned no id.
976
+ */
977
+ async forkConversation({ sessionId, upToMessageId } = {}) {
978
+ const source = sessionId || this._sdkSessionId
979
+ if (!source) throw new Error('Cannot fork conversation: no source session id')
980
+ const opts = {}
981
+ if (typeof upToMessageId === 'string' && upToMessageId) opts.upToMessageId = upToMessageId
982
+ // Scope the transcript search to this session's project dir when known; the
983
+ // SDK falls back to searching all project dirs when `dir` is omitted.
984
+ if (this.cwd) opts.dir = this.cwd
985
+ const result = await this._forkSessionImpl(source, opts)
986
+ return result?.sessionId || null
987
+ }
988
+
433
989
  /**
434
990
  * Public accessor for the cumulative stdin_dropped totals (#3544).
435
991
  *
@@ -512,15 +1068,29 @@ export class SdkSession extends BaseSession {
512
1068
  message: 'Cannot send message — stdin forwarding is disabled; restart this session',
513
1069
  recoverable: false,
514
1070
  })
1071
+ reportInputAdmission(sendOptions, {
1072
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1073
+ reason: 'stdin_disabled', message: 'The provider input channel is disabled; restart the session before retrying.',
1074
+ })
515
1075
  return
516
1076
  }
517
1077
 
518
- if (this._isBusy) {
1078
+ // #8321: a previous turn's query may still be draining after its result
1079
+ // cleared busy. A follow-up then waits in the same outgoing queue and is
1080
+ // flushed by that turn's `finally`, so one query() runs at a time.
1081
+ if (this._isBusy || this._drainingTurn) {
519
1082
  // #5936 (epic #5935): a send-while-busy follow-up goes into the shared
520
1083
  // outgoing queue (BaseSession) — flushed FIFO on the next `result`. The
521
1084
  // overflow cap + the `message_queued` mirror event live in
522
1085
  // enqueueOutgoingMessage; nothing to do here but enqueue and return.
523
- this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
1086
+ const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
1087
+ if (queued && !this._isBusy) this._armDrainRelease()
1088
+ reportInputAdmission(sendOptions, queued
1089
+ ? { status: 'queued', delivery: 'queued' }
1090
+ : {
1091
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1092
+ reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
1093
+ })
524
1094
  return
525
1095
  }
526
1096
 
@@ -536,17 +1106,50 @@ export class SdkSession extends BaseSession {
536
1106
  }
537
1107
 
538
1108
  this._isBusy = true
1109
+ // #7376: a turn starts with no Stop requested, whatever the last one did.
1110
+ this._stopRequestedThisTurn = false
1111
+ this._stopCancelledToolUseIds.clear() // #8363
1112
+ this._stopResolvedToolUseIds.clear() // #8430
1113
+ this._deniedToolMessages.clear() // #8936
1114
+ // #8430: ...and with no user Stop in flight, whatever the last turn left (a
1115
+ // turn superseded before its teardown never reaches `_clearMessageState`).
1116
+ this._permissions.clearUserStopInFlight()
1117
+ // #8300: a per-session monotonic turn token. `supersededByNewerTurn`
1118
+ // compares against it: unlike a handle comparison it never reverts once
1119
+ // a follow-up turn has started and ended.
1120
+ this._turnSeq = (this._turnSeq || 0) + 1
1121
+ const turnSeq = this._turnSeq
539
1122
  this._messageCounter++
540
1123
  // `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
541
1124
  // the boot-unique prefix is needed (#3700). Format change does not
542
1125
  // affect the wire schema; clients treat messageId as opaque string.
543
1126
  const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
544
1127
  this._currentMessageId = messageId
1128
+ // This immutable request id remains this query's identity across awaits,
1129
+ // timeout recovery and a successor query taking over the session.
1130
+ const emitTurnEvent = (event, payload) => this.emit(event, { ...payload, declarationTurnId: messageId })
1131
+ this.emit('declaration_turn', { declarationTurnId: messageId })
545
1132
  // Shared ref so _handleResultTimeout can observe the latest value
546
1133
  // when it fires (the timer was armed when hasStreamStarted was still
547
1134
  // false, but the turn may have streamed before the timeout landed).
548
1135
  const streamState = { hasStreamStarted: false }
549
1136
  let didStreamText = false
1137
+ // #6756 — extended-thinking forwarding. Each thinking / redacted_thinking
1138
+ // content block gets a DISTINCT thinking messageId (`<turnId>-thinking-<n>`)
1139
+ // so its stream never collides with the response text stream. `thinkingBlocks`
1140
+ // maps the SDK stream event `index` → that thinking id so the thinking_delta
1141
+ // and content_block_stop events (which carry only the index) route correctly.
1142
+ const thinkingBlocks = new Map()
1143
+ // #6391 (chat-redesign footer-stat) — thinkingId -> performance.now() when
1144
+ // the reasoning block opened, so its content_block_stop can stamp the
1145
+ // elapsed `thinkingDurationMs` on the thinking stream_end. Turn-local;
1146
+ // entries are deleted alongside thinkingBlocks when the block closes.
1147
+ // #6943: monotonic clock (perf_hooks), not Date.now() — wall-clock jumps
1148
+ // (NTP step, manual change, DST) would otherwise clamp a backward jump to
1149
+ // 0 or inflate a forward jump.
1150
+ const thinkingStartMs = new Map()
1151
+ let thinkingBlockCount = 0
1152
+ let didStreamThinking = false
550
1153
 
551
1154
  const sdkPermMode = this._sdkPermissionMode()
552
1155
  // Skills MVP (#2957) — append shared skills via SDK systemPrompt.append.
@@ -580,6 +1183,13 @@ export class SdkSession extends BaseSession {
580
1183
  settingSources: ['user', 'project', 'local'],
581
1184
  systemPrompt,
582
1185
  tools: { type: 'preset', preset: 'claude_code' },
1186
+ // The environment for the `claude` child query() spawns, built per turn
1187
+ // by the same spawn-env builder every other provider child goes
1188
+ // through: the full parent env minus the daemon-owned secrets and any
1189
+ // ambiently inherited per-session chroxy values, plus the host
1190
+ // identity. A containerised subclass receives it through
1191
+ // spawnClaudeCodeProcess's `env` and applies its own allowlist.
1192
+ env: buildSpawnEnv('claude-sdk'),
583
1193
  }
584
1194
 
585
1195
  // SDK requires this flag when using bypassPermissions
@@ -591,11 +1201,9 @@ export class SdkSession extends BaseSession {
591
1201
  options.model = this.model
592
1202
  }
593
1203
 
594
- // Apply thinking level if set
595
- if (this._thinkingLevel) {
596
- const budget = SdkSession.THINKING_BUDGETS[this._thinkingLevel]
597
- if (budget != null) options.maxThinkingTokens = budget
598
- }
1204
+ // Apply thinking level if set — as Claude Code's effort, or as the legacy
1205
+ // budget for a model that predates effort (#8700, `_thinkingOptions`).
1206
+ Object.assign(options, this._thinkingOptions())
599
1207
 
600
1208
  // #4306 — magic thinking-keyword escalation. The native Claude Code CLI's
601
1209
  // interactive REPL scans the user's prompt for keywords (`think`,
@@ -631,7 +1239,12 @@ export class SdkSession extends BaseSession {
631
1239
  options.sandbox = this._sandbox
632
1240
  }
633
1241
 
634
- // In-process permission handling (only when not bypassing).
1242
+ // In-process permission handling. In normal modes the SDK's canUseTool
1243
+ // request reaches PermissionManager. `bypassPermissions` suppresses those
1244
+ // native permission requests, so Auto uses the SDK's PreToolUse hook seam
1245
+ // instead: PreToolUse runs before every tool even under bypass, and the
1246
+ // callback routes the same (tool,input) pair through PermissionManager.
1247
+ // That keeps permission-floor.js as the one protected-path predicate.
635
1248
  // We forward the SDK-provided `suggestions` to the permission manager
636
1249
  // so the 'allow always' flow can echo them back via updatedPermissions.
637
1250
  // Without this, respondToPermission('allowAlways') had nothing to
@@ -642,8 +1255,18 @@ export class SdkSession extends BaseSession {
642
1255
  // documentation is { behavior: 'allow', updatedPermissions:
643
1256
  // <suggestions from callback options> }.
644
1257
  if (this.permissionMode !== 'auto') {
645
- options.canUseTool = (toolName, input, { signal, suggestions }) =>
646
- this._handlePermission(toolName, input, signal, suggestions)
1258
+ options.canUseTool = (toolName, input, { signal, suggestions, toolUseID }) =>
1259
+ this._handlePermission(toolName, input, signal, suggestions, toolUseID)
1260
+ } else {
1261
+ options.hooks = {
1262
+ PreToolUse: [{
1263
+ hooks: [(input, toolUseId, { signal }) => this._handleAutoPreToolUse(input, signal, toolUseId)],
1264
+ // PermissionManager's default human-decision timeout is 300s. Give
1265
+ // its hook callback a small completion margin so the manager owns the
1266
+ // timeout result instead of the SDK aborting it first.
1267
+ timeout: 310,
1268
+ }],
1269
+ }
647
1270
  }
648
1271
 
649
1272
  // Resume existing session if we have one
@@ -693,24 +1316,225 @@ export class SdkSession extends BaseSession {
693
1316
  this._resetResultTimeout = resetResultTimeout
694
1317
  resetResultTimeout()
695
1318
 
1319
+ // #8030: declared OUTSIDE the try below so the catch block can see them.
1320
+ // spawnRefused distinguishes "the binary gate refused this spawn before
1321
+ // query() was ever called" from every other turn failure — it must never
1322
+ // be routed through the same error-enrichment/container-classification
1323
+ // path a real query failure gets. spawnPath is the path this turn actually
1324
+ // asked the SDK to spawn (whichever of spawnPreflight()/resolvedBinary won
1325
+ // below), used by the post-preflight spawn-failure backstop further down.
1326
+ let spawnRefused = false
1327
+ let spawnPath = null
1328
+ // #8030: flips true on the first message this turn's `for await` loop
1329
+ // receives. Gates the spawn-failure backstop below: a labelBinarySpawnFailure
1330
+ // re-verify only makes sense for a failure BEFORE any SDK output — once a
1331
+ // message has streamed, the binary plainly launched fine and a later
1332
+ // failure is something else entirely.
1333
+ let receivedAnyMessage = false
1334
+ // #8223: an authentication failure can reach this turn twice — as an assistant
1335
+ // message carrying `error: 'authentication_failed'`, and again as the query
1336
+ // throwing. Declared outside the try for the same reason as the flags above;
1337
+ // the first one to surface it wins, so a turn shows one AUTH_REQUIRED.
1338
+ let authRequiredEmitted = false
1339
+ // #8300: the turn's streaming input handle (set once `_createTurnInput`
1340
+ // runs inside the try); the `finally` ends it on every exit path.
1341
+ let input = null
1342
+ // #8300: a zero-turn `result` held back as a probable orphan-task notice
1343
+ // (see ORPHAN_NOTICE_CONFIRM_MS), the timer that takes it as the real
1344
+ // result if no `init` follows, and whether this turn has seen the prompt
1345
+ // actually run (assistant output, stream events or tool results) — a
1346
+ // result after that is the prompt's own whatever its num_turns says.
1347
+ let heldNoticeResult = null
1348
+ let noticeTimer = null
1349
+ let promptActivitySeen = false
1350
+ // #8300: set when `finishTurn` closed the query on purpose (background
1351
+ // work still live at the prompt's result), so the abort the SDK then
1352
+ // throws is logged, not surfaced as a turn error.
1353
+ let closedAfterResult = false
1354
+ // #8300: the held-result window finalizes the turn itself (see the
1355
+ // timer in `case 'result'`); the loop awaits that work before its finally
1356
+ // runs, so the two can never finish the same turn twice.
1357
+ let timerFinish = null
1358
+ // #8300: this turn's own query handle, so the `finally` only clears
1359
+ // `this._query` when it still points here — a follow-up turn that started
1360
+ // while this one was draining must keep its handle.
1361
+ let turnQuery = null
1362
+ // #8321: this turn's entry in `_drainingTurn`; ended in the `finally`.
1363
+ let turnDrain = null
1364
+ // #8300: the task ids THIS turn saw start. The roster is shared per
1365
+ // session, so a turn that finishes after a follow-up turn has started
1366
+ // must only stop and report the tasks it owns, never the successor's.
1367
+ const turnTaskIds = new Set()
1368
+ // #8302: the background SHELL ids this turn's tool_results announced. A shell
1369
+ // is owned by the process that started it, and on this provider that is the
1370
+ // turn's own per-turn process: once the turn's query is closed nothing can
1371
+ // ever read the shell's output or hear its completion, so it must not keep
1372
+ // the session "running". Kept apart from `turnTaskIds` because a shell can
1373
+ // be tracked without a `task_started` ever naming it (an older CLI build,
1374
+ // `skip_transcript`), and that is exactly the shell no other path releases.
1375
+ const turnShellIds = new Set()
1376
+ // #8302: release every shell this turn started. `clearBackgroundShell` is a
1377
+ // no-op for an id that is not tracked, so this is idempotent and is called
1378
+ // from both the normal turn end and the `finally`. It never touches a shell
1379
+ // another turn tracked: a follow-up turn that took the session owns its own.
1380
+ const reapTurnShells = () => {
1381
+ for (const shellId of turnShellIds) this.clearBackgroundShell(shellId)
1382
+ }
1383
+ // #8302: set when the turn's query threw. Its control channel is then gone,
1384
+ // so a stop request cannot be made (and must not be pretended to have been).
1385
+ let queryFailed = false
1386
+ let queryClosed = false
1387
+ // #8302: THE routine that asks the CLI to stop the turn's still-tracked
1388
+ // shells and turns the answers into reports. Used by the prompt's own result
1389
+ // (`finishTurn`, for shells no live task names) AND by the `finally` (every
1390
+ // other exit: a throw, an abort), so an abnormal exit cannot drop a spawned
1391
+ // shell silently. Idempotent: it only sees shells still tracked, and a shell
1392
+ // it handled is released by the caller, so the second call finds nothing.
1393
+ //
1394
+ // `outcome` per shell:
1395
+ // 'stopped' the CLI acknowledged the stop
1396
+ // 'unconfirmed' it did not — rejected (a shell-only id the CLI never
1397
+ // named, a task already gone), timed out, or the channel was
1398
+ // not usable to ask at all. Termination is UNKNOWN, and is
1399
+ // worded that way: "it may still be running" would claim more
1400
+ // than we know, "could not be stopped" more than we tried.
1401
+ const turnShellsToStop = () => [...turnShellIds]
1402
+ .filter((shellId) => this._pendingBackgroundShells.has(shellId))
1403
+ .filter((shellId) => !reportedShellIds.has(shellId))
1404
+ .map((shellId) => ({
1405
+ taskId: shellId,
1406
+ toolUseId: null,
1407
+ taskType: 'local_bash',
1408
+ description: this._pendingBackgroundShells.get(shellId)?.command || shellId,
1409
+ background: true,
1410
+ }))
1411
+ const reportedShellIds = new Set()
1412
+ const stopTurnShells = (shells, channelUsable) => Promise.all(shells.map(async (task) => {
1413
+ if (channelUsable) {
1414
+ ;(this._log || log).warn(`Background shell "${task.description}" (${task.taskId}) was still running at the turn's end; stopping it with the turn`)
1415
+ }
1416
+ const stopped = channelUsable ? await this._stopLiveTask(turnQuery, task.taskId) : false
1417
+ return { task, outcome: stopped ? 'stopped' : 'unconfirmed', asked: channelUsable }
1418
+ }))
1419
+ const reportTurnShells = (results) => {
1420
+ for (const { task, outcome, asked } of results) {
1421
+ if (reportedShellIds.has(task.taskId)) continue
1422
+ reportedShellIds.add(task.taskId)
1423
+ const tail = 'A claude-sdk session runs background work only within the turn that started it.'
1424
+ emitTurnEvent('error', {
1425
+ code: 'background_task_ended_with_turn',
1426
+ message: outcome === 'stopped'
1427
+ ? `Background shell "${task.description}" was still running when the turn ended and was stopped with it; ${tail}`
1428
+ : asked
1429
+ ? `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}`
1430
+ : `Background shell "${task.description}" was still tracked when the turn ended abnormally; the turn's query was no longer usable, so it could not be asked to stop and its termination is UNCONFIRMED. ${tail}`,
1431
+ toolUseId: null,
1432
+ taskId: task.taskId,
1433
+ stopped: outcome === 'stopped',
1434
+ unconfirmed: outcome !== 'stopped',
1435
+ recoverable: true,
1436
+ })
1437
+ }
1438
+ }
1439
+ // #8300: true once a follow-up turn owns the session (it started while
1440
+ // this one was still draining or stopping work, after a hard timeout or
1441
+ // stream stall cleared busy). This turn then only reports and ends its
1442
+ // own process; it must not clear busy state or flush the queue, which
1443
+ // belong to the newer turn.
1444
+ const supersededByNewerTurn = () => this._turnSeq !== turnSeq
1445
+
696
1446
  try {
697
- // Allow subclasses to augment query options (e.g. DockerSdkSession
698
- // injects spawnClaudeCodeProcess here)
699
- this._augmentQueryOptions(options)
1447
+ // #7986 / #8030: point the SDK at the installed `claude` binary on every
1448
+ // turn. The desktop bundle does not ship the SDK's own platform binary,
1449
+ // and without pathToClaudeCodeExecutable query() throws ("Native CLI
1450
+ // binary ... not found") even when a subclass supplies
1451
+ // spawnClaudeCodeProcess. The SDK execs a NEW process per turn, so
1452
+ // "verified at session-create" only covers turn one — `_gatedSpawnBinary`
1453
+ // (BaseSession; the gate is SessionManager's `spawnPreflight` opt)
1454
+ // re-runs the full binary gate against the create-time-pinned path
1455
+ // before every subsequent spawn too. Falls back to a plain
1456
+ // `resolvedBinary` read when no gate was wired (a direct `new
1457
+ // SdkSession(...)` caller that bypassed SessionManager, or a test).
1458
+ // Set BEFORE _augmentQueryOptions so a subclass can read it; a subclass
1459
+ // that CHANGES it is refused below, since the new path was never checked.
1460
+ //
1461
+ // Everything in this inner try runs before query() and decides WHAT would
1462
+ // be exec'd, so any throw here is a pre-dispatch refusal (spawnRefused).
1463
+ try {
1464
+ // #8035: an empty path would leave pathToClaudeCodeExecutable unset,
1465
+ // and the SDK would then fall back to its own bundled binary —
1466
+ // unverified. `_gatedSpawnBinary` (BaseSession) throws
1467
+ // PROVIDER_BINARY_UNVERIFIED for that case; any error the gate itself
1468
+ // throws propagates unchanged.
1469
+ spawnPath = this._gatedSpawnBinary('claude')
1470
+ options.pathToClaudeCodeExecutable = spawnPath
1471
+
1472
+ // Allow subclasses to augment query options (e.g. DockerSdkSession
1473
+ // injects spawnClaudeCodeProcess here)
1474
+ this._augmentQueryOptions(options)
1475
+ if (options.pathToClaudeCodeExecutable !== spawnPath) {
1476
+ const err = new Error('A provider hook changed the claude binary path after it was verified; this turn was not sent.')
1477
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
1478
+ throw err
1479
+ }
1480
+
1481
+ // #8030 review: a containerised subclass runs claude INSIDE its
1482
+ // container through spawnClaudeCodeProcess, and pathToClaudeCodeExecutable
1483
+ // is the HOST binary, which no gate has checked (containerised providers
1484
+ // get no spawnPreflight). Without the hook — e.g. DockerSdkSession before
1485
+ // `docker run` has returned a container id — query() would exec the host
1486
+ // claude outside the container. Refuse instead.
1487
+ if (this.constructor.capabilities?.containerized && typeof options.spawnClaudeCodeProcess !== 'function') {
1488
+ 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.')
1489
+ err.code = 'CONTAINER_SPAWN_UNAVAILABLE'
1490
+ throw err
1491
+ }
1492
+ } catch (err) {
1493
+ spawnRefused = true
1494
+ throw err
1495
+ }
700
1496
 
701
1497
  // If attachments present, build multimodal content blocks
702
1498
  const promptWithSkills = firstMessagePrefix
703
1499
  ? `${firstMessagePrefix}${transformedPrompt}`
704
1500
  : transformedPrompt
705
- const queryArgs = { prompt: promptWithSkills, options }
706
- if (attachments?.length) {
707
- queryArgs.prompt = buildContentBlocks(promptWithSkills, attachments)
708
- }
1501
+ const promptContent = attachments?.length
1502
+ ? buildContentBlocks(promptWithSkills, attachments)
1503
+ : [{ type: 'text', text: typeof promptWithSkills === 'string' ? promptWithSkills : String(promptWithSkills ?? '') }]
1504
+ // #8300: the prompt goes to query() as a STREAMING input (an async
1505
+ // iterable of one user message), never as a plain string. With a string
1506
+ // the Agent SDK marks the query single-turn and closes the CLI's stdin at
1507
+ // the FIRST `result` it sees — and on `--resume` the first result can be
1508
+ // the orphan-task notice turn, not the prompt's: the prompt then runs
1509
+ // with no channel for `canUseTool`/PreToolUse, every tool call is
1510
+ // cancelled with the generic "user doesn't want to take this action"
1511
+ // text, and no permission_request ever reaches a client. With an
1512
+ // iterable the SDK closes stdin only after the iterable ENDS, and this
1513
+ // turn ends it in `finishTurn` — after the result that answers the
1514
+ // prompt — or in the `finally` below, so stdin is never left open past
1515
+ // the turn either.
1516
+ input = this._createTurnInput({
1517
+ type: 'user',
1518
+ session_id: this._sdkSessionId || '',
1519
+ message: { role: 'user', content: promptContent },
1520
+ parent_tool_use_id: null,
1521
+ })
1522
+ this._turnInput = input
1523
+ const queryArgs = { prompt: input.iterable, options }
709
1524
  this._query = this._callQuery(queryArgs)
1525
+ turnQuery = this._query
1526
+ turnDrain = { query: turnQuery, waitTimer: null, forceTimer: null }
1527
+ this._drainingTurn = turnDrain
1528
+ // A message already waited while busy had cleared before this query existed.
1529
+ if (!this._isBusy && this._outgoingQueue.length) this._armDrainRelease()
1530
+ reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
710
1531
  // #5269: a fresh turn — drop any task_id mappings left over from a prior
711
1532
  // turn (every subagent should clear via task_notification, but a turn
712
1533
  // aborted before its notifications would otherwise strand entries).
713
1534
  this._taskIdByToolUseId.clear()
1535
+ // #8300: the live-task roster is NOT cleared here: a previous turn may
1536
+ // still be finishing (stopping its own tasks) and reads its entries by
1537
+ // the ids it saw start; a stale entry can never match a later turn.
714
1538
 
715
1539
  // _callQuery returned an iterable without throwing — the prepend
716
1540
  // bucket is committed to this turn's prompt, so flip the flag (#3225).
@@ -721,13 +1545,301 @@ export class SdkSession extends BaseSession {
721
1545
  this._skillsPrepended = true
722
1546
  }
723
1547
 
1548
+ // #8300: a held zero-turn result turned out to be the orphan-task
1549
+ // notice — the CLI went on with the prompt in the same process. Called
1550
+ // from the next `init` (the usual confirmation), from any prompt
1551
+ // activity, and from a further result; each is stronger evidence than
1552
+ // the 2 s window, which must never fire under a running prompt.
1553
+ const confirmHeldNotice = (how) => {
1554
+ if (heldNoticeResult === null) return
1555
+ heldNoticeResult = null
1556
+ if (noticeTimer) {
1557
+ clearTimeout(noticeTimer)
1558
+ noticeTimer = null
1559
+ }
1560
+ ;(this._log || log).info(`Claude Code replayed a background task left over from an earlier turn (${how}); the prompt runs in the same process`)
1561
+ this.emit('message', {
1562
+ type: 'system',
1563
+ subtype: 'orphan_task_notice',
1564
+ content: 'A background task from an earlier turn ended with that turn; Claude Code noted it and is now running this prompt.',
1565
+ timestamp: Date.now(),
1566
+ })
1567
+ }
1568
+
1569
+ // #8300: the prompt's own result ends the turn. A closure rather than a
1570
+ // `case` body so the held-notice timer and the post-loop fallback can
1571
+ // run the identical turn end. Idempotent: whichever of the three callers
1572
+ // gets here first finishes the turn, the others return. `heldPath` says
1573
+ // this is a held zero-turn result taken as the prompt's own (the CLI is
1574
+ // idle or already gone), so no context-usage snapshot is requested.
1575
+ let turnFinished = false
1576
+ // #8300: end this turn's own process, once. Used when live work would
1577
+ // keep it alive past the result, when a finished turn keeps receiving
1578
+ // messages (the process lingered), and when destroy() lands mid-stop.
1579
+ // (`queryClosed` itself is declared with the turn's other flags, above the
1580
+ // try, because the `finally` reads it too — #8302.)
1581
+ // #8300: set once finishTurn's stop requests have been answered (or
1582
+ // timed out). A message that lands during the stops must not close the
1583
+ // query first: the real SDK rejects pending control requests on close,
1584
+ // and a stop the CLI had already carried out would be reported as failed.
1585
+ let stopsDone = false
1586
+ const closeTurnQuery = () => {
1587
+ if (queryClosed || !turnQuery) return
1588
+ queryClosed = true
1589
+ closedAfterResult = true
1590
+ try {
1591
+ if (typeof turnQuery.close === 'function') turnQuery.close()
1592
+ } catch (closeErr) {
1593
+ ;(this._log || log).warn(`Query close after result failed: ${closeErr?.message || closeErr}`)
1594
+ }
1595
+ }
1596
+ // #8321: the drain bound closes the query through the turn's own close, so
1597
+ // the abort the SDK then throws is logged, not reported as a turn error.
1598
+ if (turnDrain) turnDrain.close = closeTurnQuery
1599
+ const finishTurn = async (msg, { heldPath = false } = {}) => {
1600
+ if (turnFinished) return
1601
+ turnFinished = true
1602
+ // #8300: background work the CLI started this turn and has not
1603
+ // closed. The turn's process cannot outlive the turn, and the SDK
1604
+ // provider cannot service a task past the result (its tool calls
1605
+ // would be cancelled and its notification turn left unserviced), so
1606
+ // the work is stopped with the turn and each loss is said out loud —
1607
+ // never a silent cancellation.
1608
+ //
1609
+ // Stops go to THIS turn's query (`turnQuery`), never `this._query`,
1610
+ // which a follow-up turn may own by now. Asked in parallel and
1611
+ // bounded, so N hung tasks cost one STOP_TASK_TIMEOUT_MS, not N.
1612
+ const liveWork = this._liveBackgroundWork().filter((task) => turnTaskIds.has(task.taskId))
1613
+ // Only this turn's own tasks leave the roster: a follow-up turn that
1614
+ // took the session owns whatever else is in it.
1615
+ for (const task of liveWork) this._liveBackgroundTasks.delete(task.taskId)
1616
+ // #8302: a shell this turn's tool_result announced that no live task
1617
+ // names (no `task_started`, or a `skip_transcript` one) is still a shell
1618
+ // the CLI spawned, and a spawned shell can outlive the query (verified
1619
+ // live, above). Releasing it silently would leave it running, unreported.
1620
+ // So it goes through the SAME bounded stop pass and the SAME report as a
1621
+ // rostered task, and is released afterwards. Only shells still tracked:
1622
+ // one a notification already closed is gone from the tracker.
1623
+ const rosteredIds = new Set(liveWork.map((task) => task.taskId))
1624
+ const shellOnlyWork = turnShellsToStop().filter((task) => !rosteredIds.has(task.taskId))
1625
+ const stopWork = [...liveWork, ...shellOnlyWork]
1626
+ const [stopResults, shellOnlyResults] = await Promise.all([Promise.all(liveWork.map((task) => {
1627
+ const kind = task.taskType === 'local_bash' ? 'shell' : 'subagent'
1628
+ ;(this._log || log).warn(`Background ${kind} "${task.description}" (${task.taskId}) was still running at the turn's result; stopping it with the turn`)
1629
+ // Ask the CLI to stop the task while the control channel is still
1630
+ // open: closing the query alone ends the CLI, not a shell it spawned
1631
+ // (verified live: the shell outlived `close()`), so the report below
1632
+ // says which of the two happened.
1633
+ return this._stopLiveTask(turnQuery, task.taskId).then((stopped) => ({ task, kind, stopped }))
1634
+ })), stopTurnShells(shellOnlyWork, true)])
1635
+ // destroy() may have landed during the stops: it owns the UX from here
1636
+ // and has removed every listener, so nothing is emitted — but the
1637
+ // process is still ended, or a live task would keep it (and this
1638
+ // parked loop) alive for good.
1639
+ stopsDone = true
1640
+ if (this._destroying) {
1641
+ if (input) input.end()
1642
+ closeTurnQuery()
1643
+ return
1644
+ }
1645
+ // A hard timeout or stream stall during the stops may have cleared
1646
+ // busy and let a follow-up turn start: the session's state is then
1647
+ // that turn's, and this one only reports and ends its own process.
1648
+ const superseded = supersededByNewerTurn()
1649
+ for (const { task, kind, stopped } of stopResults) {
1650
+ emitTurnEvent('error', {
1651
+ code: 'background_task_ended_with_turn',
1652
+ message: stopped
1653
+ ? `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.`
1654
+ : `Background ${kind} "${task.description}" was still running when the turn ended and could not be stopped; it may still be running. A claude-sdk session runs background work only within the turn that started it.`,
1655
+ toolUseId: task.toolUseId,
1656
+ taskId: task.taskId,
1657
+ stopped,
1658
+ recoverable: true,
1659
+ })
1660
+ // A background shell's `task_id` is the shell id the tool_result
1661
+ // announced ("Command running in background with ID: <id>"), which
1662
+ // `_recordBackgroundShellsFromToolResults` tracked as pending work
1663
+ // (#4307). The shell dies with the turn's process, so drop it now:
1664
+ // left in place it keeps the roster busy ("waiting on background
1665
+ // work") for a shell nothing will ever read (#8302's shape).
1666
+ if (task.taskType === 'local_bash') this.clearBackgroundShell(task.taskId)
1667
+ }
1668
+ // #8302: and any shell this turn tracked that no live task named (see
1669
+ // `turnShellIds`), reported through the same routine the abnormal-exit
1670
+ // path uses. The process that could report on it ends with the turn.
1671
+ // Before the result is emitted, so the idle snapshot a client takes at
1672
+ // the result already reads idle.
1673
+ reportTurnShells(shellOnlyResults)
1674
+ reapTurnShells()
1675
+
1676
+ if (streamState.hasStreamStarted) {
1677
+ const outcome = outcomeFromSdkResult(msg)
1678
+ this.emit('stream_end', { messageId, ...(msg.is_error === true || (outcome && outcome !== 'completed') ? { interrupted: true } : {}) })
1679
+ }
1680
+
1681
+ if (msg.session_id) {
1682
+ this._sdkSessionId = msg.session_id
1683
+ this._sessionId = msg.session_id
1684
+ }
1685
+
1686
+ // Correct any static context-window guess using the SDK's
1687
+ // authoritative per-model values. Only cache + broadcast when
1688
+ // a value actually changed to avoid thrashy writes / UI churn.
1689
+ let contextWindowChanged = false
1690
+ if (msg.modelUsage && typeof msg.modelUsage === 'object') {
1691
+ const missingIds = []
1692
+ for (const [modelId, usage] of Object.entries(msg.modelUsage)) {
1693
+ if (usage && typeof usage.contextWindow === 'number') {
1694
+ if (updateContextWindow(modelId, usage.contextWindow)) {
1695
+ contextWindowChanged = true
1696
+ }
1697
+ } else {
1698
+ missingIds.push(modelId)
1699
+ }
1700
+ }
1701
+ // Drift signal: at least one modelUsage entry was missing a
1702
+ // numeric contextWindow. Catches both total drift (field renamed
1703
+ // or removed upstream) and partial drift (schema updated for one
1704
+ // model family before another). Log a redacted sample so a
1705
+ // future regression is diagnosable without flooding info-level
1706
+ // output.
1707
+ if (missingIds.length > 0) {
1708
+ const sampleId = missingIds[0]
1709
+ const sampleKeys = Object.keys(msg.modelUsage[sampleId] || {})
1710
+ // #4828: session-scoped (result handler runs strictly post-init).
1711
+ ;(this._log || log).debug(
1712
+ `modelUsage partial drift: contextWindow missing for modelIds=${JSON.stringify(missingIds)} sampleKeys=${JSON.stringify(sampleKeys)}`
1713
+ )
1714
+ }
1715
+ }
1716
+ if (contextWindowChanged) {
1717
+ saveModelsCache()
1718
+ // Notify connected clients so the picker / budget UI picks up
1719
+ // the corrected window without waiting for the next refresh.
1720
+ this.emit('models_updated', { models: getModels() })
1721
+ }
1722
+
1723
+ // #6769: end-of-turn occupancy snapshot via the SDK's
1724
+ // getContextUsage() control API — the same number Claude Code's
1725
+ // own /context shows. Queried while `this._query` is still live
1726
+ // (we're inside the for-await; the CLI process is alive until
1727
+ // the generator completes). `msg.usage` below is the per-turn
1728
+ // BILLING aggregate (summed across agent-loop rounds) and must
1729
+ // never be read as occupancy — see context-window.ts (#6769).
1730
+ // Null on timeout/old-CLI/error → field omitted → clients keep
1731
+ // their previous snapshot (or the honest dash state).
1732
+ // The snapshot asks the session's current query, which a superseding
1733
+ // turn would own; a superseded turn reports without one.
1734
+ const contextUsageSnapshot = (heldPath || superseded) ? null : await this._getContextUsageSnapshot()
1735
+
1736
+ // #8153: emit plan_ready before result — mirrors CliSession's
1737
+ // "the turn that calls ExitPlanMode ends with a normal result
1738
+ // event" ordering. `_planAllowedPrompts` is only non-null once
1739
+ // ExitPlanMode's tool_use block has been parsed (see
1740
+ // _handleToolUseBlock's 'exit_plan' branch above).
1741
+ if (!supersededByNewerTurn() && this._inPlanMode && this._planAllowedPrompts !== null) {
1742
+ this.emit('plan_ready', { allowedPrompts: this._planAllowedPrompts })
1743
+ this._inPlanMode = false
1744
+ this._planAllowedPrompts = null
1745
+ }
1746
+
1747
+ // #4628: sweep any orphan tool_starts before emitting result
1748
+ // so the dashboard's activeTools clears as part of the same
1749
+ // turn-end burst. _clearMessageState (called next) would also
1750
+ // clear the in-flight map but without broadcasting synthetic
1751
+ // tool_results to the dashboard.
1752
+ // A superseded turn emits its result directly: `_emitResult` would
1753
+ // sweep the shared in-flight tool_starts, which are the successor's.
1754
+ ;(supersededByNewerTurn() ? (payload) => emitTurnEvent('result', payload) : (payload, reason, opts) => this._emitResult(payload, reason, opts))({
1755
+ sessionId: msg.session_id || this._sdkSessionId,
1756
+ cost: msg.total_cost_usd,
1757
+ duration: msg.duration_ms,
1758
+ usage: msg.usage,
1759
+ // #6692: surface the per-model split + turn metadata the SDK
1760
+ // already reports instead of discarding them. Additive — every
1761
+ // existing result consumer ignores unknown fields.
1762
+ numTurns: Number.isFinite(msg.num_turns) ? msg.num_turns : null,
1763
+ apiDurationMs: Number.isFinite(msg.duration_api_ms) ? msg.duration_api_ms : null,
1764
+ modelUsage: normalizeSdkModelUsage(msg.modelUsage),
1765
+ // #6769: occupancy snapshot (or absent when unavailable).
1766
+ // Wire field is contextOccupancy — NOT contextUsage — so it can
1767
+ // never be confused with the billing `usage` aggregate above.
1768
+ ...(contextUsageSnapshot ? { contextOccupancy: contextUsageSnapshot } : {}),
1769
+ // #7326: why the turn ended (truncated by max_tokens / max turns /
1770
+ // budget, refused, ...). Omitted when the SDK reported nothing we map.
1771
+ declarationTurnId: messageId,
1772
+ declarationEligible: !supersededByNewerTurn() && !this._stdinForwardingDisabled && sdkDeclarationEligible(msg),
1773
+ ...turnOutcomeField(outcomeFromSdkResult(msg)),
1774
+ }, 'turn_ended_with_orphan_tool_start', { completion: 'normal' }) // #7376
1775
+
1776
+ // #7340: NOT `{ turnEndedCleanly: true }`, however much this looks
1777
+ // like CliSession's `result` branch -- and the difference is the
1778
+ // whole reason that flag is opt-in.
1779
+ //
1780
+ // CliSession owns a PERSISTENT stream-json child that spans turns,
1781
+ // so after its `result` a backgrounded subagent's
1782
+ // `task_notification` still arrives. SdkSession creates one
1783
+ // `query()` PER TURN (`sendMessage`: "Each call creates a new
1784
+ // query() with resume"), and this turn ends it a few lines below:
1785
+ // the streaming input is released, and with live background work
1786
+ // the query is closed outright (#8300). No `task_notification` can
1787
+ // arrive for an agent spared here -- and every recovery route is
1788
+ // closed too: `_handleHardTimeout` / `_handleStreamStall`
1789
+ // early-return on `!_isBusy`, `interrupt()` early-returns on a null
1790
+ // `_query`, and `cancelActivity` answers `not-supported`. The agent
1791
+ // would be stranded until `destroy()`, pinning the session as
1792
+ // working -- the failure #7340 names as the worse one.
1793
+ //
1794
+ // The subagent dies with the query, so completing it here is not
1795
+ // merely safe, it is accurate -- and #8300 says so to the client
1796
+ // (the `background_task_ended_with_turn` error above) instead of
1797
+ // leaving the loss silent. Exempting on this path needs the query
1798
+ // kept alive past `result`, which is a much larger change.
1799
+ if (!supersededByNewerTurn()) this._clearMessageState({ completion: 'normal' }) // #7376
1800
+
1801
+ // #8300: the prompt is answered — release the streaming input so the
1802
+ // SDK closes the CLI's stdin and the process exits once idle. With
1803
+ // live background work the process would NOT go idle (the task keeps
1804
+ // it alive with its tools cancelled), so the query is closed outright;
1805
+ // the abort that follows is expected (see `closedAfterResult`).
1806
+ streamState.hasStreamStarted = false
1807
+ if (input) input.end()
1808
+ if (stopWork.length) closeTurnQuery()
1809
+ }
1810
+
724
1811
  for await (const msg of this._query) {
725
1812
  if (this._destroying) break
726
- resetResultTimeout() // Any SDK event = activity, reset inactivity timer
1813
+ // #8300: a finished turn expects nothing more; a message after the
1814
+ // finish means the process lingered (work this turn could not see
1815
+ // kept it alive). It is not relayed into a turn that is over — the
1816
+ // process is ended instead, and the first such message is logged.
1817
+ if (turnFinished) {
1818
+ // Only another turn's traffic means the process lingered: an init,
1819
+ // assistant output, stream events or tool results. Bookkeeping
1820
+ // that routinely follows a result (task_updated/task_notification
1821
+ // after a stop, status, hook events) is dropped quietly.
1822
+ const lingering = msg?.type === 'assistant' || msg?.type === 'stream_event' || msg?.type === 'user' ||
1823
+ (msg?.type === 'system' && msg?.subtype === 'init')
1824
+ if (lingering && stopsDone && !queryClosed) {
1825
+ ;(this._log || log).warn(`SDK message after the turn's result (${msg?.type}/${msg?.subtype || ''}); ending the lingering process`)
1826
+ closeTurnQuery()
1827
+ }
1828
+ continue
1829
+ }
1830
+ receivedAnyMessage = true // #8030: gates the spawn-failure backstop below
1831
+ // A superseded turn's traffic must not re-arm the session's
1832
+ // inactivity timers against the successor.
1833
+ if (!supersededByNewerTurn()) resetResultTimeout() // Any SDK event = activity, reset inactivity timer
727
1834
 
728
1835
  switch (msg.type) {
729
1836
  case 'system': {
730
1837
  if (msg.subtype === 'init') {
1838
+ // #8300: a second `init` right after a zero-turn `result` is the
1839
+ // CLI starting the prompt's own turn in the same process — the
1840
+ // held result was the orphan-task notice. Say so once and keep
1841
+ // the turn open; the prompt's result is still to come.
1842
+ confirmHeldNotice('a second init followed it')
731
1843
  this._sdkSessionId = msg.session_id
732
1844
  this._sessionId = msg.session_id
733
1845
  // #4828: bind the session-scoped logger now that session_id
@@ -757,6 +1869,13 @@ export class SdkSession extends BaseSession {
757
1869
  }
758
1870
  // Fetch dynamic model list from SDK (non-blocking)
759
1871
  this._fetchSupportedModels()
1872
+ // #8700: and the effort this turn actually runs at (non-blocking).
1873
+ // Caught here because nothing awaits it: a throwing listener on the
1874
+ // `thinking_level_changed` it emits must not become an unhandled
1875
+ // rejection, which ends the daemon (#5313).
1876
+ this._readEffectiveEffort().catch((err) => {
1877
+ ;(this._log || log).warn(`Effort report failed: ${err?.message || err}`)
1878
+ })
760
1879
  } else if (msg.subtype === 'task_started') {
761
1880
  // #5269: a Task subagent started. The SDK message carries BOTH
762
1881
  // the subagent's `task_id` (needed by query.stopTask) and the
@@ -765,6 +1884,49 @@ export class SdkSession extends BaseSession {
765
1884
  // activity id back to a stoppable task. No client-facing emit —
766
1885
  // the agent node already exists via agent_spawned.
767
1886
  this._captureTaskId(msg.tool_use_id, msg.task_id)
1887
+ // #8300: remember the task until its `task_notification`. Only a
1888
+ // task the CLI itself flags `is_backgrounded` counts as live work
1889
+ // at the prompt's result: a foreground Bash is ALSO reported as a
1890
+ // `local_bash` task (with `is_backgrounded: false`) and settles
1891
+ // before the result, so the task type alone says nothing. A
1892
+ // `task_updated` patch can flip the flag later (Ctrl+B-style
1893
+ // backgrounding). `skip_transcript` marks ambient housekeeping
1894
+ // work the user never started; it is never reported as a loss.
1895
+ if (typeof msg.task_id === 'string' && msg.task_id && msg.skip_transcript !== true) {
1896
+ turnTaskIds.add(msg.task_id)
1897
+ this._liveBackgroundTasks.set(msg.task_id, {
1898
+ taskId: msg.task_id,
1899
+ toolUseId: typeof msg.tool_use_id === 'string' ? msg.tool_use_id : null,
1900
+ taskType: typeof msg.task_type === 'string' ? msg.task_type : 'unknown',
1901
+ description: typeof msg.description === 'string' && msg.description
1902
+ ? msg.description
1903
+ : 'Background task',
1904
+ background: msg.is_backgrounded === true,
1905
+ })
1906
+ }
1907
+ // #7340: `task_started` is the provider's OWN lifecycle event and
1908
+ // carries `is_backgrounded` — authoritative where the tool input
1909
+ // is only the model's request. It also arrives regardless of what
1910
+ // the subagent tool is NAMED, so tracking survives a future
1911
+ // rename the way the `Task` -> `Agent` one was not survived.
1912
+ // `task_type` distinguishes a subagent (`local_agent`) from a
1913
+ // backgrounded Bash (`local_bash`), which is #4307's surface and
1914
+ // must not be tracked as an agent.
1915
+ if (msg.task_type === 'local_agent') {
1916
+ this._trackAgent({
1917
+ toolUseId: msg.tool_use_id,
1918
+ description: typeof msg.description === 'string' && msg.description
1919
+ ? msg.description
1920
+ : 'Background task',
1921
+ background: msg.is_backgrounded === true,
1922
+ // #7340: authoritative -- this is the provider's own account,
1923
+ // so it overwrites the model's request in BOTH directions.
1924
+ // It is also the evidence that this build emits task
1925
+ // lifecycle messages at all, which is what makes the
1926
+ // turn-end exemption safe: `task_notification` can arrive.
1927
+ authoritative: true,
1928
+ })
1929
+ }
768
1930
  break
769
1931
  } else if (msg.subtype === 'task_notification') {
770
1932
  // #5269: a Task subagent reached a terminal state (completed /
@@ -773,6 +1935,77 @@ export class SdkSession extends BaseSession {
773
1935
  // cancel feels responsive instead of waiting for the turn-end
774
1936
  // sweep. Idempotent (no-op if already finalized).
775
1937
  this._finalizeAgentByToolUseId(msg.tool_use_id)
1938
+ // #8300: the task is closed; it no longer counts as live work at
1939
+ // the prompt's result.
1940
+ if (typeof msg.task_id === 'string') {
1941
+ this._liveBackgroundTasks.delete(msg.task_id)
1942
+ // #8302: a background shell's `task_id` IS the shell id its
1943
+ // tool_result announced, and a terminal notification is the
1944
+ // only completion signal that still exists (current Claude Code
1945
+ // has no `BashOutput` tool, so the acknowledgement clear can
1946
+ // never fire). Untracked ids are a no-op.
1947
+ this.clearBackgroundShell(msg.task_id)
1948
+ }
1949
+ break
1950
+ } else if (msg.subtype === 'task_updated') {
1951
+ // #8300: a task backgrounded after it started (`patch.is_backgrounded`)
1952
+ // becomes live work; a terminal `patch.status` closes it.
1953
+ const live = typeof msg.task_id === 'string' ? this._liveBackgroundTasks.get(msg.task_id) : null
1954
+ const patch = msg.patch && typeof msg.patch === 'object' ? msg.patch : null
1955
+ if (live && patch) {
1956
+ if (patch.is_backgrounded === true) live.background = true
1957
+ if (typeof patch.description === 'string' && patch.description) live.description = patch.description
1958
+ if (isTerminalTaskStatus(patch.status)) {
1959
+ this._liveBackgroundTasks.delete(msg.task_id)
1960
+ }
1961
+ }
1962
+ // #8302: a terminal status closes the task's shell too — whether
1963
+ // or not the roster holds the task (a `skip_transcript` task is
1964
+ // never on it, yet its shell may still be tracked). Same id
1965
+ // equality and same no-op as the `task_notification` branch.
1966
+ if (patch && typeof msg.task_id === 'string' && isTerminalTaskStatus(patch.status)) {
1967
+ this.clearBackgroundShell(msg.task_id)
1968
+ }
1969
+ break
1970
+ } else if (msg.subtype === 'compact_boundary') {
1971
+ // #6768: the SDK compacted the conversation (auto-triggered
1972
+ // near the context limit, or manually via `/compact`). Parse
1973
+ // the structured `compact_metadata` into a distinct marker
1974
+ // instead of letting it fall through to the generic
1975
+ // "unknown system event" branch below, which would forward
1976
+ // the literal string `compact_boundary` as `content` with no
1977
+ // human-readable text and drop trigger/token/duration data
1978
+ // entirely.
1979
+ const meta = parseCompactBoundaryMeta(msg.compact_metadata)
1980
+ ;(this._log || log).info(
1981
+ `Context compacted (${meta.trigger}): ${meta.preTokens ?? '?'} -> ${meta.postTokens ?? '?'} tokens` +
1982
+ (meta.durationMs != null ? ` in ${meta.durationMs}ms` : '')
1983
+ )
1984
+ this.emit('message', {
1985
+ type: 'system',
1986
+ subtype: 'compact_boundary',
1987
+ content: formatCompactBoundaryContent(meta),
1988
+ compactMetadata: meta,
1989
+ timestamp: Date.now(),
1990
+ })
1991
+ break
1992
+ } else if (msg.subtype === 'status') {
1993
+ // #8153 (review nit): `SDKStatusMessage` carries no
1994
+ // `message`/`text` field, just `status: 'compacting' |
1995
+ // 'requesting' | null` — the generic fallback below would
1996
+ // otherwise forward the bare literal string "status" as a
1997
+ // chat bubble. `status: null` means the previous status
1998
+ // cleared, nothing new to show, so it's suppressed entirely
1999
+ // rather than emitted as an empty/placeholder bubble.
2000
+ const statusText = formatStatusContent(msg.status)
2001
+ if (statusText) {
2002
+ this.emit('message', {
2003
+ type: 'system',
2004
+ subtype: 'status',
2005
+ content: statusText,
2006
+ timestamp: Date.now(),
2007
+ })
2008
+ }
776
2009
  break
777
2010
  } else {
778
2011
  // Forward non-init system events (e.g. /usage, /cost, other
@@ -790,6 +2023,8 @@ export class SdkSession extends BaseSession {
790
2023
  }
791
2024
 
792
2025
  case 'stream_event': {
2026
+ promptActivitySeen = true // #8300: the prompt is running
2027
+ confirmHeldNotice('stream events followed it')
793
2028
  // Handle partial message events (content_block_start/delta/stop)
794
2029
  const event = msg.event
795
2030
  if (!event) break
@@ -811,6 +2046,35 @@ export class SdkSession extends BaseSession {
811
2046
  // #4628: defense-in-depth — track so _emitResult sweep
812
2047
  // catches any orphan if the API ever drops a tool_result.
813
2048
  this._trackToolStart(toolStartData.toolUseId, event.content_block.name)
2049
+ } else if (blockType === 'thinking' || blockType === 'redacted_thinking') {
2050
+ // #6756 — extended-thinking block opened. Open a thinking
2051
+ // stream on a distinct id so reasoning content streams into a
2052
+ // `type: 'thinking'` bubble (not the response slot).
2053
+ // Copilot review on #6817: if a reordered thinking_delta for
2054
+ // this block index already lazily opened the stream, REUSE its
2055
+ // id and don't re-emit stream_start — one block must never
2056
+ // produce two streams.
2057
+ let thinkingId = thinkingBlocks.get(event.index)
2058
+ if (!thinkingId) {
2059
+ thinkingId = `${messageId}-thinking-${thinkingBlockCount++}`
2060
+ thinkingBlocks.set(event.index, thinkingId)
2061
+ // #6391 footer-stat: mark the block's start for the
2062
+ // content_block_stop elapsed-time computation. #6943:
2063
+ // performance.now() (monotonic), not Date.now().
2064
+ thinkingStartMs.set(thinkingId, performance.now())
2065
+ this.emit('stream_start', { messageId: thinkingId, thinking: true })
2066
+ }
2067
+ didStreamThinking = true
2068
+ if (blockType === 'redacted_thinking') {
2069
+ // Redacted thinking carries encrypted `data`, never readable
2070
+ // text — forward a marker so the block is never silently
2071
+ // dropped (its content_block_stop still closes the stream).
2072
+ this.emit('stream_delta', {
2073
+ messageId: thinkingId,
2074
+ delta: '[redacted thinking]',
2075
+ thinking: true,
2076
+ })
2077
+ }
814
2078
  }
815
2079
  break
816
2080
  }
@@ -830,6 +2094,57 @@ export class SdkSession extends BaseSession {
830
2094
  // because both ends are this same process; it's a true
831
2095
  // elapsed duration, unlike the cross-machine serverTs field.
832
2096
  this.emit('stream_delta', { messageId, delta: delta.text, _emitMonoMs: Number(process.hrtime.bigint() / 1_000_000n) })
2097
+ } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
2098
+ // #6756 — reasoning delta. Route to the thinking id opened on
2099
+ // this block's content_block_start; lazy-open if the start was
2100
+ // reordered/dropped so a delta is never lost. `signature_delta`
2101
+ // (the block's signature, not content) falls through untouched.
2102
+ let thinkingId = thinkingBlocks.get(event.index)
2103
+ if (!thinkingId) {
2104
+ thinkingId = `${messageId}-thinking-${thinkingBlockCount++}`
2105
+ thinkingBlocks.set(event.index, thinkingId)
2106
+ // #6391 footer-stat: mark the block's start (lazy-open path)
2107
+ // for the content_block_stop elapsed-time computation.
2108
+ // #6943: performance.now() (monotonic), not Date.now().
2109
+ thinkingStartMs.set(thinkingId, performance.now())
2110
+ this.emit('stream_start', { messageId: thinkingId, thinking: true })
2111
+ }
2112
+ didStreamThinking = true
2113
+ this.emit('stream_delta', { messageId: thinkingId, delta: delta.thinking, thinking: true })
2114
+ }
2115
+ // #8135 (review on #7346): the Agent SDK's `input_json_delta`
2116
+ // chunks (present, since `includePartialMessages: true` is
2117
+ // set) are deliberately NOT forwarded here — a secret can
2118
+ // straddle chunk boundaries and mid-stream partial JSON
2119
+ // can't be sanitized. The sanitized FULL input is delivered
2120
+ // once instead, from `_handleToolUseBlock` below, once the
2121
+ // complete assistant-message `block.input` is known.
2122
+ break
2123
+ }
2124
+
2125
+ case 'content_block_stop': {
2126
+ // #6756 — close the thinking stream for this block so the client
2127
+ // finalises its "Thinking… → Thought" label. Only thinking
2128
+ // blocks are tracked here; text/tool_use blocks are a no-op.
2129
+ const thinkingId = thinkingBlocks.get(event.index)
2130
+ if (thinkingId) {
2131
+ thinkingBlocks.delete(event.index)
2132
+ // #6391 footer-stat: elapsed monotonic time from the block's
2133
+ // open to now → the client's `thought for Xs` footer. Omit
2134
+ // when the start wasn't tracked (defensive) so we never send
2135
+ // a bogus 0. No token count: Anthropic's usage folds thinking
2136
+ // tokens into output_tokens with no per-block breakdown (see
2137
+ // follow-up). #6943: startMs is a performance.now() sample
2138
+ // (monotonic, immune to wall-clock jumps), so elapsed can
2139
+ // never legitimately be negative — Math.max(0, …) is a
2140
+ // defensive floor only, not a correctness requirement.
2141
+ const startMs = thinkingStartMs.get(thinkingId)
2142
+ thinkingStartMs.delete(thinkingId)
2143
+ const streamEndMsg = { messageId: thinkingId, thinking: true }
2144
+ if (typeof startMs === 'number') {
2145
+ streamEndMsg.thinkingDurationMs = Math.max(0, Math.round(performance.now() - startMs))
2146
+ }
2147
+ this.emit('stream_end', streamEndMsg)
833
2148
  }
834
2149
  break
835
2150
  }
@@ -838,8 +2153,29 @@ export class SdkSession extends BaseSession {
838
2153
  }
839
2154
 
840
2155
  case 'assistant': {
2156
+ // #8223: the SDK marks a synthetic assistant message with the failure
2157
+ // class (`SDKAssistantMessage.error`). For `authentication_failed` its
2158
+ // text block is the raw "Failed to authenticate: …" line; surface the
2159
+ // typed error INSTEAD of that text as a chat response, and do not take
2160
+ // this non-turn message as the fork boundary below.
2161
+ if (msg.error === 'authentication_failed') {
2162
+ if (!authRequiredEmitted) {
2163
+ authRequiredEmitted = true
2164
+ ;(this._log || log).warn('Assistant message reported authentication_failed')
2165
+ emitTurnEvent('error', this._authRequiredPayload())
2166
+ }
2167
+ break
2168
+ }
2169
+ // #6766: remember this message's transcript UUID as the fork
2170
+ // boundary. A checkpoint auto-created at the start of the NEXT turn
2171
+ // captures this as its boundary, so restoring that checkpoint can
2172
+ // fork the conversation truncated to exactly this point.
2173
+ this._captureBoundaryMessage(msg)
2174
+ promptActivitySeen = true // #8300: the prompt is running
2175
+ confirmHeldNotice('assistant output followed it')
841
2176
  // Full assistant message — process content blocks for tool detection
842
2177
  const content = msg.message?.content
2178
+ emitTurnEvent('assistant_response', { responseId: msg.message?.id ?? msg.uuid, text: assistantResponseText(content) })
843
2179
  if (!Array.isArray(content)) break
844
2180
 
845
2181
  for (const block of content) {
@@ -852,6 +2188,20 @@ export class SdkSession extends BaseSession {
852
2188
  })
853
2189
  }
854
2190
 
2191
+ // #6756 — fallback for thinking delivered only on the full
2192
+ // assistant message (partial-message streaming off, or a block the
2193
+ // stream_event path never surfaced). Only fires when NOTHING was
2194
+ // streamed this turn, so the streaming path is never double-emitted.
2195
+ if ((block.type === 'thinking' || block.type === 'redacted_thinking') && !didStreamThinking) {
2196
+ const thinkingId = `${messageId}-thinking-${thinkingBlockCount++}`
2197
+ const text = block.type === 'redacted_thinking'
2198
+ ? '[redacted thinking]'
2199
+ : (typeof block.thinking === 'string' ? block.thinking : '')
2200
+ this.emit('stream_start', { messageId: thinkingId, thinking: true })
2201
+ if (text) this.emit('stream_delta', { messageId: thinkingId, delta: text, thinking: true })
2202
+ this.emit('stream_end', { messageId: thinkingId, thinking: true })
2203
+ }
2204
+
855
2205
  if (block.type === 'tool_use') {
856
2206
  this._handleToolUseBlock(messageId, block)
857
2207
  }
@@ -860,6 +2210,42 @@ export class SdkSession extends BaseSession {
860
2210
  }
861
2211
 
862
2212
  case 'user': {
2213
+ promptActivitySeen = true // #8300: the prompt is running
2214
+ confirmHeldNotice('tool results followed it')
2215
+ // #8300: a tool_result carrying Claude Code's own cancellation text
2216
+ // means the CLI dropped the call WITHOUT asking this session's
2217
+ // PermissionManager — there was no channel to ask on. That is a
2218
+ // runtime fault of the turn, not a decision anyone took, so it is
2219
+ // surfaced as a session error naming the tool and its id (the
2220
+ // tool_result still follows, flagged isError, so the tool_start
2221
+ // it answers is closed). Read BEFORE emitToolResults, which drops
2222
+ // the in-flight entry that carries the tool name.
2223
+ if (Array.isArray(msg.message?.content)) {
2224
+ for (const block of msg.message.content) {
2225
+ if (block?.type !== 'tool_result' || !block.tool_use_id) continue
2226
+ // The CLI's cancellation block is always `is_error: true`; a
2227
+ // tool's OWN output that happens to start with the sentence (a
2228
+ // fetched page, a file, an echo) is not an error block.
2229
+ if (block.is_error !== true) continue
2230
+ // #8363: Stop cancelled this tool's pending prompt; the result is
2231
+ // tagged as a Stop below, and is not a provider-side fault.
2232
+ if (this._stopCancelledToolUseIds.has(block.tool_use_id)) continue
2233
+ const text = toolResultText(block)
2234
+ if (!isSdkToolCancellationText(text)) continue
2235
+ const tool = this._inFlightToolStarts.get(block.tool_use_id)?.tool || 'unknown'
2236
+ const firstLine = text.trim().split('\n')[0].slice(0, 200)
2237
+ ;(this._log || log).error(
2238
+ `Claude Code cancelled the ${tool} tool call ${block.tool_use_id} without consulting the permission pipeline: ${firstLine}`,
2239
+ )
2240
+ emitTurnEvent('error', {
2241
+ code: 'tool_cancelled_by_provider',
2242
+ message: `Claude Code cancelled the ${tool} tool call (${block.tool_use_id}) before it reached the permission pipeline: ${firstLine}`,
2243
+ tool,
2244
+ toolUseId: block.tool_use_id,
2245
+ recoverable: true,
2246
+ })
2247
+ }
2248
+ }
863
2249
  // Tool result content blocks appear in user-role messages during the tool loop
864
2250
  emitToolResults(msg.message?.content, this)
865
2251
  // #4307: scan tool_result blocks for the canonical
@@ -870,114 +2256,238 @@ export class SdkSession extends BaseSession {
870
2256
  // truncation surface (tool-result.js is also used by
871
2257
  // CliSession + GeminiSession, which don't share this
872
2258
  // BaseSession path).
873
- this._recordBackgroundShellsFromToolResults(msg.message?.content)
2259
+ this._recordBackgroundShellsFromToolResults(msg.message?.content, turnShellIds)
874
2260
  break
875
2261
  }
876
2262
 
877
2263
  case 'result': {
878
- if (streamState.hasStreamStarted) {
879
- this.emit('stream_end', { messageId })
880
- }
881
-
882
- if (msg.session_id) {
883
- this._sdkSessionId = msg.session_id
884
- this._sessionId = msg.session_id
885
- }
886
-
887
- // Correct any static context-window guess using the SDK's
888
- // authoritative per-model values. Only cache + broadcast when
889
- // a value actually changed to avoid thrashy writes / UI churn.
890
- let contextWindowChanged = false
891
- if (msg.modelUsage && typeof msg.modelUsage === 'object') {
892
- const missingIds = []
893
- for (const [modelId, usage] of Object.entries(msg.modelUsage)) {
894
- if (usage && typeof usage.contextWindow === 'number') {
895
- if (updateContextWindow(modelId, usage.contextWindow)) {
896
- contextWindowChanged = true
897
- }
898
- } else {
899
- missingIds.push(modelId)
900
- }
901
- }
902
- // Drift signal: at least one modelUsage entry was missing a
903
- // numeric contextWindow. Catches both total drift (field renamed
904
- // or removed upstream) and partial drift (schema updated for one
905
- // model family before another). Log a redacted sample so a
906
- // future regression is diagnosable without flooding info-level
907
- // output.
908
- if (missingIds.length > 0) {
909
- const sampleId = missingIds[0]
910
- const sampleKeys = Object.keys(msg.modelUsage[sampleId] || {})
911
- // #4828: session-scoped (result handler runs strictly post-init).
912
- ;(this._log || log).debug(
913
- `modelUsage partial drift: contextWindow missing for modelIds=${JSON.stringify(missingIds)} sampleKeys=${JSON.stringify(sampleKeys)}`
914
- )
915
- }
916
- }
917
- if (contextWindowChanged) {
918
- saveModelsCache()
919
- // Notify connected clients so the picker / budget UI picks up
920
- // the corrected window without waiting for the next refresh.
921
- this.emit('models_updated', { models: getModels() })
2264
+ // #8300: on `--resume` the CLI can run an orphan-task notice as its
2265
+ // own zero-cost turn BEFORE the prompt: `init` → this result with
2266
+ // `num_turns: 0` → a second `init`. Taking it as the prompt's
2267
+ // result would end the turn (and the input) under the prompt.
2268
+ // Hold it: the next `init` confirms the notice; if none comes
2269
+ // within ORPHAN_NOTICE_CONFIRM_MS it was the prompt's own, the
2270
+ // input is released so the CLI exits, and the loop's end finishes
2271
+ // the held result below.
2272
+ // A further result while one is held: the held one was the notice
2273
+ // (the CLI ran another turn after it); this one is judged afresh.
2274
+ confirmHeldNotice('a further result followed it')
2275
+ if (msg.num_turns === 0 && msg.is_error !== true && !promptActivitySeen) {
2276
+ heldNoticeResult = msg
2277
+ ;(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`)
2278
+ // On expiry the held result is finished HERE, while the loop is
2279
+ // parked on the generator and the query is still live: finishTurn
2280
+ // releases the input and, if background work is keeping the
2281
+ // process alive, stops it and closes the query — so the turn can
2282
+ // never depend on an EOF that such work would withhold.
2283
+ noticeTimer = setTimeout(() => {
2284
+ noticeTimer = null
2285
+ if (heldNoticeResult === null || this._destroying) return
2286
+ const held = heldNoticeResult
2287
+ heldNoticeResult = null
2288
+ ;(this._log || log).info('No init followed the zero-turn result within the window; taking it as the prompt\'s own')
2289
+ timerFinish = finishTurn(held, { heldPath: true }).catch((err) => {
2290
+ ;(this._log || log).warn(`Finishing the held result failed: ${err?.message || err}`)
2291
+ })
2292
+ }, SdkSession.ORPHAN_NOTICE_CONFIRM_MS)
2293
+ break
922
2294
  }
923
-
924
- // #4628: sweep any orphan tool_starts before emitting result
925
- // so the dashboard's activeTools clears as part of the same
926
- // turn-end burst. _clearMessageState (called next) would also
927
- // clear the in-flight map but without broadcasting synthetic
928
- // tool_results to the dashboard.
929
- this._emitResult({
930
- sessionId: msg.session_id || this._sdkSessionId,
931
- cost: msg.total_cost_usd,
932
- duration: msg.duration_ms,
933
- usage: msg.usage,
934
- }, 'turn_ended_with_orphan_tool_start')
935
-
936
- this._clearMessageState()
2295
+ await finishTurn(msg)
937
2296
  break
938
2297
  }
939
2298
  }
940
2299
  }
2300
+ // #8300: the loop ended (the CLI exited on its own) with a zero-turn
2301
+ // result still held and no init after it — it was the prompt's own.
2302
+ if (timerFinish) await timerFinish
2303
+ if (heldNoticeResult !== null && !this._destroying) {
2304
+ const held = heldNoticeResult
2305
+ heldNoticeResult = null
2306
+ await finishTurn(held, { heldPath: true })
2307
+ }
941
2308
  } catch (err) {
2309
+ // #8302: the query threw; its control channel is gone (see `queryFailed`).
2310
+ queryFailed = true
2311
+ // #8300: a held zero-turn result dies with the loop — its timer must
2312
+ // not finish a turn that is being reported as failed below.
2313
+ if (noticeTimer) {
2314
+ clearTimeout(noticeTimer)
2315
+ noticeTimer = null
2316
+ }
2317
+ heldNoticeResult = null
2318
+ // #8300: a timer-driven finish may be mid-flight (stopping live work);
2319
+ // let it complete so its result precedes any error surfaced below and
2320
+ // nothing it emits lands after `_clearMessageState`.
2321
+ if (timerFinish) {
2322
+ try { await timerFinish } catch { /* logged where it was started */ }
2323
+ }
942
2324
  if (streamState.hasStreamStarted) {
943
2325
  this.emit('stream_end', { messageId })
944
2326
  }
945
2327
  // #4881: capture-and-clear before any branch so the flag never leaks
946
2328
  // past this turn even when _destroying short-circuits the emits below.
947
2329
  // Mirrors CliSession._handleChildClose (#4602).
948
- const wasIntentionalStop = this._consumeIntentionalStop()
2330
+ // A superseded turn leaves the Stop flag to the turn it belongs to.
2331
+ const wasIntentionalStop = supersededByNewerTurn() ? false : this._consumeIntentionalStop()
2332
+ // #8430: whether the USER's Stop is what ended this turn is decided NOW, with
2333
+ // `wasIntentionalStop`. The failure handling below can await (container
2334
+ // classification), and a Stop that lands during that await did not end a turn
2335
+ // that had already failed.
2336
+ const userStopEndedTurn = this._permissions.isUserStopInFlight()
949
2337
  if (!this._destroying) {
950
- if (wasIntentionalStop) {
2338
+ if (closedAfterResult && isQueryCloseError(err)) {
2339
+ // #8300: finishTurn already emitted this turn's result and closed
2340
+ // the query on purpose (background work was still live); the abort
2341
+ // the SDK throws for that is expected, not a turn failure. Any
2342
+ // OTHER error after the close is still surfaced below.
2343
+ ;(this._log || log).debug(`Query closed after the turn's result: ${err?.message || err}`)
2344
+ } else if (wasIntentionalStop) {
951
2345
  // #4881: user clicked Stop — interrupt() set the flag, the SDK
952
2346
  // generator threw an AbortError as a result. Skip the loud "Query
953
2347
  // error" surface and emit the quiet `stopped` event for parity
954
2348
  // with CliSession. No `code` because SDK runs in-process — there
955
2349
  // is no child-process exit status to carry.
956
2350
  ;(this._log || log).info('Query aborted after user stop')
957
- this.emit('stopped', {})
2351
+ emitTurnEvent('stopped', {})
2352
+ } else if (spawnRefused) {
2353
+ // #8030: the turn was refused BEFORE query() was ever called — by the
2354
+ // per-spawn binary gate (a block-mode hash mismatch, quarantine, a
2355
+ // vanished pinned binary, …) or because a containerised session has
2356
+ // no in-container spawn hook yet. Two things this branch deliberately
2357
+ // does NOT do:
2358
+ // - route through _enrichErrorMessage: a provenance message
2359
+ // embeds a hex hash prefix (e.g. "...a4291b0c...") that can
2360
+ // match the rate-limit ("429") or auth ("401") patterns in
2361
+ // _ERROR_PATTERNS and get silently rewritten into a wrong,
2362
+ // misleading "rate limit"/"auth failed" message instead of the
2363
+ // real cause.
2364
+ // - run container classification: the turn never reached the
2365
+ // SDK, so there is no container to have vanished.
2366
+ // #8035: hoisted onto BaseSession (`_refuseTurnBeforeDispatch`) so
2367
+ // JsonlSubprocessSession's per-turn spawn gets byte-identical wire
2368
+ // shape instead of a second hand-rolled copy.
2369
+ this._refuseTurnBeforeDispatch(err, sendOptions, this._log || log)
958
2370
  } else {
959
- // #4828: session-scoped when init has fired; falls back to module
960
- // `log` for pre-init query failures (e.g. spawn refused).
961
- ;(this._log || log).error(`Query error: ${err.message}`)
962
- this.emit('error', { message: SdkSession._enrichErrorMessage(err.message) })
2371
+ // #7599: let a containerized subclass classify this turn failure as a
2372
+ // vanished container (a distinct, recoverable state) before the
2373
+ // generic query-error surface. Base returns null; DockerSdkSession
2374
+ // probes the container and returns a CONTAINER_VANISHED payload.
2375
+ const containerGone = await this._classifyContainerFailure(err)
2376
+ // #7599: _classifyContainerFailure can await a real `docker exec` probe
2377
+ // (up to 10s). A destroy() landing in that window has already torn the
2378
+ // session down and removed its listeners, so emitting here would fire
2379
+ // on a dead EventEmitter (Node throws on an unhandled 'error'). Re-check
2380
+ // teardown after the await before surfacing anything.
2381
+ if (this._destroying) {
2382
+ // fall through to _clearMessageState below; destroy() owns the UX
2383
+ } else if (containerGone) {
2384
+ ;(this._log || log).warn(`Container vanished during turn: ${containerGone.message}`)
2385
+ emitTurnEvent('error', containerGone)
2386
+ } else {
2387
+ // #8030 backstop: a spawn failure AFTER preflight passed (the
2388
+ // pinned binary was quarantined/moved/removed between the gate
2389
+ // call above and the actual exec, or the gate wasn't wired at
2390
+ // all) surfaces from the SDK as generic text ("native binary ...
2391
+ // failed to launch"). Re-verify the ATTEMPTED path and label the
2392
+ // real cause + fix, the same backstop cli-session.js /
2393
+ // jsonl-subprocess-session.js run for their own spawns — but only
2394
+ // when this is plausibly a launch failure: no SDK message has
2395
+ // arrived yet this turn, a path was actually attempted, and the
2396
+ // provider isn't containerised (its binary lives inside a
2397
+ // container a host-side verify can't see).
2398
+ const labeled = (!receivedAnyMessage && spawnPath && !this.constructor.capabilities?.containerized)
2399
+ ? labelBinarySpawnFailure({ attemptedPath: spawnPath, binary: 'claude' })
2400
+ : null
2401
+ // #4828: session-scoped when init has fired; falls back to module
2402
+ // `log` for pre-init query failures (e.g. spawn refused).
2403
+ ;(this._log || log).error(`Query error: ${err.message}`)
2404
+ // #8223: an auth-shaped failure carries AUTH_REQUIRED (so the clients
2405
+ // render the sign-in card) unless this turn already surfaced one from
2406
+ // the assistant message. A binary-launch label wins over classification,
2407
+ // exactly as it wins over enrichment.
2408
+ const classified = labeled ? { message: labeled } : SdkSession._classifyError(err.message)
2409
+ if (classified.code === AUTH_REQUIRED_CODE) {
2410
+ if (!authRequiredEmitted) {
2411
+ authRequiredEmitted = true
2412
+ emitTurnEvent('error', this._authRequiredPayload())
2413
+ }
2414
+ } else {
2415
+ emitTurnEvent('error', { message: classified.message })
2416
+ }
2417
+ }
963
2418
  }
964
2419
  }
965
- this._clearMessageState()
2420
+ // #7376: a Stop that aborted the query leaves its in-flight tools "stopped",
2421
+ // and a CLI process that exited under the query leaves them cut off by the
2422
+ // exit; neither is a failed command. Any other throw has no considered
2423
+ // cause and keeps the generic sweep.
2424
+ if (!supersededByNewerTurn()) {
2425
+ this._clearMessageState({
2426
+ ...(wasIntentionalStop
2427
+ ? { terminatedReason: 'user_stop' }
2428
+ : isProcessExitError(err) ? { terminatedReason: 'process_exit' } : {}),
2429
+ userStop: userStopEndedTurn,
2430
+ })
2431
+ }
966
2432
  } finally {
967
- this._query = null
2433
+ // #8300: whatever ended the loop — the prompt's result, a throw, a
2434
+ // destroy() break — the streaming input is released here, so the SDK
2435
+ // closes the CLI's stdin and the process can exit. Idempotent; the
2436
+ // normal path already ended it in finishTurn. A still-pending notice
2437
+ // timer is dropped with the turn.
2438
+ if (noticeTimer) {
2439
+ clearTimeout(noticeTimer)
2440
+ noticeTimer = null
2441
+ }
2442
+ if (timerFinish) {
2443
+ try { await timerFinish } catch { /* logged where it was started */ }
2444
+ }
2445
+ if (input) input.end()
2446
+ if (this._turnInput === input) this._turnInput = null
2447
+ if (this._query === turnQuery) this._query = null
2448
+ // #8300: whatever this turn saw start is gone with its process.
2449
+ for (const taskId of turnTaskIds) this._liveBackgroundTasks.delete(taskId)
2450
+ // #8302: ...and so is every shell it started, whatever ended the loop (a
2451
+ // throw, a destroy, a result with no live task to report). Without this a
2452
+ // shell that died or was never acknowledged left the session reading busy
2453
+ // forever on a provider that has no `BashOutput` to clear it.
2454
+ //
2455
+ // On the normal path `finishTurn` has already stopped, reported and
2456
+ // released them. What reaches here are the abnormal exits (an AbortError, a
2457
+ // crash): ask the CLI to stop each still-tracked shell while the channel is
2458
+ // still usable, and where it is not, SAY each one is unconfirmed instead of
2459
+ // forgetting it. destroy() owns its own UX and reports nothing.
2460
+ // #8321: the drain is held until just before the flush below, whatever
2461
+ // happens here, so a send during these awaits queues behind older ones
2462
+ // instead of overtaking them.
2463
+ try {
2464
+ if (!this._destroying) {
2465
+ const leftover = turnShellsToStop()
2466
+ if (leftover.length > 0) {
2467
+ const channelUsable = !queryFailed && !queryClosed && !!turnQuery
2468
+ const results = await stopTurnShells(leftover, channelUsable)
2469
+ if (!this._destroying) reportTurnShells(results)
2470
+ }
2471
+ }
2472
+ reapTurnShells()
968
2473
  // #4881: safety-net clear of _intentionalStop. The catch block clears
969
2474
  // it on the throw path (AbortError after interrupt()), but if
970
2475
  // query.interrupt() races a `result` message arriving first, the
971
2476
  // for-await loop exits normally, skipping the catch. Without this
972
2477
  // clear, the flag would stay armed until the next turn's catch and
973
2478
  // mis-trigger a spurious `stopped` emit there. Idempotent — the
974
- // catch path already cleared it on the throw path.
975
- this._clearIntentionalStop()
2479
+ // catch path already cleared it on the throw path. Not for a
2480
+ // superseded turn: the flag is then the successor's.
2481
+ if (!supersededByNewerTurn()) this._clearIntentionalStop()
2482
+ } finally {
2483
+ // The generator has ended; a follow-up queued behind it may now run.
2484
+ if (turnDrain) this._endDrain(turnDrain)
2485
+ }
976
2486
  // Dequeue any follow-up messages that arrived while busy (#5936: the
977
2487
  // shared `_outgoingQueue`; flush one item via dequeueNextOutgoing, whose
978
2488
  // re-dispatched sendMessage re-sets _isBusy so the next `result` drains
979
2489
  // the following item — FIFO, one turn at a time).
980
- if (this._outgoingQueue.length && !this._destroying) {
2490
+ if (this._outgoingQueue.length && !this._destroying && !supersededByNewerTurn()) {
981
2491
  // #3562: if the SidecarProcess latched stdin_disabled mid-turn (e.g.
982
2492
  // the PassThrough closed while _callQuery was still streaming), the
983
2493
  // entry-gate at the top of sendMessage has already been bypassed
@@ -1012,6 +2522,168 @@ export class SdkSession extends BaseSession {
1012
2522
  return query(queryArgs)
1013
2523
  }
1014
2524
 
2525
+ /**
2526
+ * #8300: the turn's streaming input — an async iterable that yields the
2527
+ * prompt's user message once and then stays open until `end()` is called.
2528
+ *
2529
+ * The Agent SDK decides when to close the CLI's stdin from the SHAPE of
2530
+ * `prompt`: a string marks the query single-turn and stdin closes at the
2531
+ * first `result`; an iterable keeps stdin open until the iterable ends. The
2532
+ * turn therefore owns the close: `finishTurn` ends the iterable once the
2533
+ * result that answers the prompt has been processed, and `sendMessage`'s
2534
+ * `finally` ends it on every other exit so the CLI is never left waiting.
2535
+ *
2536
+ * @param {object} userMessage - the SDKUserMessage to send
2537
+ * @returns {{ iterable: AsyncIterable<object>, end: () => void, readonly ended: boolean }}
2538
+ */
2539
+ _createTurnInput(userMessage) {
2540
+ let release
2541
+ const released = new Promise((resolve) => { release = resolve })
2542
+ let ended = false
2543
+ const end = () => {
2544
+ if (ended) return
2545
+ ended = true
2546
+ release()
2547
+ }
2548
+ const iterable = (async function* () {
2549
+ yield userMessage
2550
+ await released
2551
+ })()
2552
+ return {
2553
+ iterable,
2554
+ end,
2555
+ get ended() { return ended },
2556
+ }
2557
+ }
2558
+
2559
+ /**
2560
+ * #8300: background work the CLI reported as started and never closed. Read
2561
+ * at the prompt's result; anything still here would outlive the turn's
2562
+ * process.
2563
+ *
2564
+ * @returns {Array<{taskId:string,toolUseId:string|null,taskType:string,description:string,background:boolean}>}
2565
+ */
2566
+ _liveBackgroundWork() {
2567
+ // A `local_bash` task whose shell the tool_result announced ("Command
2568
+ // running in background with ID: <id>", tracked by
2569
+ // `_recordBackgroundShellsFromToolResults`) is background work whatever
2570
+ // `task_started` said: a foreground Bash never produces that text. This
2571
+ // keeps shell detection working if a CLI build stops sending the
2572
+ // undocumented `is_backgrounded` field on `task_started`.
2573
+ return [...this._liveBackgroundTasks.values()].filter((task) =>
2574
+ task.background === true ||
2575
+ (task.taskType === 'local_bash' && this._pendingBackgroundShells.has(task.taskId)))
2576
+ }
2577
+
2578
+ // #8300: bound on `Query.stopTask()` at the turn's result. The CLI answers
2579
+ // the control request in milliseconds when alive; the cap only bites when
2580
+ // it is already gone, in which case the task is reported as not stopped.
2581
+ static STOP_TASK_TIMEOUT_MS = 3000
2582
+ // #8321: how long a follow-up may wait behind a previous query's generator
2583
+ // that is still draining after the turn's result, before that query is
2584
+ // closed, and the further grace after the close before the hold is dropped.
2585
+ static DRAIN_WAIT_MS = 10000
2586
+ static DRAIN_FORCE_GRACE_MS = 3000
2587
+
2588
+ /**
2589
+ * #8300: ask the CLI to stop a task that would outlive the turn, via the
2590
+ * SDK's `stopTask` control request. Resolves true when the CLI acknowledged
2591
+ * the stop, false when the query has no `stopTask`, it threw, or it did not
2592
+ * answer within STOP_TASK_TIMEOUT_MS. Never throws.
2593
+ *
2594
+ * @param {object|null} q - the turn's own query handle
2595
+ * @param {string} taskId
2596
+ * @returns {Promise<boolean>}
2597
+ */
2598
+ async _stopLiveTask(q, taskId) {
2599
+ if (!q || typeof q.stopTask !== 'function') return false
2600
+ let timer = null
2601
+ try {
2602
+ const timeout = new Promise((resolve) => {
2603
+ timer = setTimeout(() => resolve(false), SdkSession.STOP_TASK_TIMEOUT_MS)
2604
+ })
2605
+ const ok = await Promise.race([q.stopTask(taskId).then(() => true), timeout])
2606
+ if (!ok) (this._log || log).warn(`stopTask(${taskId}) did not answer within ${SdkSession.STOP_TASK_TIMEOUT_MS}ms`)
2607
+ return ok === true
2608
+ } catch (err) {
2609
+ ;(this._log || log).warn(`stopTask(${taskId}) failed: ${err?.message || err}`)
2610
+ return false
2611
+ } finally {
2612
+ if (timer) clearTimeout(timer)
2613
+ }
2614
+ }
2615
+
2616
+ /**
2617
+ * #7599 — hook for a containerized subclass to classify a turn failure as a
2618
+ * vanished container. Called from the query catch before the generic error
2619
+ * surface. The base in-process SdkSession has no container, so it never
2620
+ * classifies a failure this way.
2621
+ *
2622
+ * @param {Error} _err the error the query threw
2623
+ * @returns {Promise<{code:string,message:string,recoverable?:boolean}|null>}
2624
+ * a session-error payload to emit instead of the generic one, or null
2625
+ */
2626
+ async _classifyContainerFailure(_err) {
2627
+ return null
2628
+ }
2629
+
2630
+ /**
2631
+ * #6769: fetch the end-of-turn context-window OCCUPANCY snapshot from the
2632
+ * SDK's `getContextUsage()` control API (verified on
2633
+ * @anthropic-ai/claude-agent-sdk 0.2.114: sdk.d.ts declares
2634
+ * `Query.getContextUsage(): Promise<SDKControlGetContextUsageResponse>` with
2635
+ * `totalTokens` / `maxTokens` / `percentage` / `autoCompactThreshold` (in
2636
+ * TOKENS — the CLI compares it directly against token counts) /
2637
+ * `isAutoCompactEnabled`).
2638
+ *
2639
+ * This is the ONLY honest occupancy source for this provider: the result
2640
+ * message's own `usage` is the per-turn billing aggregate summed across
2641
+ * agent-loop rounds (+ subagents) and over-reads window fill ≈N× on an
2642
+ * N-round turn.
2643
+ *
2644
+ * Fail-soft by design — returns null (result emits without the field) when:
2645
+ * - the query is gone or the installed SDK predates the API (typeof guard)
2646
+ * - the control request errors (CLI already shutting down post-result)
2647
+ * - the response doesn't arrive within the timeout (bounds the latency
2648
+ * this adds to the turn-end result broadcast)
2649
+ * - the response lacks a finite totalTokens
2650
+ * Clients treat a missing field as "keep the previous snapshot / dash".
2651
+ *
2652
+ * @returns {Promise<{totalTokens: number, maxTokens: number|null, autoCompactThreshold: number|null, isAutoCompactEnabled: boolean|null, source: 'context-usage-api'}|null>}
2653
+ */
2654
+ async _getContextUsageSnapshot() {
2655
+ const q = this._query
2656
+ if (!q || typeof q.getContextUsage !== 'function') return null
2657
+ let timer = null
2658
+ try {
2659
+ const timeout = new Promise((resolve) => {
2660
+ timer = setTimeout(() => resolve(null), SdkSession.CONTEXT_USAGE_SNAPSHOT_TIMEOUT_MS)
2661
+ // Don't hold the process open for a race that already resolved (#6027).
2662
+ if (typeof timer.unref === 'function') timer.unref()
2663
+ })
2664
+ const res = await Promise.race([q.getContextUsage(), timeout])
2665
+ if (!res || typeof res.totalTokens !== 'number' || !Number.isFinite(res.totalTokens) || res.totalTokens < 0) {
2666
+ if (!res) {
2667
+ ;(this._log || log).debug('getContextUsage() timed out or returned nothing — result emits without occupancy')
2668
+ }
2669
+ return null
2670
+ }
2671
+ const pos = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null)
2672
+ return {
2673
+ totalTokens: res.totalTokens,
2674
+ maxTokens: pos(res.maxTokens),
2675
+ autoCompactThreshold: pos(res.autoCompactThreshold),
2676
+ isAutoCompactEnabled: typeof res.isAutoCompactEnabled === 'boolean' ? res.isAutoCompactEnabled : null,
2677
+ source: 'context-usage-api',
2678
+ }
2679
+ } catch (err) {
2680
+ ;(this._log || log).debug(`getContextUsage() failed (${err?.message || err}) — result emits without occupancy`)
2681
+ return null
2682
+ } finally {
2683
+ if (timer) clearTimeout(timer)
2684
+ }
2685
+ }
2686
+
1015
2687
  /**
1016
2688
  * Hook for subclasses to modify query options before they're passed to query().
1017
2689
  * Default implementation is a no-op. Override in subclasses that need to inject
@@ -1191,10 +2863,39 @@ export class SdkSession extends BaseSession {
1191
2863
  ;(this._log || log).warn(`Tool input for ${block.name} exceeded ${this._maxToolInput} bytes, skipping`)
1192
2864
  this.emit('error', {
1193
2865
  message: `Tool input too large (>${Math.round(this._maxToolInput / 1024)}KB) for ${block.name} — tool use was skipped`,
2866
+ declarationTurnId: messageId,
1194
2867
  })
1195
2868
  return
1196
2869
  }
1197
2870
 
2871
+ // #7346: backfill the finalized input onto the in-flight tool_start
2872
+ // tracking entry (`_trackToolStart` / base-session.js
2873
+ // `_recordToolInput`, which sanitizes + size-caps it — see
2874
+ // #8135/#8136) so `tool-result.js`'s `emitToolResults` can attach it
2875
+ // to the matching `tool_result` (`_getTrackedToolInput`). Runs for
2876
+ // EVERY tool_use block, not just the Task/plan-mode ones handled
2877
+ // below: the full "assistant" message this function is called from
2878
+ // always carries the complete `block.input`, so (unlike CliSession,
2879
+ // which must accumulate `input_json_delta` chunks) no buffering is
2880
+ // needed. Mirrors the `${messageId}-tool` fallback `buildToolStartData`
2881
+ // uses (and the Task branch below reuses) so the id always matches
2882
+ // whatever `_trackToolStart` was called with at `content_block_start`.
2883
+ const toolUseId = block.id || `${messageId}-tool`
2884
+ const sanitizedInput = this._recordToolInput(toolUseId, block.input ?? null)
2885
+ // #8135 (review): deliver the SANITIZED input as a single-shot
2886
+ // `tool_input_delta` here — this is the earliest point SdkSession
2887
+ // knows the full value, milliseconds after the block finalized and
2888
+ // well before the tool finishes executing. `null`/`undefined` means
2889
+ // "known to have no input" (the placeholder logic covers that on
2890
+ // its own); don't ship a literal "null" chunk for it.
2891
+ if (sanitizedInput !== null && sanitizedInput !== undefined) {
2892
+ this.emit('tool_input_delta', {
2893
+ messageId,
2894
+ toolUseId,
2895
+ partialJson: JSON.stringify(sanitizedInput),
2896
+ })
2897
+ }
2898
+
1198
2899
  // #4307: stash the command text against the tool_use_id so the
1199
2900
  // matching tool_result (carrying the shellId Claude prints) can
1200
2901
  // recover it. Strict-boolean run_in_background check; non-Bash
@@ -1227,18 +2928,34 @@ export class SdkSession extends BaseSession {
1227
2928
  // agent_spawned toolUseId + _activeAgents key match the wire-emitted
1228
2929
  // tool_start id. Without this, _activeAgents.set(undefined, ...)
1229
2930
  // collides on undefined for any fallback-path Task spawn.
1230
- const toolUseId = block.id || `${messageId}-tool`
1231
- const agentInfo = {
2931
+ // (#7346: reuses the same `toolUseId` computed above — one fallback
2932
+ // derivation, not two.)
2933
+ // #7340: this records the MODEL'S REQUEST (`run_in_background`) into
2934
+ // `background`. It does NOT exempt the agent from the turn-end sweep —
2935
+ // `backgroundConfirmed` does, and only `task_started` can set that.
2936
+ // (On this provider nothing is exempted at all; see the `result` branch.)
2937
+ // Whichever signal lands first wins via `_trackAgent`'s upgrade.
2938
+ this._trackAgent({
1232
2939
  toolUseId,
1233
2940
  description: semantics.payload.description,
1234
- startedAt: Date.now(),
1235
- }
1236
- this._activeAgents.set(toolUseId, agentInfo)
1237
- this.emit('agent_spawned', agentInfo)
2941
+ background: semantics.payload.background,
2942
+ })
2943
+ }
2944
+ // #8153: EnterPlanMode / ExitPlanMode wiring, mirroring CliSession's
2945
+ // _applyToolInputSemantics. `permissionMode: 'plan'` is a literal
2946
+ // `--permission-mode plan` pass-through to the same `claude` CLI binary
2947
+ // CliSession spawns (query() execs `pathToClaudeCodeExecutable`, #7986),
2948
+ // so the native read-only enforcement and EnterPlanMode/ExitPlanMode tool
2949
+ // calls are identical on both providers — only the event wiring was
2950
+ // missing here. Unlike CliSession (which buffers `toolInputChunks` across
2951
+ // stream deltas), SdkSession receives the full `block.input` directly, so
2952
+ // there is no overflow-discard case to special-case.
2953
+ if (semantics.kind === 'enter_plan') {
2954
+ this._inPlanMode = true
2955
+ this.emit('plan_started')
2956
+ } else if (semantics.kind === 'exit_plan') {
2957
+ this._planAllowedPrompts = semantics.payload.allowedPrompts
1238
2958
  }
1239
- // EnterPlanMode / ExitPlanMode are not currently surfaced by SdkSession
1240
- // (plan-mode flow is CliSession-only today). Extracting via the shared
1241
- // parser leaves the door open without changing observable behavior.
1242
2959
  }
1243
2960
 
1244
2961
  /**
@@ -1252,9 +2969,11 @@ export class SdkSession extends BaseSession {
1252
2969
  * (no-op) — the standard tool-loop flow always populates both.
1253
2970
  *
1254
2971
  * @param {unknown} content
2972
+ * @param {Set<string>|null} [ownedShellIds] - #8302: the calling turn's set;
2973
+ * every shell newly tracked here is added to it.
1255
2974
  * @private
1256
2975
  */
1257
- _recordBackgroundShellsFromToolResults(content) {
2976
+ _recordBackgroundShellsFromToolResults(content, ownedShellIds = null) {
1258
2977
  if (!Array.isArray(content)) return
1259
2978
  for (const block of content) {
1260
2979
  if (block?.type !== 'tool_result' || !block.tool_use_id) continue
@@ -1276,7 +2995,8 @@ export class SdkSession extends BaseSession {
1276
2995
  // #5177: capture the output file path from the same tool_result so the
1277
2996
  // completion sweep can reap the shell on quiescence without a poll.
1278
2997
  const outputPath = parseBackgroundShellOutputPath(text)
1279
- this.trackBackgroundShell({ shellId, command, outputPath })
2998
+ // #8302: remember which turn started it, so that turn's end can release it.
2999
+ if (this.trackBackgroundShell({ shellId, command, outputPath })) ownedShellIds?.add(shellId)
1280
3000
  }
1281
3001
  }
1282
3002
 
@@ -1284,16 +3004,146 @@ export class SdkSession extends BaseSession {
1284
3004
  * In-process permission handler for canUseTool callback.
1285
3005
  * Delegates to the PermissionManager.
1286
3006
  */
1287
- _handlePermission(toolName, input, signal, suggestions) {
1288
- return this._permissions.handlePermission(toolName, input, signal, this.permissionMode, suggestions)
3007
+ _handlePermission(toolName, input, signal, suggestions, toolUseId = undefined) {
3008
+ return this._trackPermissionDecision(
3009
+ toolUseId,
3010
+ this._permissions.handlePermission(toolName, input, signal, this.permissionMode, suggestions, toolUseId),
3011
+ )
3012
+ }
3013
+
3014
+ /**
3015
+ * #8363: follow a permission decision from the moment the provider asks until
3016
+ * it settles, so `interrupt()` knows which tool calls Stop caught mid-prompt.
3017
+ * Passes the decision through unchanged. An `allow` removes the call from the
3018
+ * stopped set again: if the user approved it in the instant between Stop and
3019
+ * the abort, the tool may run and its result is a real one.
3020
+ * @param {string|undefined} toolUseId
3021
+ * @param {Promise<{behavior: string}>} decision
3022
+ * @returns {Promise<{behavior: string}>}
3023
+ */
3024
+ _trackPermissionDecision(toolUseId, decision) {
3025
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) return decision
3026
+ this._pendingPermissionToolUseIds.add(toolUseId)
3027
+ const settled = (result) => {
3028
+ this._pendingPermissionToolUseIds.delete(toolUseId)
3029
+ if (result?.behavior === 'deny' && typeof result.message === 'string' && result.message.trim()) {
3030
+ this._deniedToolMessages.set(toolUseId, result.message.trim())
3031
+ } else {
3032
+ this._deniedToolMessages.delete(toolUseId)
3033
+ }
3034
+ if (result?.behavior === 'allow') {
3035
+ this._stopCancelledToolUseIds.delete(toolUseId)
3036
+ this._stopResolvedToolUseIds.delete(toolUseId)
3037
+ } else if (!this._stopResolvedToolUseIds.has(toolUseId)) {
3038
+ // #8430: settled by something other than the Stop (the user's Deny, a
3039
+ // timeout, a rule): the tool row keeps that decision's own reading.
3040
+ this._stopCancelledToolUseIds.delete(toolUseId)
3041
+ }
3042
+ }
3043
+ return Promise.resolve(decision).then(
3044
+ (result) => { settled(result); return result },
3045
+ (err) => { settled(undefined); throw err },
3046
+ )
3047
+ }
3048
+
3049
+ /**
3050
+ * #8936: the user-facing text for a provider `tool_result` that is a refusal,
3051
+ * or undefined. Consulted by `emitToolResults` for every result block.
3052
+ *
3053
+ * Keyed on this session's own decision: an error block whose tool_use id has a
3054
+ * recorded denial shows that denial's message, whatever wording the CLI chose.
3055
+ * Without a record, only a block that reads as one of the CLI's refusals gets
3056
+ * the generic sentence; any other error (a real tool failure) is untouched. A
3057
+ * non-error block never consumes the record.
3058
+ * @param {string} toolUseId
3059
+ * @param {{is_error?: boolean}} block
3060
+ * @returns {string|undefined}
3061
+ */
3062
+ _deniedTextForToolResult(toolUseId, block) {
3063
+ if (block?.is_error !== true) return undefined
3064
+ const text = toolResultText(block)
3065
+ const message = this._deniedToolMessages.get(toolUseId)
3066
+ if (message !== undefined) {
3067
+ this._deniedToolMessages.delete(toolUseId)
3068
+ if (!isSdkToolRejectionText(text)) {
3069
+ ;(this._log || log).warn(
3070
+ `Denied ${toolUseId} came back with an unrecognised refusal text: ${text.trim().split('\n')[0].slice(0, 120)}`,
3071
+ )
3072
+ }
3073
+ return message
3074
+ }
3075
+ return isSdkToolRejectionText(text) ? SDK_DENIED_FALLBACK_TEXT : undefined
3076
+ }
3077
+
3078
+ /**
3079
+ * #8363: the termination reason for a provider `tool_result`, or undefined.
3080
+ * Consulted by `emitToolResults` for every result block. A result is a Stop's
3081
+ * when the call's permission prompt was still pending at the moment Stop was
3082
+ * pressed and the provider's block is an error (the denial it wrote itself).
3083
+ * Single-use: the id is dropped on the way out.
3084
+ * @param {string} toolUseId
3085
+ * @param {{is_error?: boolean}} block
3086
+ * @returns {string|undefined}
3087
+ */
3088
+ _terminatedReasonForToolResult(toolUseId, block) {
3089
+ this._stopResolvedToolUseIds.delete(toolUseId)
3090
+ if (!this._stopCancelledToolUseIds.delete(toolUseId)) return undefined
3091
+ return block?.is_error === true ? 'user_stop_before_run' : undefined
3092
+ }
3093
+
3094
+ /**
3095
+ * SDK PreToolUse bridge for Auto turns (#7825). The hook contract supplies
3096
+ * the same tool name/input that canUseTool receives, but its response uses
3097
+ * hookSpecificOutput rather than PermissionResult.
3098
+ */
3099
+ async _handleAutoPreToolUse(hookInput, signal, hookToolUseId = undefined) {
3100
+ const toolName = hookInput?.tool_name
3101
+ const input = hookInput?.tool_input
3102
+ if (typeof toolName !== 'string' || !input || typeof input !== 'object' || Array.isArray(input)) {
3103
+ return {
3104
+ continue: true,
3105
+ hookSpecificOutput: {
3106
+ hookEventName: 'PreToolUse',
3107
+ permissionDecision: 'deny',
3108
+ permissionDecisionReason: 'Malformed tool request',
3109
+ },
3110
+ }
3111
+ }
3112
+
3113
+ // #8336: the provider's id for this tool call -- the hook's second argument,
3114
+ // else the same id on the hook payload.
3115
+ const toolUseId = typeof hookToolUseId === 'string' && hookToolUseId.length > 0
3116
+ ? hookToolUseId
3117
+ : hookInput?.tool_use_id
3118
+ // This callback is the only gate on an Auto turn (the SDK itself runs in
3119
+ // bypassPermissions), and a callback that rejects gives the SDK no decision.
3120
+ // So a permission check that throws, or whose promise rejects, becomes a
3121
+ // deny RESULT here, before it is tracked: it then goes through the same
3122
+ // bookkeeping as any other deny (the tool row shows this reason).
3123
+ const check = (async () => this._permissions.handlePermission(toolName, input, signal, this.permissionMode, undefined, toolUseId))()
3124
+ .catch((err) => {
3125
+ ;(this._log || log).warn(`Auto-mode permission check failed for ${toolName}; denying: ${err?.message || err}`)
3126
+ return { behavior: 'deny', message: 'Chroxy could not complete the permission check for this tool call. Failing closed (denied).' }
3127
+ })
3128
+ const result = await this._trackPermissionDecision(toolUseId, check)
3129
+ const allow = result?.behavior === 'allow'
3130
+ return {
3131
+ continue: true,
3132
+ hookSpecificOutput: {
3133
+ hookEventName: 'PreToolUse',
3134
+ permissionDecision: allow ? 'allow' : 'deny',
3135
+ ...(allow && result.updatedInput ? { updatedInput: result.updatedInput } : {}),
3136
+ ...(!allow ? { permissionDecisionReason: result?.message || 'Permission denied' } : {}),
3137
+ },
3138
+ }
1289
3139
  }
1290
3140
 
1291
3141
  /**
1292
3142
  * Resolve a pending permission request (called by WsServer when
1293
3143
  * the app sends permission_response).
1294
3144
  */
1295
- respondToPermission(requestId, decision, editedInput) {
1296
- return this._permissions.respondToPermission(requestId, decision, editedInput)
3145
+ respondToPermission(requestId, decision, editedInput, reason, scope) {
3146
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
1297
3147
  }
1298
3148
 
1299
3149
  /**
@@ -1301,8 +3151,9 @@ export class SdkSession extends BaseSession {
1301
3151
  * In SDK mode, the canUseTool callback is holding a Promise open.
1302
3152
  * This method resolves it with the user's answer as structured updatedInput.
1303
3153
  */
1304
- respondToQuestion(text, answersMap) {
1305
- this._permissions.respondToQuestion(text, answersMap)
3154
+ respondToQuestion(text, answersMap, toolUseId) {
3155
+ // #8460: the id lets the manager refuse an answer meant for a different question.
3156
+ return this._permissions.respondToQuestion(text, answersMap, toolUseId)
1306
3157
  }
1307
3158
 
1308
3159
  /**
@@ -1312,15 +3163,29 @@ export class SdkSession extends BaseSession {
1312
3163
  _onModelChanged() {
1313
3164
  // #4828: session-scoped when init has fired.
1314
3165
  ;(this._log || log).info(`Model changed to ${this.model || 'default'}`)
3166
+ // #8700: the level was chosen against the PREVIOUS model's roster. One the
3167
+ // new model does not offer would reach `--effort` anyway and be silently
3168
+ // downgraded (or, for a budget level, ignored), so it goes back to the
3169
+ // model default, announced rather than kept on a header it no longer
3170
+ // describes. Whatever was reported belonged to the old model too: with no
3171
+ // level of our own, Claude Code applies the effort saved for the NEW model
3172
+ // (`modelSettings.<model>.effortLevel`), so it is unknown until the next
3173
+ // turn reports it.
3174
+ let reason = 'the model changed; the effort is reported when the next turn starts'
3175
+ const dropped = this._thinkingLevel
3176
+ if (dropped && !this._offeredThinkingLevels().includes(dropped)) {
3177
+ this._thinkingLevel = null
3178
+ reason = `the model changed and ${this.model || 'the default model'} does not offer ${dropped}, so the session is back on the model default`
3179
+ }
3180
+ this._forgetEffortReport()
3181
+ this.emit('thinking_level_changed', { reason })
1315
3182
  }
1316
3183
 
1317
3184
  _onPermissionModeChanged(mode) {
1318
3185
  this._permissions.clearRules()
1319
- // #3729: switching TO auto is a "panic button" — drain any pending
1320
- // permission prompts so the user isn't left staring at modals after
1321
- // declaring "approve everything". Without this, prompts that were
1322
- // emitted under the previous mode hang until the user resolves them
1323
- // or they hit the 5-min timeout, contradicting the bypass semantics.
3186
+ // #3729: switching TO auto drains ordinary pending permission prompts so
3187
+ // the user isn't left staring at stale modals. PermissionManager preserves
3188
+ // protected-path prompts because the floor still applies in Auto.
1324
3189
  if (mode === 'auto') {
1325
3190
  this._permissions.autoAllowPending()
1326
3191
  }
@@ -1359,25 +3224,223 @@ export class SdkSession extends BaseSession {
1359
3224
  }
1360
3225
 
1361
3226
  /**
1362
- * Set thinking level by adjusting max thinking tokens.
1363
- * @param {string} level - 'default' | 'high' | 'max'
3227
+ * #6771 — durable (project-scoped) permission rules currently applied to this
3228
+ * session, tagged `persist:'project'`. Delegates to PermissionManager.
3229
+ * @returns {Array<{tool: string, decision: string, persist: 'project'}>}
3230
+ */
3231
+ getPersistentPermissionRules() {
3232
+ if (typeof this._permissions.getPersistentRules === 'function') {
3233
+ return this._permissions.getPersistentRules()
3234
+ }
3235
+ return []
3236
+ }
3237
+
3238
+ /**
3239
+ * #6771 — re-seed this session's in-memory durable rule set (does NOT persist;
3240
+ * the caller owns the store write). Delegates to PermissionManager.
3241
+ * @param {Array<{tool: string, decision: string}>} rules
3242
+ */
3243
+ setPersistentPermissionRules(rules) {
3244
+ if (typeof this._permissions.setPersistentRules === 'function') {
3245
+ this._permissions.setPersistentRules(rules)
3246
+ }
3247
+ }
3248
+
3249
+ /**
3250
+ * Set the session's thinking level: Claude Code's effort for a model that
3251
+ * has one, the legacy `maxThinkingTokens` budget for one that predates it
3252
+ * (#8700, `_thinkingOptions`). Never rejects: the per-model membership
3253
+ * decision belongs to the `set_thinking_level` handler, which knows the
3254
+ * session's model (#7730).
3255
+ *
3256
+ * Between turns the level simply rides on the next turn's `query()`
3257
+ * options, and the last report is dropped: it described a turn that ran at
3258
+ * the old level. Mid-turn the running process is asked to switch (the flag
3259
+ * settings layer for an effort, `setMaxThinkingTokens` for a budget) and then
3260
+ * asked what it now applies, so the reported level is the CLI's answer, not
3261
+ * this method's hope — `max` cannot be set that way (Claude Code's settings
3262
+ * do not take it) and reaches the CLI at the next turn.
3263
+ * @param {string} level
1364
3264
  */
1365
3265
  async setThinkingLevel(level) {
3266
+ this._thinkingLevel = level === LEGACY_DEFAULT_THINKING_LEVEL ? null : level
3267
+ // Invalidate pending reads and the previous answer before any live setter
3268
+ // can yield. Even Auto, Max and budget-only changes leave that answer behind.
3269
+ this._forgetEffortReport()
3270
+ // Note: thinking_level_changed is broadcast by the WS handler, not emitted here
3271
+ const query = this._query
3272
+ const turnSeq = this._turnSeq
3273
+ const epoch = this._effortEpoch
3274
+ if (!query) return
3275
+
3276
+ // The same choice `_thinkingOptions` makes for the next turn, made live:
3277
+ // the effort is set when the next turn would send one, and cleared at
3278
+ // Auto; the budget is set when the next turn would send one, and cleared
3279
+ // at Auto or where the model reads no effort (a level with no budget then
3280
+ // means none). An unknown model gets both, as its next turn will. Each
3281
+ // setter fails on its own, so one the CLI refuses cannot keep the other
3282
+ // from landing, and the report is asked for last.
3283
+ const opts = this._thinkingOptions()
3284
+ const setsEffort = opts.effort !== undefined || !this._thinkingLevel
3285
+ const setsBudget = opts.effort === undefined || opts.maxThinkingTokens !== undefined
3286
+ const asksEffort = setsEffort && this._thinkingLevel !== 'max' && typeof query.applyFlagSettings === 'function'
3287
+ if (asksEffort) {
3288
+ try {
3289
+ await query.applyFlagSettings({ effortLevel: this._thinkingLevel })
3290
+ } catch (err) {
3291
+ ;(this._log || log).warn(`Failed to apply effort ${level ?? 'default (cleared)'} to the running turn: ${err?.message || err}`)
3292
+ }
3293
+ }
3294
+ if (setsBudget && typeof query.setMaxThinkingTokens === 'function') {
3295
+ try {
3296
+ await query.setMaxThinkingTokens(opts.maxThinkingTokens ?? null)
3297
+ } catch (err) {
3298
+ ;(this._log || log).warn(`Failed to apply the thinking budget for ${level ?? 'default (cleared)'} to the running turn: ${err?.message || err}`)
3299
+ }
3300
+ }
3301
+ // Capture ownership before the setters await: an older continuation must
3302
+ // not start a read under a newer setting, model, turn or query's identity.
3303
+ if (asksEffort && this._query === query && this._turnSeq === turnSeq && this._effortEpoch === epoch) {
3304
+ try {
3305
+ await this._readEffectiveEffort('after a mid-turn change')
3306
+ } catch (err) {
3307
+ ;(this._log || log).warn(`Effort report failed: ${err?.message || err}`)
3308
+ }
3309
+ }
3310
+ }
3311
+
3312
+ /**
3313
+ * #8700 — the levels the session's current model offers, by the SAME
3314
+ * resolution the `set_thinking_level` gate and the dashboard picker use (the
3315
+ * model's roster row, else the legacy triple: SdkSession is Claude-family),
3316
+ * so a model switch keeps exactly the levels the gate would accept.
3317
+ * @returns {string[]}
3318
+ */
3319
+ _offeredThinkingLevels() {
3320
+ const modelId = this.model || this.bootedModel
3321
+ let row = null
3322
+ try {
3323
+ row = modelId ? getRosterModelRow(this._provider, modelId) : null
3324
+ } catch (err) {
3325
+ ;(this._log || log).warn(`Thinking-level roster lookup failed for model '${modelId}': ${err?.message || err}`)
3326
+ }
3327
+ return resolveThinkingLevels(row, { legacyFallback: true }).levels
3328
+ }
3329
+
3330
+ /**
3331
+ * #8700 — does `modelId` take Claude Code's effort, a token budget, or is
3332
+ * that not known yet? The SDK's own `supportedModels()` answer for this
3333
+ * session comes first; failing that, a roster row that advertises levels
3334
+ * (stamped from that same answer by any session, and kept across restarts
3335
+ * in the models cache) means effort.
3336
+ * @returns {'effort'|'budget'|'unknown'}
3337
+ */
3338
+ _effortSupportFor(modelId) {
3339
+ const heard = this._modelEffortSupport.get(modelId || SDK_DEFAULT_MODEL_ALIAS)
3340
+ if (heard) return heard
3341
+ let row = null
3342
+ try {
3343
+ row = modelId ? getRosterModelRow(this._provider, modelId) : null
3344
+ } catch {
3345
+ row = null
3346
+ }
3347
+ return Array.isArray(row?.reasoningLevels) && row.reasoningLevels.length > 0 ? 'effort' : 'unknown'
3348
+ }
3349
+
3350
+ /**
3351
+ * #8700 — the per-turn `query()` options for the session's level.
3352
+ *
3353
+ * An adaptive model (every current one) ignores `maxThinkingTokens`, which
3354
+ * is all a level used to set, so High and Max did nothing and a session ran
3355
+ * at Claude Code's default effort whatever the header said. A level now goes
3356
+ * to such a model as `effort` (the CLI's `--effort`). A model that predates
3357
+ * effort still reads the budget, and gets it alone. When neither is known
3358
+ * yet (no model list heard and no roster row that says), the level is sent
3359
+ * as an effort — the CLI drops `--effort` on a model without it — and a
3360
+ * legacy level's budget rides along exactly as it did before #8700, for the
3361
+ * pre-adaptive model that reads only that. No level (`default`) sends
3362
+ * neither, so Claude Code applies the user's own setting for the model.
3363
+ * @returns {{effort?: string, maxThinkingTokens?: number}}
3364
+ */
3365
+ _thinkingOptions() {
3366
+ const level = this._thinkingLevel
3367
+ if (!level) return {}
1366
3368
  const budget = SdkSession.THINKING_BUDGETS[level] ?? null
1367
- this._thinkingLevel = level === 'default' ? null : level
3369
+ const support = this._effortSupportFor(this.model || this.bootedModel)
3370
+ if (support === 'budget') return budget != null ? { maxThinkingTokens: budget } : {}
3371
+ if (support === 'effort' || budget == null) return { effort: level }
3372
+ return { effort: level, maxThinkingTokens: budget }
3373
+ }
1368
3374
 
1369
- if (this._query && typeof this._query.setMaxThinkingTokens === 'function') {
3375
+ /** #8700: drop the last effort report — it described a model or level the session has left. */
3376
+ _forgetEffortReport() {
3377
+ this._effortEpoch += 1
3378
+ this._effectiveEffort = null
3379
+ this._effectiveModel = null
3380
+ this._lastEffortReport = null
3381
+ }
3382
+
3383
+ /**
3384
+ * #8700 — ask the running turn's Claude Code what it applies
3385
+ * (`get_settings` → `applied: { model, effort }`) and announce it when it
3386
+ * changed. `query.getSettings()` is in the Agent SDK's runtime, not its
3387
+ * typings; a CLI or SDK without it, or a failed request, leaves the level
3388
+ * unknown and says so once. `applied.effort: null` (a model without effort,
3389
+ * or an environment override that turns it off) is shown as unknown and is
3390
+ * NOT read as "this model takes a budget": which parameter a model reads is
3391
+ * the `supportedModels()` answer's call alone (`_effortSupportFor`).
3392
+ * @param {string} [when] - for the log line
3393
+ */
3394
+ async _readEffectiveEffort(when = 'when the turn started') {
3395
+ const readSeq = ++this._effortReadSeq
3396
+ const query = this._query
3397
+ const turnSeq = this._turnSeq
3398
+ const epoch = this._effortEpoch
3399
+ let applied = null
3400
+ let reason
3401
+ if (!query || typeof query.getSettings !== 'function') {
3402
+ reason = 'this Claude Code cannot report the effort it applies'
3403
+ } else {
1370
3404
  try {
1371
- await this._query.setMaxThinkingTokens(budget)
1372
- // #4828: session-scoped (setThinkingLevel only takes effect with
1373
- // an active query — strictly post-init).
1374
- ;(this._log || log).info(`Thinking level set to ${level} (${budget ?? 'adaptive'} tokens)`)
3405
+ applied = (await query.getSettings())?.applied ?? null
3406
+ reason = applied ? `reported by Claude Code ${when}` : 'Claude Code did not report the effort it applies'
1375
3407
  } catch (err) {
1376
- ;(this._log || log).warn(`Failed to set thinking level: ${err.message}`)
3408
+ reason = `Claude Code could not report the effort it applies (${err?.message || err})`
1377
3409
  }
1378
3410
  }
3411
+ // A report that lands after the session went away, after a newer turn
3412
+ // started (which makes its own), or after a model or level change
3413
+ // (`_forgetEffortReport`) is not this session's current answer. Within one
3414
+ // epoch only the latest read owns the answer, even when an init read races
3415
+ // the live setter's read. A latest read that lands after its own turn ended,
3416
+ // with nothing changed since, still is current.
3417
+ if (this._destroying || this._turnSeq !== turnSeq || this._effortEpoch !== epoch || this._effortReadSeq !== readSeq) return
3418
+ const effort = isWellFormedThinkingLevel(applied?.effort) ? applied.effort : null
3419
+ const model = typeof applied?.model === 'string' && applied.model.length > 0 ? applied.model : null
3420
+ if (applied && applied.effort === null) {
3421
+ reason = `Claude Code reports no effort level for ${model || 'this model'}`
3422
+ }
3423
+ this._effectiveEffort = effort
3424
+ this._effectiveModel = model
3425
+ const report = `${model}|${effort}|${applied ? 'reported' : reason}`
3426
+ if (report === this._lastEffortReport) return
3427
+ this._lastEffortReport = report
3428
+ this.emit('thinking_level_changed', { reason })
3429
+ }
1379
3430
 
1380
- // Note: thinking_level_changed is broadcast by the WS handler, not emitted here
3431
+ /**
3432
+ * #8700 — the SDK's per-model effort answer (`supportsEffort` +
3433
+ * `supportedEffortLevels`, which the CLI already narrows per model) as the
3434
+ * registry's `reasoningLevels` roster, the same translation
3435
+ * codex-model-catalog.js does for `supportedReasoningEfforts`. The model
3436
+ * default leads the list so the picker's first option is "Auto" — no effort
3437
+ * of our own, the user's saved one applies. null for a model without effort,
3438
+ * which keeps the legacy roster.
3439
+ * @param {object} modelInfo - one `supportedModels()` row
3440
+ * @returns {{reasoningLevels: string[], defaultReasoningLevel: string} | null}
3441
+ */
3442
+ static effortRoster(modelInfo) {
3443
+ return effortRoster(modelInfo)
1381
3444
  }
1382
3445
 
1383
3446
  /**
@@ -1400,7 +3463,11 @@ export class SdkSession extends BaseSession {
1400
3463
 
1401
3464
  try {
1402
3465
  const sdkModels = await this._query.supportedModels()
1403
- const converted = updateModels(sdkModels)
3466
+ // #8700: each row's effort roster rides into the registry as its
3467
+ // `reasoningLevels`; this session also remembers the per-model answer
3468
+ // for `_thinkingOptions` (see annotateSupportedModels).
3469
+ const withEffort = annotateSupportedModels(sdkModels, this._modelEffortSupport)
3470
+ const converted = updateModels(withEffort)
1404
3471
  if (converted && converted.length > 0) {
1405
3472
  // #4828: session-scoped (called from init handler so _log is set).
1406
3473
  ;(this._log || log).info(`Dynamic model list: ${converted.map(m => m.id).join(', ')}`)
@@ -1408,7 +3475,7 @@ export class SdkSession extends BaseSession {
1408
3475
  this.emit('models_updated', { models: converted })
1409
3476
  }
1410
3477
  } catch (err) {
1411
- ;(this._log || log).warn(`Failed to fetch supported models: ${err.message}`)
3478
+ ;(this._log || log).warn(`Failed to fetch supported models: ${err?.message || err}`)
1412
3479
  }
1413
3480
  }
1414
3481
 
@@ -1440,10 +3507,10 @@ export class SdkSession extends BaseSession {
1440
3507
  _finalizeAgentByToolUseId(toolUseId) {
1441
3508
  if (typeof toolUseId !== 'string' || !toolUseId) return
1442
3509
  this._taskIdByToolUseId.delete(toolUseId)
1443
- if (this._activeAgents.has(toolUseId)) {
1444
- this._activeAgents.delete(toolUseId)
1445
- this.emit('agent_completed', { toolUseId })
1446
- }
3510
+ // #7340: the agent half is BaseSession's `_completeAgent` (idempotent, and
3511
+ // the single implementation shared with CliSession and ByokSession). This
3512
+ // wrapper adds only the SDK-specific task-id mapping cleanup above.
3513
+ this._completeAgent(toolUseId)
1447
3514
  }
1448
3515
 
1449
3516
  /**
@@ -1508,13 +3575,40 @@ export class SdkSession extends BaseSession {
1508
3575
  // already settling) so an interrupt never strands a queued message.
1509
3576
  this.clearOutgoingQueue()
1510
3577
 
1511
- if (!this._query) return
3578
+ if (!this._query) {
3579
+ // #8430: a Stop with nothing to interrupt -- no query yet -- and no prompt
3580
+ // open has nothing to label; do not leave it armed for the rest of the turn.
3581
+ if (!this._permissions.hasPendingPrompt()) this._permissions.clearUserStopInFlight()
3582
+ return
3583
+ }
1512
3584
 
1513
3585
  // #4881: mark the imminent query teardown as user-initiated so the
1514
3586
  // _callQuery catch block suppresses the AbortError-flavored "Query error"
1515
3587
  // emit and instead surfaces a quiet `stopped` event. Cleared in the
1516
3588
  // catch/finally (single-use, mirrors CliSession#4602).
1517
3589
  this.markIntentionalStop()
3590
+ this._noteTurnStopRequested() // #7376
3591
+ // #8363: every permission prompt still waiting is about to be resolved by the
3592
+ // abort, not by the user. Snapshot them BEFORE the abort -- the SDK writes the
3593
+ // tool_result for each as soon as it sees the interrupt, which can be before
3594
+ // this session's abort listeners have run.
3595
+ //
3596
+ // #8430: only for a USER Stop. Any other interrupt (an orchestration deadline,
3597
+ // the scheduler) is not one, and its prompts' rows must not read as the user's
3598
+ // doing. The mark is provisional: the prompt's own resolution confirms it (a
3599
+ // Stop-caused one) or removes it (a Deny or timeout that won first), see
3600
+ // `_trackPermissionDecision`.
3601
+ //
3602
+ // Only a prompt that is STILL waiting. A decision delivered in this same
3603
+ // synchronous tick (the scheduler denies, then interrupts, back to back) has
3604
+ // already left the permission manager's pending state, though its id leaves
3605
+ // `_pendingPermissionToolUseIds` a microtask later; that call was refused,
3606
+ // not stopped.
3607
+ if (this._permissions.isUserStopInFlight()) {
3608
+ for (const id of this._pendingPermissionToolUseIds) {
3609
+ if (this._permissions.hasPendingForToolUse(id)) this._stopCancelledToolUseIds.add(id)
3610
+ }
3611
+ }
1518
3612
 
1519
3613
  // #4828: session-scoped (interrupt() only meaningful with an active query).
1520
3614
  ;(this._log || log).info('Interrupting query')
@@ -1583,8 +3677,11 @@ export class SdkSession extends BaseSession {
1583
3677
  // into a cleared message. Best-effort — the SDK's generator may not
1584
3678
  // support .return()/.throw() uniformly.
1585
3679
  this._abortActiveQuery()
1586
- this._clearMessageState()
1587
- this.emit('error', { message: `Response timed out after ${friendly} of inactivity` })
3680
+ this._abandonDrain() // #8321
3681
+ // #7376: name the cause so a tool left in flight reads as "the turn was
3682
+ // terminated under it", not as a failed command.
3683
+ this._clearMessageState({ terminatedReason: 'hard_timeout' })
3684
+ this.emit('error', { message: `Response timed out after ${friendly} of inactivity`, declarationTurnId: messageId })
1588
3685
  }
1589
3686
 
1590
3687
  /**
@@ -1617,10 +3714,11 @@ export class SdkSession extends BaseSession {
1617
3714
  // Attempt to abort the SDK query generator so no further events land
1618
3715
  // into a cleared message context. Best-effort — matches _handleHardTimeout.
1619
3716
  this._abortActiveQuery()
3717
+ this._abandonDrain() // #8321
1620
3718
  // #4616: snapshot sessionId BEFORE _clearMessageState wipes it so the
1621
3719
  // synthetic `result` event below carries the correct identifier.
1622
3720
  const sessionId = this._sdkSessionId || this._sessionId
1623
- this._clearMessageState()
3721
+ this._clearMessageState({ terminatedReason: 'stream_stall' }) // #7376
1624
3722
  // #4616: emit a synthetic `result` so event-normalizer fans it to
1625
3723
  // `agent_idle`. Per #4308 handleAgentIdle clears `activeTools: []`
1626
3724
  // as a safety net, which is what stops the dashboard's footer pill
@@ -1628,13 +3726,79 @@ export class SdkSession extends BaseSession {
1628
3726
  // _emitInterruptedTurnResult (stream_end + result); the SDK was
1629
3727
  // previously missing the `result` half of the pair. cost:null skips
1630
3728
  // session-manager billing accumulation (mirrors CLI).
1631
- this.emit('result', { cost: null, duration: this._streamStallTimeoutMs, usage: null, sessionId })
3729
+ const message = `Stream stalled — no response for ${friendly}. Try sending again.`
3730
+ // #7072: `interrupted` + `failureMessage` are internal (event-normalizer
3731
+ // whitelists the wire fields). An orchestration TurnDriver settles on the FIRST
3732
+ // terminal event, this result, and drops the `error` below at its epoch guard;
3733
+ // without the mark a stalled turn reads as a completed one and the caller never
3734
+ // sees TURN_ERROR. The result itself stays: it is what clears activeTools.
3735
+ this.emit('result', { cost: null, duration: this._streamStallTimeoutMs, usage: null, sessionId, interrupted: true, failureMessage: message, declarationTurnId: messageId })
1632
3736
  this.emit('error', {
1633
3737
  code: 'stream_stall',
1634
- message: `Stream stalled — no response for ${friendly}. Try sending again.`,
3738
+ message,
3739
+ declarationTurnId: messageId,
1635
3740
  })
1636
3741
  }
1637
3742
 
3743
+ /**
3744
+ * #8321: stop timing a drain and forget it. Idempotent, and a no-op for a
3745
+ * drain that is no longer the session's current one.
3746
+ */
3747
+ _endDrain(drain) {
3748
+ if (drain.waitTimer) clearTimeout(drain.waitTimer)
3749
+ if (drain.forceTimer) clearTimeout(drain.forceTimer)
3750
+ drain.waitTimer = null
3751
+ drain.forceTimer = null
3752
+ if (this._drainingTurn === drain) this._drainingTurn = null
3753
+ }
3754
+
3755
+ /**
3756
+ * #8321: a hard timeout or stream stall gives up on the query: it was told to
3757
+ * abort and is not answering, and the point of the recovery is that the next
3758
+ * send runs now. Waiting behind such a query would only add the drain bound to
3759
+ * every retry, so the hold is dropped; the abandoned loop is superseded by the
3760
+ * next turn and touches nothing of its.
3761
+ */
3762
+ _abandonDrain() {
3763
+ if (this._drainingTurn) this._endDrain(this._drainingTurn)
3764
+ }
3765
+
3766
+ /**
3767
+ * #8321: a drain has an end. Once a follow-up is waiting AND busy has cleared
3768
+ * (whichever happens last starts the clock; nothing waiting, nothing armed), the generator gets
3769
+ * `DRAIN_WAIT_MS` to finish; then its query is closed; and if even that does
3770
+ * not end it within `DRAIN_FORCE_GRACE_MS`, the hold is released anyway and
3771
+ * the next queued follow-up runs (the late loop is superseded by it, and its
3772
+ * own `finally` then touches nothing of the successor's). Without the bound
3773
+ * a generator that never ended would block the session forever.
3774
+ */
3775
+ _armDrainRelease() {
3776
+ const drain = this._drainingTurn
3777
+ if (!drain || drain.waitTimer || drain.forceTimer) return
3778
+ drain.waitTimer = setTimeout(() => {
3779
+ drain.waitTimer = null
3780
+ if (this._drainingTurn !== drain || this._destroying) return
3781
+ // The follow-up it was held for may be gone (interrupt); a lingering
3782
+ // query with nothing waiting behind it is left as it always was.
3783
+ if (this._outgoingQueue.length === 0) return
3784
+ ;(this._log || log).warn(`Previous query still draining after ${SdkSession.DRAIN_WAIT_MS}ms; closing it`)
3785
+ try {
3786
+ if (typeof drain.close === 'function') drain.close()
3787
+ else if (typeof drain.query?.close === 'function') drain.query.close()
3788
+ } catch (err) {
3789
+ ;(this._log || log).warn(`Failed to close draining query: ${err?.message || err}`)
3790
+ }
3791
+ drain.forceTimer = setTimeout(() => {
3792
+ drain.forceTimer = null
3793
+ if (this._drainingTurn !== drain || this._destroying) return
3794
+ ;(this._log || log).warn('Draining query did not end after close; releasing queued follow-ups anyway')
3795
+ this._endDrain(drain)
3796
+ if (this._query === drain.query) this._query = null
3797
+ if (this._outgoingQueue.length && !this._isBusy) this.dequeueNextOutgoing()
3798
+ }, SdkSession.DRAIN_FORCE_GRACE_MS)
3799
+ }, SdkSession.DRAIN_WAIT_MS)
3800
+ }
3801
+
1638
3802
  /**
1639
3803
  * Best-effort abort of the active SDK query generator. Used when the
1640
3804
  * session times out mid-turn so tool results don't stream into a
@@ -1705,14 +3869,35 @@ export class SdkSession extends BaseSession {
1705
3869
  /**
1706
3870
  * Clear per-message state, marking us as ready for the next message.
1707
3871
  */
1708
- _clearMessageState() {
1709
- super._clearMessageState()
1710
- this._permissions.clearAll()
3872
+ // #7340: forward the opts to super. `turnEndedCleanly` decides whether a
3873
+ // confirmed-backgrounded subagent survives BaseSession's turn-end sweep;
3874
+ // an override that drops it silently disables the exemption.
3875
+ _clearMessageState(opts) {
3876
+ // #8430: read the user Stop BEFORE the base teardown clears it. A live Stop
3877
+ // ends the turn on the generator's AbortError, so the prompts still open are
3878
+ // resolved by `clearAll()` below, not by the abort listener.
3879
+ // The teardown of a failed query passes the cause it established earlier.
3880
+ const userStop = opts?.userStop ?? this._permissions.isUserStopInFlight()
3881
+ super._clearMessageState(opts)
3882
+ this._permissions.clearAll({ userStop })
3883
+ this._deniedToolMessages.clear() // #8936
3884
+ // #8321: busy ends here, possibly with the turn's generator still alive.
3885
+ // Bound how long a follow-up can be held behind it.
3886
+ if (this._drainingTurn && !this._destroying && this._outgoingQueue.length) this._armDrainRelease()
1711
3887
  // Pause counter is tied to the previous message — reset so the next
1712
3888
  // message starts with a fresh counter.
1713
3889
  this._permissionPauseCount = 0
1714
3890
  this._resultTimeoutPaused = false
1715
3891
  this._resetResultTimeout = null
3892
+ // #8153: mirrors CliSession's stale-flag reset. If plan mode is active
3893
+ // but ExitPlanMode never arrived (interrupt/crash), the flag is stale —
3894
+ // reset it. In normal flow, _planAllowedPrompts is non-null (set by
3895
+ // ExitPlanMode) and plan_ready has already been emitted + both flags
3896
+ // reset before we reach here (see the 'result' case in _callQuery).
3897
+ if (this._inPlanMode && this._planAllowedPrompts === null) {
3898
+ this._inPlanMode = false
3899
+ }
3900
+ this._planAllowedPrompts = null
1716
3901
  }
1717
3902
 
1718
3903
  /**
@@ -1720,6 +3905,8 @@ export class SdkSession extends BaseSession {
1720
3905
  */
1721
3906
  destroy() {
1722
3907
  this._destroying = true
3908
+ this._deniedToolMessages.clear() // #8936
3909
+ if (this._drainingTurn) this._endDrain(this._drainingTurn)
1723
3910
  // #5936: tear down the shared outgoing queue silently — no message_dequeued
1724
3911
  // (which signals "sent") for a session that's going away.
1725
3912
  this.clearOutgoingQueue({ emit: false })
@@ -1744,13 +3931,32 @@ export class SdkSession extends BaseSession {
1744
3931
  this._streamStallTimeout = null
1745
3932
  }
1746
3933
 
1747
- // Interrupt active query
3934
+ // #8300: release the turn's streaming input first, so the CLI's stdin
3935
+ // closes even if the message loop never gets to observe `_destroying`
3936
+ // (it is parked on the generator's next message).
3937
+ if (this._turnInput) {
3938
+ this._turnInput.end()
3939
+ this._turnInput = null
3940
+ }
3941
+
3942
+ // Interrupt active query, then close it: with the input released an idle
3943
+ // CLI exits on its own, but one kept alive by background work would not,
3944
+ // and the parked message loop would never end (#8300).
1748
3945
  if (this._query) {
1749
- this._query.interrupt().catch((err) => {
3946
+ const q = this._query
3947
+ this._query = null
3948
+ q.interrupt().catch((err) => {
3949
+ // The close below rejects the pending interrupt ("Query closed
3950
+ // before response received"); that is the expected outcome here.
3951
+ const expected = /closed before/i.test(err?.message || '')
1750
3952
  // #4828: session-scoped when init has fired.
1751
- ;(this._log || log).warn(`Failed to interrupt active query: ${err.message} (non-critical, session destroying)`)
3953
+ ;(this._log || log)[expected ? 'debug' : 'warn'](`Failed to interrupt active query: ${err.message} (non-critical, session destroying)`)
1752
3954
  })
1753
- this._query = null
3955
+ try {
3956
+ if (typeof q.close === 'function') q.close()
3957
+ } catch (err) {
3958
+ ;(this._log || log).warn(`Failed to close query on destroy: ${err?.message || err}`)
3959
+ }
1754
3960
  }
1755
3961
 
1756
3962
  // Emit completions for any tracked agents and clear busy state