@chroxy/server 0.11.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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +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 +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  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 +69 -5
  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 +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,10 +1,16 @@
1
+ import { assistantResponseText, sdkDeclarationEligible } from './assistant-response.js'
1
2
  import { query, forkSession } from '@anthropic-ai/claude-agent-sdk'
2
- import { join } from 'path'
3
- import { homedir } from 'os'
3
+ import { claudeConfigDir } from './utils/claude-config-dir.js'
4
4
  import { performance } from 'node:perf_hooks'
5
- import { updateModels, saveModelsCache, updateContextWindow, getModels, ALLOWED_MODEL_IDS } from './models.js'
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'
6
12
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
7
- import { BaseSession, buildBaseSessionOpts } from './base-session.js'
13
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission } from './base-session.js'
8
14
  import { normalizeSdkModelUsage } from './usage-normalize.js'
9
15
  import { buildContentBlocks } from './content-blocks.js'
10
16
  import { MessageTransformPipeline } from './message-transform.js'
@@ -15,16 +21,50 @@ import {
15
21
  isRunInBackgroundInput,
16
22
  parseBashOutputShellId,
17
23
  } from './background-shells.js'
18
- import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent } from './claude-stream-parser.js'
24
+ import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent, formatStatusContent } from './claude-stream-parser.js'
19
25
  import { createLogger, loggerForSession } from './logger.js'
20
26
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
21
27
  import { formatBytes } from './utils/format-bytes.js'
22
28
  import { formatIdleDuration } from './session-timeout-manager.js'
23
29
  import { detectThinkingKeyword } from './detect-thinking-keyword.js'
24
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'
25
35
 
26
36
  const log = createLogger('sdk')
27
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
+
28
68
  /**
29
69
  * Manages a Claude Code session using the Agent SDK.
30
70
  *
@@ -90,18 +130,159 @@ export const STDIN_DROPPED_ESCALATION_EVERY_N = 10
90
130
  // stuck") with noise control.
91
131
  export const REFUSED_SENDMESSAGE_WARN_INTERVAL_MS = 30 * 1000
92
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
+
93
255
  export class SdkSession extends BaseSession {
256
+ static canonicalAssistantResponses = true
257
+ static declarationTurnOwnership = true
258
+
94
259
  // #5858: marks this as a Claude-family provider — the single source of truth
95
260
  // for `isClaudeProvider()` (drives the createSession soft-fallback for stale
96
261
  // model ids + the shared models registry). Docker subclasses inherit it.
97
262
  static claudeFamily = true
98
263
 
264
+ static get customizationDescriptor() {
265
+ return CLAUDE_SDK_CUSTOMIZATION
266
+ }
267
+
99
268
  // #6769: cap on how long the end-of-turn getContextUsage() control request
100
269
  // may delay the `result` broadcast. The CLI answers in milliseconds when
101
270
  // alive; the cap only bites when the process is already shutting down —
102
271
  // in which case the snapshot is skipped and the result emits without it.
103
272
  static CONTEXT_USAGE_SNAPSHOT_TIMEOUT_MS = 2000
104
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
+
105
286
  /**
106
287
  * Human-readable label shown in the startup banner and anywhere else the
107
288
  * server needs to name this provider (#2953). Each provider owns its own
@@ -119,13 +300,18 @@ export class SdkSession extends BaseSession {
119
300
  * hardcoding the path.
120
301
  */
121
302
  static get dataDir() {
122
- return join(homedir(), '.claude')
303
+ return claudeConfigDir()
123
304
  }
124
305
 
125
306
  static get capabilities() {
126
307
  return {
127
308
  permissions: true,
128
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,
129
315
  modelSwitch: true,
130
316
  permissionModeSwitch: true,
131
317
  // #5609: SDK applies a mid-turn switch to 'auto' in-process (clears
@@ -133,10 +319,35 @@ export class SdkSession extends BaseSession {
133
319
  // killing the turn. Declared false so the capability matrix is uniform —
134
320
  // CliSession is the only provider where the auto-switch is destructive.
135
321
  interruptsTurnOnAutoSwitch: false,
136
- 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,
137
333
  resume: true,
138
334
  terminal: false,
139
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,
140
351
  // #3932: explicit `streaming` so the capability matrix is uniform across
141
352
  // providers — claude-tui sets this to false (deliver-on-complete), all
142
353
  // others stream incremental deltas via stream_delta during a turn.
@@ -162,6 +373,13 @@ export class SdkSession extends BaseSession {
162
373
  // DockerSdkSession overrides this to false — see the instance-level
163
374
  // `supportsConversationFork` getter (transcript lives in-container).
164
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,
165
383
  }
166
384
  }
167
385
 
@@ -177,10 +395,35 @@ export class SdkSession extends BaseSession {
177
395
  * are session-lifetime so a fresh emit on the next drop re-publishes
178
396
  * the running total.
179
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
+ *
180
411
  * @returns {string[]}
181
412
  */
182
413
  static get customEvents() {
183
- 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
184
427
  }
185
428
 
186
429
  /**
@@ -193,11 +436,47 @@ export class SdkSession extends BaseSession {
193
436
  return true
194
437
  }
195
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
+
196
452
  /**
197
453
  * Preflight dependency spec used by `chroxy doctor`.
198
- * SDK mode spawns the `claude` binary under the hood, so the same
199
- * binary check applies. Credentials can come from ANTHROPIC_API_KEY,
200
- * CLAUDE_CODE_OAUTH_TOKEN, or a prior `claude login` subscription.
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.
201
480
  */
202
481
  static get preflight() {
203
482
  return {
@@ -205,15 +484,22 @@ export class SdkSession extends BaseSession {
205
484
  binary: {
206
485
  name: 'claude',
207
486
  args: ['--version'],
208
- candidates: [
209
- '/opt/homebrew/bin/claude',
210
- '/usr/local/bin/claude',
211
- ],
212
- installHint: 'install Claude Code CLI (required by the Agent SDK)',
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`',
213
499
  },
214
500
  credentials: {
215
501
  envVars: ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'],
216
- hint: 'run `claude login` or set ANTHROPIC_API_KEY',
502
+ hint: `run \`${CLAUDE_LOGIN_COMMAND}\` or set ANTHROPIC_API_KEY`,
217
503
  optional: true,
218
504
  },
219
505
  }
@@ -235,6 +521,11 @@ export class SdkSession extends BaseSession {
235
521
  const credSpec = this.preflight.credentials
236
522
  const envVars = credSpec.envVars
237
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`
238
529
  // Era read at call time so a long-running daemon flips OAuth/credit-pool
239
530
  // copy at the 2026-06-15 boundary without a restart (#5629).
240
531
  const era = isProgrammaticCreditEra()
@@ -292,8 +583,8 @@ export class SdkSession extends BaseSession {
292
583
  source: 'none',
293
584
  envVar: null,
294
585
  envVars,
295
- hint: hint || 'run `claude login` or set ANTHROPIC_API_KEY',
296
- detail: `Not configured — ${hint || 'run \`claude login\` or set ANTHROPIC_API_KEY'}`,
586
+ hint: hint || fallbackHint,
587
+ detail: `Not configured — ${hint || fallbackHint}`,
297
588
  // Unconfigured: default to the era-gated credit-pool class (this is the
298
589
  // claude-sdk default auth path once configured via `claude login`).
299
590
  billingClass: era ? BILLING_CLASSES.PROGRAMMATIC_CREDIT : BILLING_CLASSES.SUBSCRIPTION,
@@ -327,7 +618,12 @@ export class SdkSession extends BaseSession {
327
618
  return claudeModelMetadata(modelId)
328
619
  }
329
620
 
330
- /** 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
+ */
331
627
  static THINKING_BUDGETS = { default: null, high: 32000, max: 128000 }
332
628
 
333
629
  /** Error patterns mapped to user-friendly messages. */
@@ -336,8 +632,20 @@ export class SdkSession extends BaseSession {
336
632
  msg: 'Insufficient API credits or billing limit reached. Check your API provider dashboard.' },
337
633
  { test: /rate.limit|too many requests|429/i,
338
634
  msg: 'API rate limit exceeded. Please wait a moment and try again.' },
339
- { test: /authentication|invalid.api.key|401|unauthorized/i,
340
- msg: 'API authentication failed. Check your API key configuration.' },
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 },
341
649
  { test: /overloaded|503|529|temporarily unavailable/i,
342
650
  msg: 'The API is temporarily overloaded. Please try again in a few minutes.' },
343
651
  { test: /SIGABRT|SIGKILL|SIGSEGV|terminated by signal/i,
@@ -345,25 +653,104 @@ export class SdkSession extends BaseSession {
345
653
  ]
346
654
 
347
655
  static _enrichErrorMessage(raw) {
348
- if (!raw) return 'Unknown error'
349
- for (const { test, msg } of SdkSession._ERROR_PATTERNS) {
350
- if (test.test(raw)) return msg
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 } : {}),
351
708
  }
352
- return raw
353
709
  }
354
710
 
355
711
  get thinkingLevel() { return this._thinkingLevel }
356
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
+
357
733
  constructor(opts = {}) {
358
734
  super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-sdk' }))
359
735
  // SdkSession-local opts (not BaseSession opts — see buildBaseSessionOpts).
360
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.
361
743
  this._maxToolInput = maxToolInput || DEFAULT_MAX_TOOL_INPUT_LENGTH
362
744
  this._transformPipeline = new MessageTransformPipeline(transforms || [])
363
745
  this._sandbox = sandbox || null
364
746
 
365
747
  this._sdkSessionId = resumeSessionId || null
366
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
367
754
  // #4828: session-scoped logger, lazily bound on the SDK's first `init`
368
755
  // message (where session_id becomes known). Pre-init log lines stay on
369
756
  // the module-level `log` — same fallback pattern as ClaudeTuiSession.
@@ -372,7 +759,30 @@ export class SdkSession extends BaseSession {
372
759
  // lifetime; the binding stays valid until destroy() drops the instance.
373
760
  this._log = null
374
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
375
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()
376
786
 
377
787
  // #6766: last SDK transcript message UUID seen this session. Captured from
378
788
  // each full `assistant` message in the query loop and used as the fork
@@ -395,6 +805,20 @@ export class SdkSession extends BaseSession {
395
805
  // destroy().
396
806
  this._taskIdByToolUseId = new Map()
397
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
+
398
822
  // Permission handling — delegated to PermissionManager. The pause/resume
399
823
  // hooks keep the inactivity timer suspended while a permission is pending:
400
824
  // waiting on user input is NOT inactivity, and without this a session with
@@ -406,6 +830,16 @@ export class SdkSession extends BaseSession {
406
830
  // #6771 — pass the durable rule store so an `allowAlways` decision persists
407
831
  // a project-scoped rule and this session seeds from prior grants for its cwd.
408
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
+ })
409
843
  wirePermissionManager(this, this._permissions, {
410
844
  onRequest: () => this._pauseResultTimeoutForPermission(),
411
845
  onResolved: () => this._resumeResultTimeoutForPermission(),
@@ -447,6 +881,26 @@ export class SdkSession extends BaseSession {
447
881
  // client UI feedback is unaffected.
448
882
  this._lastRefusedWarnTs = 0
449
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
+
450
904
  // #4881: provider parity with CliSession's #4602 _intentionalStop flag.
451
905
  // Set by `interrupt()` immediately before aborting the active SDK query
452
906
  // generator, then consumed inside `_callQuery`'s try/catch/finally so a
@@ -614,15 +1068,29 @@ export class SdkSession extends BaseSession {
614
1068
  message: 'Cannot send message — stdin forwarding is disabled; restart this session',
615
1069
  recoverable: false,
616
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
+ })
617
1075
  return
618
1076
  }
619
1077
 
620
- 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) {
621
1082
  // #5936 (epic #5935): a send-while-busy follow-up goes into the shared
622
1083
  // outgoing queue (BaseSession) — flushed FIFO on the next `result`. The
623
1084
  // overflow cap + the `message_queued` mirror event live in
624
1085
  // enqueueOutgoingMessage; nothing to do here but enqueue and return.
625
- 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
+ })
626
1094
  return
627
1095
  }
628
1096
 
@@ -638,12 +1106,29 @@ export class SdkSession extends BaseSession {
638
1106
  }
639
1107
 
640
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
641
1122
  this._messageCounter++
642
1123
  // `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
643
1124
  // the boot-unique prefix is needed (#3700). Format change does not
644
1125
  // affect the wire schema; clients treat messageId as opaque string.
645
1126
  const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
646
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 })
647
1132
  // Shared ref so _handleResultTimeout can observe the latest value
648
1133
  // when it fires (the timer was armed when hasStreamStarted was still
649
1134
  // false, but the turn may have streamed before the timeout landed).
@@ -698,6 +1183,13 @@ export class SdkSession extends BaseSession {
698
1183
  settingSources: ['user', 'project', 'local'],
699
1184
  systemPrompt,
700
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'),
701
1193
  }
702
1194
 
703
1195
  // SDK requires this flag when using bypassPermissions
@@ -709,11 +1201,9 @@ export class SdkSession extends BaseSession {
709
1201
  options.model = this.model
710
1202
  }
711
1203
 
712
- // Apply thinking level if set
713
- if (this._thinkingLevel) {
714
- const budget = SdkSession.THINKING_BUDGETS[this._thinkingLevel]
715
- if (budget != null) options.maxThinkingTokens = budget
716
- }
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())
717
1207
 
718
1208
  // #4306 — magic thinking-keyword escalation. The native Claude Code CLI's
719
1209
  // interactive REPL scans the user's prompt for keywords (`think`,
@@ -749,7 +1239,12 @@ export class SdkSession extends BaseSession {
749
1239
  options.sandbox = this._sandbox
750
1240
  }
751
1241
 
752
- // 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.
753
1248
  // We forward the SDK-provided `suggestions` to the permission manager
754
1249
  // so the 'allow always' flow can echo them back via updatedPermissions.
755
1250
  // Without this, respondToPermission('allowAlways') had nothing to
@@ -760,8 +1255,18 @@ export class SdkSession extends BaseSession {
760
1255
  // documentation is { behavior: 'allow', updatedPermissions:
761
1256
  // <suggestions from callback options> }.
762
1257
  if (this.permissionMode !== 'auto') {
763
- options.canUseTool = (toolName, input, { signal, suggestions }) =>
764
- 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
+ }
765
1270
  }
766
1271
 
767
1272
  // Resume existing session if we have one
@@ -811,24 +1316,225 @@ export class SdkSession extends BaseSession {
811
1316
  this._resetResultTimeout = resetResultTimeout
812
1317
  resetResultTimeout()
813
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
+
814
1446
  try {
815
- // Allow subclasses to augment query options (e.g. DockerSdkSession
816
- // injects spawnClaudeCodeProcess here)
817
- 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
+ }
818
1496
 
819
1497
  // If attachments present, build multimodal content blocks
820
1498
  const promptWithSkills = firstMessagePrefix
821
1499
  ? `${firstMessagePrefix}${transformedPrompt}`
822
1500
  : transformedPrompt
823
- const queryArgs = { prompt: promptWithSkills, options }
824
- if (attachments?.length) {
825
- queryArgs.prompt = buildContentBlocks(promptWithSkills, attachments)
826
- }
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 }
827
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' })
828
1531
  // #5269: a fresh turn — drop any task_id mappings left over from a prior
829
1532
  // turn (every subagent should clear via task_notification, but a turn
830
1533
  // aborted before its notifications would otherwise strand entries).
831
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.
832
1538
 
833
1539
  // _callQuery returned an iterable without throwing — the prepend
834
1540
  // bucket is committed to this turn's prompt, so flip the flag (#3225).
@@ -839,13 +1545,301 @@ export class SdkSession extends BaseSession {
839
1545
  this._skillsPrepended = true
840
1546
  }
841
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
+
842
1811
  for await (const msg of this._query) {
843
1812
  if (this._destroying) break
844
- 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
845
1834
 
846
1835
  switch (msg.type) {
847
1836
  case 'system': {
848
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')
849
1843
  this._sdkSessionId = msg.session_id
850
1844
  this._sessionId = msg.session_id
851
1845
  // #4828: bind the session-scoped logger now that session_id
@@ -875,6 +1869,13 @@ export class SdkSession extends BaseSession {
875
1869
  }
876
1870
  // Fetch dynamic model list from SDK (non-blocking)
877
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
+ })
878
1879
  } else if (msg.subtype === 'task_started') {
879
1880
  // #5269: a Task subagent started. The SDK message carries BOTH
880
1881
  // the subagent's `task_id` (needed by query.stopTask) and the
@@ -883,6 +1884,49 @@ export class SdkSession extends BaseSession {
883
1884
  // activity id back to a stoppable task. No client-facing emit —
884
1885
  // the agent node already exists via agent_spawned.
885
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
+ }
886
1930
  break
887
1931
  } else if (msg.subtype === 'task_notification') {
888
1932
  // #5269: a Task subagent reached a terminal state (completed /
@@ -891,6 +1935,37 @@ export class SdkSession extends BaseSession {
891
1935
  // cancel feels responsive instead of waiting for the turn-end
892
1936
  // sweep. Idempotent (no-op if already finalized).
893
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
+ }
894
1969
  break
895
1970
  } else if (msg.subtype === 'compact_boundary') {
896
1971
  // #6768: the SDK compacted the conversation (auto-triggered
@@ -914,6 +1989,24 @@ export class SdkSession extends BaseSession {
914
1989
  timestamp: Date.now(),
915
1990
  })
916
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
+ }
2009
+ break
917
2010
  } else {
918
2011
  // Forward non-init system events (e.g. /usage, /cost, other
919
2012
  // slash command responses) as system messages to the client
@@ -930,6 +2023,8 @@ export class SdkSession extends BaseSession {
930
2023
  }
931
2024
 
932
2025
  case 'stream_event': {
2026
+ promptActivitySeen = true // #8300: the prompt is running
2027
+ confirmHeldNotice('stream events followed it')
933
2028
  // Handle partial message events (content_block_start/delta/stop)
934
2029
  const event = msg.event
935
2030
  if (!event) break
@@ -1017,6 +2112,13 @@ export class SdkSession extends BaseSession {
1017
2112
  didStreamThinking = true
1018
2113
  this.emit('stream_delta', { messageId: thinkingId, delta: delta.thinking, thinking: true })
1019
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.
1020
2122
  break
1021
2123
  }
1022
2124
 
@@ -1051,13 +2153,29 @@ export class SdkSession extends BaseSession {
1051
2153
  }
1052
2154
 
1053
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
+ }
1054
2169
  // #6766: remember this message's transcript UUID as the fork
1055
2170
  // boundary. A checkpoint auto-created at the start of the NEXT turn
1056
2171
  // captures this as its boundary, so restoring that checkpoint can
1057
2172
  // fork the conversation truncated to exactly this point.
1058
2173
  this._captureBoundaryMessage(msg)
2174
+ promptActivitySeen = true // #8300: the prompt is running
2175
+ confirmHeldNotice('assistant output followed it')
1059
2176
  // Full assistant message — process content blocks for tool detection
1060
2177
  const content = msg.message?.content
2178
+ emitTurnEvent('assistant_response', { responseId: msg.message?.id ?? msg.uuid, text: assistantResponseText(content) })
1061
2179
  if (!Array.isArray(content)) break
1062
2180
 
1063
2181
  for (const block of content) {
@@ -1092,6 +2210,42 @@ export class SdkSession extends BaseSession {
1092
2210
  }
1093
2211
 
1094
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
+ }
1095
2249
  // Tool result content blocks appear in user-role messages during the tool loop
1096
2250
  emitToolResults(msg.message?.content, this)
1097
2251
  // #4307: scan tool_result blocks for the canonical
@@ -1102,135 +2256,238 @@ export class SdkSession extends BaseSession {
1102
2256
  // truncation surface (tool-result.js is also used by
1103
2257
  // CliSession + GeminiSession, which don't share this
1104
2258
  // BaseSession path).
1105
- this._recordBackgroundShellsFromToolResults(msg.message?.content)
2259
+ this._recordBackgroundShellsFromToolResults(msg.message?.content, turnShellIds)
1106
2260
  break
1107
2261
  }
1108
2262
 
1109
2263
  case 'result': {
1110
- if (streamState.hasStreamStarted) {
1111
- this.emit('stream_end', { messageId })
1112
- }
1113
-
1114
- if (msg.session_id) {
1115
- this._sdkSessionId = msg.session_id
1116
- this._sessionId = msg.session_id
1117
- }
1118
-
1119
- // Correct any static context-window guess using the SDK's
1120
- // authoritative per-model values. Only cache + broadcast when
1121
- // a value actually changed to avoid thrashy writes / UI churn.
1122
- let contextWindowChanged = false
1123
- if (msg.modelUsage && typeof msg.modelUsage === 'object') {
1124
- const missingIds = []
1125
- for (const [modelId, usage] of Object.entries(msg.modelUsage)) {
1126
- if (usage && typeof usage.contextWindow === 'number') {
1127
- if (updateContextWindow(modelId, usage.contextWindow)) {
1128
- contextWindowChanged = true
1129
- }
1130
- } else {
1131
- missingIds.push(modelId)
1132
- }
1133
- }
1134
- // Drift signal: at least one modelUsage entry was missing a
1135
- // numeric contextWindow. Catches both total drift (field renamed
1136
- // or removed upstream) and partial drift (schema updated for one
1137
- // model family before another). Log a redacted sample so a
1138
- // future regression is diagnosable without flooding info-level
1139
- // output.
1140
- if (missingIds.length > 0) {
1141
- const sampleId = missingIds[0]
1142
- const sampleKeys = Object.keys(msg.modelUsage[sampleId] || {})
1143
- // #4828: session-scoped (result handler runs strictly post-init).
1144
- ;(this._log || log).debug(
1145
- `modelUsage partial drift: contextWindow missing for modelIds=${JSON.stringify(missingIds)} sampleKeys=${JSON.stringify(sampleKeys)}`
1146
- )
1147
- }
1148
- }
1149
- if (contextWindowChanged) {
1150
- saveModelsCache()
1151
- // Notify connected clients so the picker / budget UI picks up
1152
- // the corrected window without waiting for the next refresh.
1153
- this.emit('models_updated', { models: getModels() })
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
1154
2294
  }
1155
-
1156
- // #6769: end-of-turn occupancy snapshot via the SDK's
1157
- // getContextUsage() control API — the same number Claude Code's
1158
- // own /context shows. Queried while `this._query` is still live
1159
- // (we're inside the for-await; the CLI process is alive until
1160
- // the generator completes). `msg.usage` below is the per-turn
1161
- // BILLING aggregate (summed across agent-loop rounds) and must
1162
- // never be read as occupancy — see context-window.ts (#6769).
1163
- // Null on timeout/old-CLI/error → field omitted → clients keep
1164
- // their previous snapshot (or the honest dash state).
1165
- const contextUsageSnapshot = await this._getContextUsageSnapshot()
1166
-
1167
- // #4628: sweep any orphan tool_starts before emitting result
1168
- // so the dashboard's activeTools clears as part of the same
1169
- // turn-end burst. _clearMessageState (called next) would also
1170
- // clear the in-flight map but without broadcasting synthetic
1171
- // tool_results to the dashboard.
1172
- this._emitResult({
1173
- sessionId: msg.session_id || this._sdkSessionId,
1174
- cost: msg.total_cost_usd,
1175
- duration: msg.duration_ms,
1176
- usage: msg.usage,
1177
- // #6692: surface the per-model split + turn metadata the SDK
1178
- // already reports instead of discarding them. Additive — every
1179
- // existing result consumer ignores unknown fields.
1180
- numTurns: Number.isFinite(msg.num_turns) ? msg.num_turns : null,
1181
- apiDurationMs: Number.isFinite(msg.duration_api_ms) ? msg.duration_api_ms : null,
1182
- modelUsage: normalizeSdkModelUsage(msg.modelUsage),
1183
- // #6769: occupancy snapshot (or absent when unavailable).
1184
- // Wire field is contextOccupancy — NOT contextUsage — so it can
1185
- // never be confused with the billing `usage` aggregate above.
1186
- ...(contextUsageSnapshot ? { contextOccupancy: contextUsageSnapshot } : {}),
1187
- }, 'turn_ended_with_orphan_tool_start')
1188
-
1189
- this._clearMessageState()
2295
+ await finishTurn(msg)
1190
2296
  break
1191
2297
  }
1192
2298
  }
1193
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
+ }
1194
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
+ }
1195
2324
  if (streamState.hasStreamStarted) {
1196
2325
  this.emit('stream_end', { messageId })
1197
2326
  }
1198
2327
  // #4881: capture-and-clear before any branch so the flag never leaks
1199
2328
  // past this turn even when _destroying short-circuits the emits below.
1200
2329
  // Mirrors CliSession._handleChildClose (#4602).
1201
- 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()
1202
2337
  if (!this._destroying) {
1203
- 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) {
1204
2345
  // #4881: user clicked Stop — interrupt() set the flag, the SDK
1205
2346
  // generator threw an AbortError as a result. Skip the loud "Query
1206
2347
  // error" surface and emit the quiet `stopped` event for parity
1207
2348
  // with CliSession. No `code` because SDK runs in-process — there
1208
2349
  // is no child-process exit status to carry.
1209
2350
  ;(this._log || log).info('Query aborted after user stop')
1210
- 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)
1211
2370
  } else {
1212
- // #4828: session-scoped when init has fired; falls back to module
1213
- // `log` for pre-init query failures (e.g. spawn refused).
1214
- ;(this._log || log).error(`Query error: ${err.message}`)
1215
- this.emit('error', { message: SdkSession._enrichErrorMessage(err.message) })
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
+ }
1216
2418
  }
1217
2419
  }
1218
- 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
+ }
1219
2432
  } finally {
1220
- 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()
1221
2473
  // #4881: safety-net clear of _intentionalStop. The catch block clears
1222
2474
  // it on the throw path (AbortError after interrupt()), but if
1223
2475
  // query.interrupt() races a `result` message arriving first, the
1224
2476
  // for-await loop exits normally, skipping the catch. Without this
1225
2477
  // clear, the flag would stay armed until the next turn's catch and
1226
2478
  // mis-trigger a spurious `stopped` emit there. Idempotent — the
1227
- // catch path already cleared it on the throw path.
1228
- 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
+ }
1229
2486
  // Dequeue any follow-up messages that arrived while busy (#5936: the
1230
2487
  // shared `_outgoingQueue`; flush one item via dequeueNextOutgoing, whose
1231
2488
  // re-dispatched sendMessage re-sets _isBusy so the next `result` drains
1232
2489
  // the following item — FIFO, one turn at a time).
1233
- if (this._outgoingQueue.length && !this._destroying) {
2490
+ if (this._outgoingQueue.length && !this._destroying && !supersededByNewerTurn()) {
1234
2491
  // #3562: if the SidecarProcess latched stdin_disabled mid-turn (e.g.
1235
2492
  // the PassThrough closed while _callQuery was still streaming), the
1236
2493
  // entry-gate at the top of sendMessage has already been bypassed
@@ -1265,6 +2522,111 @@ export class SdkSession extends BaseSession {
1265
2522
  return query(queryArgs)
1266
2523
  }
1267
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
+
1268
2630
  /**
1269
2631
  * #6769: fetch the end-of-turn context-window OCCUPANCY snapshot from the
1270
2632
  * SDK's `getContextUsage()` control API (verified on
@@ -1501,10 +2863,39 @@ export class SdkSession extends BaseSession {
1501
2863
  ;(this._log || log).warn(`Tool input for ${block.name} exceeded ${this._maxToolInput} bytes, skipping`)
1502
2864
  this.emit('error', {
1503
2865
  message: `Tool input too large (>${Math.round(this._maxToolInput / 1024)}KB) for ${block.name} — tool use was skipped`,
2866
+ declarationTurnId: messageId,
1504
2867
  })
1505
2868
  return
1506
2869
  }
1507
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
+
1508
2899
  // #4307: stash the command text against the tool_use_id so the
1509
2900
  // matching tool_result (carrying the shellId Claude prints) can
1510
2901
  // recover it. Strict-boolean run_in_background check; non-Bash
@@ -1537,18 +2928,34 @@ export class SdkSession extends BaseSession {
1537
2928
  // agent_spawned toolUseId + _activeAgents key match the wire-emitted
1538
2929
  // tool_start id. Without this, _activeAgents.set(undefined, ...)
1539
2930
  // collides on undefined for any fallback-path Task spawn.
1540
- const toolUseId = block.id || `${messageId}-tool`
1541
- 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({
1542
2939
  toolUseId,
1543
2940
  description: semantics.payload.description,
1544
- startedAt: Date.now(),
1545
- }
1546
- this._activeAgents.set(toolUseId, agentInfo)
1547
- 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
1548
2958
  }
1549
- // EnterPlanMode / ExitPlanMode are not currently surfaced by SdkSession
1550
- // (plan-mode flow is CliSession-only today). Extracting via the shared
1551
- // parser leaves the door open without changing observable behavior.
1552
2959
  }
1553
2960
 
1554
2961
  /**
@@ -1562,9 +2969,11 @@ export class SdkSession extends BaseSession {
1562
2969
  * (no-op) — the standard tool-loop flow always populates both.
1563
2970
  *
1564
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.
1565
2974
  * @private
1566
2975
  */
1567
- _recordBackgroundShellsFromToolResults(content) {
2976
+ _recordBackgroundShellsFromToolResults(content, ownedShellIds = null) {
1568
2977
  if (!Array.isArray(content)) return
1569
2978
  for (const block of content) {
1570
2979
  if (block?.type !== 'tool_result' || !block.tool_use_id) continue
@@ -1586,7 +2995,8 @@ export class SdkSession extends BaseSession {
1586
2995
  // #5177: capture the output file path from the same tool_result so the
1587
2996
  // completion sweep can reap the shell on quiescence without a poll.
1588
2997
  const outputPath = parseBackgroundShellOutputPath(text)
1589
- 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)
1590
3000
  }
1591
3001
  }
1592
3002
 
@@ -1594,16 +3004,146 @@ export class SdkSession extends BaseSession {
1594
3004
  * In-process permission handler for canUseTool callback.
1595
3005
  * Delegates to the PermissionManager.
1596
3006
  */
1597
- _handlePermission(toolName, input, signal, suggestions) {
1598
- 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
+ }
1599
3139
  }
1600
3140
 
1601
3141
  /**
1602
3142
  * Resolve a pending permission request (called by WsServer when
1603
3143
  * the app sends permission_response).
1604
3144
  */
1605
- respondToPermission(requestId, decision, editedInput, reason) {
1606
- return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
3145
+ respondToPermission(requestId, decision, editedInput, reason, scope) {
3146
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
1607
3147
  }
1608
3148
 
1609
3149
  /**
@@ -1611,8 +3151,9 @@ export class SdkSession extends BaseSession {
1611
3151
  * In SDK mode, the canUseTool callback is holding a Promise open.
1612
3152
  * This method resolves it with the user's answer as structured updatedInput.
1613
3153
  */
1614
- respondToQuestion(text, answersMap) {
1615
- 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)
1616
3157
  }
1617
3158
 
1618
3159
  /**
@@ -1622,15 +3163,29 @@ export class SdkSession extends BaseSession {
1622
3163
  _onModelChanged() {
1623
3164
  // #4828: session-scoped when init has fired.
1624
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 })
1625
3182
  }
1626
3183
 
1627
3184
  _onPermissionModeChanged(mode) {
1628
3185
  this._permissions.clearRules()
1629
- // #3729: switching TO auto is a "panic button" — drain any pending
1630
- // permission prompts so the user isn't left staring at modals after
1631
- // declaring "approve everything". Without this, prompts that were
1632
- // emitted under the previous mode hang until the user resolves them
1633
- // or they hit the 5-min timeout, contradicting the bypass semantics.
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.
1634
3189
  if (mode === 'auto') {
1635
3190
  this._permissions.autoAllowPending()
1636
3191
  }
@@ -1692,25 +3247,200 @@ export class SdkSession extends BaseSession {
1692
3247
  }
1693
3248
 
1694
3249
  /**
1695
- * Set thinking level by adjusting max thinking tokens.
1696
- * @param {string} level - 'default' | 'high' | 'max'
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
1697
3264
  */
1698
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 {}
1699
3368
  const budget = SdkSession.THINKING_BUDGETS[level] ?? null
1700
- 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
+ }
1701
3374
 
1702
- 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 {
1703
3404
  try {
1704
- await this._query.setMaxThinkingTokens(budget)
1705
- // #4828: session-scoped (setThinkingLevel only takes effect with
1706
- // an active query — strictly post-init).
1707
- ;(this._log || log).info(`Thinking level set to ${level} (${budget ?? 'adaptive'} tokens)`)
3405
+ applied = (await query.getSettings())?.applied ?? null
3406
+ reason = applied ? `reported by Claude Code ${when}` : 'Claude Code did not report the effort it applies'
1708
3407
  } catch (err) {
1709
- ;(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})`
1710
3409
  }
1711
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
+ }
1712
3430
 
1713
- // 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)
1714
3444
  }
1715
3445
 
1716
3446
  /**
@@ -1733,7 +3463,11 @@ export class SdkSession extends BaseSession {
1733
3463
 
1734
3464
  try {
1735
3465
  const sdkModels = await this._query.supportedModels()
1736
- 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)
1737
3471
  if (converted && converted.length > 0) {
1738
3472
  // #4828: session-scoped (called from init handler so _log is set).
1739
3473
  ;(this._log || log).info(`Dynamic model list: ${converted.map(m => m.id).join(', ')}`)
@@ -1741,7 +3475,7 @@ export class SdkSession extends BaseSession {
1741
3475
  this.emit('models_updated', { models: converted })
1742
3476
  }
1743
3477
  } catch (err) {
1744
- ;(this._log || log).warn(`Failed to fetch supported models: ${err.message}`)
3478
+ ;(this._log || log).warn(`Failed to fetch supported models: ${err?.message || err}`)
1745
3479
  }
1746
3480
  }
1747
3481
 
@@ -1773,10 +3507,10 @@ export class SdkSession extends BaseSession {
1773
3507
  _finalizeAgentByToolUseId(toolUseId) {
1774
3508
  if (typeof toolUseId !== 'string' || !toolUseId) return
1775
3509
  this._taskIdByToolUseId.delete(toolUseId)
1776
- if (this._activeAgents.has(toolUseId)) {
1777
- this._activeAgents.delete(toolUseId)
1778
- this.emit('agent_completed', { toolUseId })
1779
- }
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)
1780
3514
  }
1781
3515
 
1782
3516
  /**
@@ -1841,13 +3575,40 @@ export class SdkSession extends BaseSession {
1841
3575
  // already settling) so an interrupt never strands a queued message.
1842
3576
  this.clearOutgoingQueue()
1843
3577
 
1844
- 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
+ }
1845
3584
 
1846
3585
  // #4881: mark the imminent query teardown as user-initiated so the
1847
3586
  // _callQuery catch block suppresses the AbortError-flavored "Query error"
1848
3587
  // emit and instead surfaces a quiet `stopped` event. Cleared in the
1849
3588
  // catch/finally (single-use, mirrors CliSession#4602).
1850
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
+ }
1851
3612
 
1852
3613
  // #4828: session-scoped (interrupt() only meaningful with an active query).
1853
3614
  ;(this._log || log).info('Interrupting query')
@@ -1916,8 +3677,11 @@ export class SdkSession extends BaseSession {
1916
3677
  // into a cleared message. Best-effort — the SDK's generator may not
1917
3678
  // support .return()/.throw() uniformly.
1918
3679
  this._abortActiveQuery()
1919
- this._clearMessageState()
1920
- 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 })
1921
3685
  }
1922
3686
 
1923
3687
  /**
@@ -1950,10 +3714,11 @@ export class SdkSession extends BaseSession {
1950
3714
  // Attempt to abort the SDK query generator so no further events land
1951
3715
  // into a cleared message context. Best-effort — matches _handleHardTimeout.
1952
3716
  this._abortActiveQuery()
3717
+ this._abandonDrain() // #8321
1953
3718
  // #4616: snapshot sessionId BEFORE _clearMessageState wipes it so the
1954
3719
  // synthetic `result` event below carries the correct identifier.
1955
3720
  const sessionId = this._sdkSessionId || this._sessionId
1956
- this._clearMessageState()
3721
+ this._clearMessageState({ terminatedReason: 'stream_stall' }) // #7376
1957
3722
  // #4616: emit a synthetic `result` so event-normalizer fans it to
1958
3723
  // `agent_idle`. Per #4308 handleAgentIdle clears `activeTools: []`
1959
3724
  // as a safety net, which is what stops the dashboard's footer pill
@@ -1961,13 +3726,79 @@ export class SdkSession extends BaseSession {
1961
3726
  // _emitInterruptedTurnResult (stream_end + result); the SDK was
1962
3727
  // previously missing the `result` half of the pair. cost:null skips
1963
3728
  // session-manager billing accumulation (mirrors CLI).
1964
- 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 })
1965
3736
  this.emit('error', {
1966
3737
  code: 'stream_stall',
1967
- message: `Stream stalled — no response for ${friendly}. Try sending again.`,
3738
+ message,
3739
+ declarationTurnId: messageId,
1968
3740
  })
1969
3741
  }
1970
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
+
1971
3802
  /**
1972
3803
  * Best-effort abort of the active SDK query generator. Used when the
1973
3804
  * session times out mid-turn so tool results don't stream into a
@@ -2038,14 +3869,35 @@ export class SdkSession extends BaseSession {
2038
3869
  /**
2039
3870
  * Clear per-message state, marking us as ready for the next message.
2040
3871
  */
2041
- _clearMessageState() {
2042
- super._clearMessageState()
2043
- 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()
2044
3887
  // Pause counter is tied to the previous message — reset so the next
2045
3888
  // message starts with a fresh counter.
2046
3889
  this._permissionPauseCount = 0
2047
3890
  this._resultTimeoutPaused = false
2048
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
2049
3901
  }
2050
3902
 
2051
3903
  /**
@@ -2053,6 +3905,8 @@ export class SdkSession extends BaseSession {
2053
3905
  */
2054
3906
  destroy() {
2055
3907
  this._destroying = true
3908
+ this._deniedToolMessages.clear() // #8936
3909
+ if (this._drainingTurn) this._endDrain(this._drainingTurn)
2056
3910
  // #5936: tear down the shared outgoing queue silently — no message_dequeued
2057
3911
  // (which signals "sent") for a session that's going away.
2058
3912
  this.clearOutgoingQueue({ emit: false })
@@ -2077,13 +3931,32 @@ export class SdkSession extends BaseSession {
2077
3931
  this._streamStallTimeout = null
2078
3932
  }
2079
3933
 
2080
- // 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).
2081
3945
  if (this._query) {
2082
- 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 || '')
2083
3952
  // #4828: session-scoped when init has fired.
2084
- ;(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)`)
2085
3954
  })
2086
- 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
+ }
2087
3960
  }
2088
3961
 
2089
3962
  // Emit completions for any tracked agents and clear busy state