@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,48 +1,40 @@
1
+ import { assistantResponseText, sdkDeclarationEligible } from './assistant-response.js'
1
2
  import { spawn } from 'child_process'
3
+ import { stillAuthorized } from './connection-authority.js'
2
4
  import { createInterface } from 'readline'
3
- import { randomBytes } from 'crypto'
5
+ import { randomBytes, randomUUID } from 'crypto'
6
+ import { mkdirSync, rmSync, writeFileSync } from 'fs'
4
7
  import { normalizeSdkModelUsage } from './usage-normalize.js'
5
- import { homedir } from 'os'
8
+ import { tmpdir } from 'os'
9
+ import { claudeConfigDir } from './utils/claude-config-dir.js'
6
10
  import { join } from 'path'
7
11
  import { createPermissionHookManager } from './permission-hook.js'
8
12
  import { guardChildStreams } from './child-stream-guard.js'
9
- import { BaseSession, buildBaseSessionOpts } from './base-session.js'
13
+ import { BaseSession, buildBaseSessionOpts, reportInputAdmission, spawnRefusalAdmission } from './base-session.js'
10
14
  import { buildContentBlocks } from './content-blocks.js'
11
15
  import { ALLOWED_MODEL_IDS } from './models.js'
12
16
  import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
13
17
  import { forceKill, killProcessTree } from './platform.js'
14
18
  import { MessageTransformPipeline } from './message-transform.js'
15
19
  import { emitToolResults } from './tool-result.js'
16
- import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent } from './claude-stream-parser.js'
17
- import { resolveBinary } from './utils/resolve-binary.js'
20
+ import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent, formatStatusContent } from './claude-stream-parser.js'
21
+ import { ThinkingStreams } from './thinking-stream.js'
22
+ import { CLAUDE_BINARY_CANDIDATES, resolveClaudeBinary } from './utils/claude-binary.js'
18
23
  import { labelBinarySpawnFailure } from './utils/verify-binary.js'
19
24
  import { prepareSpawn } from './utils/win-spawn.js'
25
+ import { CLAUDE_CLI_CUSTOMIZATION } from './provider-customization.js'
20
26
  import { buildSpawnEnv } from './utils/spawn-env.js'
21
27
  import { RespawnRateLimiter } from './utils/respawn-rate-limiter.js'
28
+ import { assertSafeArgvValue } from './utils/argv-safety.js'
29
+ import { writePermissionModeSidecarAtomic } from './utils/permission-mode-sidecar.js'
30
+ import { sweepStaleOwnedDirs, ensureOwnedBaseDir, OWNER_PID_FILE } from './utils/stale-session-dirs.js'
22
31
  import { createLogger, loggerForSession } from './logger.js'
23
32
  import { formatIdleDuration } from './session-timeout-manager.js'
24
33
  import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
34
+ import { turnOutcomeField, outcomeFromSdkResult } from './turn-outcome.js'
25
35
 
26
36
  const log = createLogger('cli-session')
27
37
 
28
- // Well-known fallback locations. Under a GUI launch (e.g. Tauri on macOS) PATH
29
- // is minimal and may exclude the user's install dir — fall through to these so
30
- // `spawn()` succeeds.
31
- const CLAUDE_BINARY_CANDIDATES = [
32
- join(homedir(), '.local/bin/claude'),
33
- '/opt/homebrew/bin/claude',
34
- '/usr/local/bin/claude',
35
- join(homedir(), '.claude/local/node_modules/.bin/claude'),
36
- join(homedir(), '.npm-global/bin/claude'),
37
- ]
38
-
39
- // Re-resolve fresh on every spawn (NOT a frozen module-load const) so a binary
40
- // quarantined / moved / reinstalled after daemon start is spawned from its
41
- // CURRENT path — and matches what preflight verified (#6708 defect #3).
42
- function resolveClaudeBinary() {
43
- return resolveBinary('claude', CLAUDE_BINARY_CANDIDATES)
44
- }
45
-
46
38
  // Default max accumulated size for tool_use input_json_delta chunks (~256KB)
47
39
  const DEFAULT_MAX_TOOL_INPUT_LENGTH = 262144
48
40
 
@@ -111,6 +103,38 @@ export function stderrIndicatesUnknownResume(stderrLines) {
111
103
  return false
112
104
  }
113
105
 
106
+ // #7847: the canonical rejection with every space removed, followed by the session UUID.
107
+ export const COMPACTED_UNKNOWN_RESUME_PATTERN =
108
+ /noconversationfoundwithsessionid:?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
109
+
110
+ /**
111
+ * Cursor-positioned TUI rendering of claude's unknown-resume rejection can reach
112
+ * the PTY tail as several fragments with the inter-word spaces removed
113
+ * (`Noconvers` / `ation` / `foundwith` / `session` / `ID:<uuid>`, #7847), so
114
+ * neither a single line nor a space-joined adjacent pair matches the
115
+ * per-line patterns above. This tests a whitespace-compacted join of up to
116
+ * `windowLines` consecutive lines against the canonical rejection ONLY: the full
117
+ * phrase "No conversation found with session ID:" followed by a UUID. The UUID
118
+ * anchor keeps it narrow — transcript text that merely discusses resume or
119
+ * session errors has no such phrase+id shape and never matches.
120
+ *
121
+ * The window is 10 lines: the five phrase fragments plus a UUID that may itself
122
+ * wrap across several rows at the narrowest widths.
123
+ *
124
+ * @param {string[]} lines
125
+ * @param {number} [windowLines=10]
126
+ * @returns {boolean}
127
+ */
128
+ export function stderrIndicatesUnknownResumeCompacted(lines, windowLines = 10) {
129
+ if (!Array.isArray(lines) || lines.length === 0) return false
130
+ const compact = lines.map((l) => (typeof l === 'string' ? l.replace(/\s+/g, '') : ''))
131
+ for (let i = 0; i < compact.length; i++) {
132
+ const joined = compact.slice(i, i + windowLines).join('')
133
+ if (COMPACTED_UNKNOWN_RESUME_PATTERN.test(joined)) return true
134
+ }
135
+ return false
136
+ }
137
+
114
138
  /**
115
139
  * Build the argv passed to `claude -p --input-format stream-json …`.
116
140
  *
@@ -167,7 +191,26 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
167
191
  // the model retains the full prior transcript. Only emitted when a non-empty
168
192
  // string is known; a brand-new session (first start()) leaves this off so
169
193
  // claude CLI mints a fresh conversation id on its `system.init` line.
194
+ //
195
+ // #7868 — REJECTED, not merely passed through, because `-r, --resume` is
196
+ // declared with an OPTIONAL argument (`[value]`), not a required one.
197
+ // Measured against the installed claude CLI (2.1.282):
198
+ //
199
+ // claude -p --resume --this-is-not-a-real-flag-xyz --output-format ...
200
+ // → error: unknown option '--this-is-not-a-real-flag-xyz' (exit 1)
201
+ //
202
+ // — i.e. the two-token form INJECTS for an optional-arg flag (the opposite
203
+ // of `--model <model>` / `--append-system-prompt <prompt>` above, both
204
+ // declared REQUIRED and measured swallowed-as-value). `resumeSessionId` can
205
+ // never legitimately start with `-`: it is either this file's own
206
+ // CLI-emitted `system.init` session_id, or a client-supplied resume target
207
+ // already required to be a canonical UUID by
208
+ // handlers/conversation-handlers.js's CONVERSATION_ID_RE before it reaches
209
+ // here — but relying on every current and future caller to keep that
210
+ // constraint is the exact "someone remembers to sweep" gap #7868 exists to
211
+ // close, so it is asserted here too (case 1: reject).
170
212
  if (typeof resumeSessionId === 'string' && resumeSessionId.length > 0) {
213
+ assertSafeArgvValue(resumeSessionId, 'resumeSessionId')
171
214
  args.push('--resume', resumeSessionId)
172
215
  }
173
216
 
@@ -189,6 +232,7 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
189
232
  * stream_end { messageId }
190
233
  * message { type, content, tool, timestamp }
191
234
  * tool_start { messageId, tool, input }
235
+ * tool_input_delta { messageId, toolUseId, partialJson }
192
236
  * result { cost, duration, usage, sessionId }
193
237
  * error { message }
194
238
  * user_question { toolUseId, questions }
@@ -196,14 +240,20 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
196
240
  * agent_completed { toolUseId }
197
241
  * plan_started {}
198
242
  * plan_ready { allowedPrompts }
199
- * tool_result { toolUseId, result, truncated }
243
+ * tool_result { toolUseId, result, truncated, input? }
200
244
  */
201
245
 
202
246
  export class CliSession extends BaseSession {
247
+ static canonicalAssistantResponses = true
248
+
203
249
  // #5858: Claude-family flag — single source of truth for isClaudeProvider().
204
250
  // DockerSession (docker-cli / docker) extends this and inherits it.
205
251
  static claudeFamily = true
206
252
 
253
+ static get customizationDescriptor() {
254
+ return CLAUDE_CLI_CUSTOMIZATION
255
+ }
256
+
207
257
  /**
208
258
  * Human-readable label shown in the startup banner and anywhere else the
209
259
  * server needs to name this provider (#2953). Each provider owns its own
@@ -228,7 +278,21 @@ export class CliSession extends BaseSession {
228
278
  * exhaust there.
229
279
  */
230
280
  static get customEvents() {
231
- return ['respawn_exhausted']
281
+ // #7346: `tool_input_delta` delivers the SANITIZED full tool input
282
+ // as a single chunk once its content_block finalizes (see
283
+ // `_captureFinalizedToolInput`, called from `content_block_stop`) —
284
+ // matches byok-session.js's wire shape/client handler exactly so
285
+ // store-core's `handleToolInputDelta` needs no provider branch.
286
+ // Per #8135/#8137, NEITHER cli-session.js NOR byok-session.js
287
+ // streams raw per-chunk `input_json_delta` partials any more — a
288
+ // secret can straddle chunk boundaries and can't be sanitized
289
+ // mid-stream, so both providers only ever emit once, already-safe.
290
+ // Without listing it here, `session-manager.js`'s
291
+ // `_wireSessionEvents` never bridges the local EventEmitter emit
292
+ // onto the `session_event` channel and it never reaches the client
293
+ // (same wiring requirement documented on byok-session.js's
294
+ // `customEvents`).
295
+ return ['respawn_exhausted', 'tool_input_delta']
232
296
  }
233
297
 
234
298
  /**
@@ -238,13 +302,15 @@ export class CliSession extends BaseSession {
238
302
  * hardcoding the path.
239
303
  */
240
304
  static get dataDir() {
241
- return join(homedir(), '.claude')
305
+ return claudeConfigDir()
242
306
  }
243
307
 
244
308
  static get capabilities() {
245
309
  return {
246
310
  permissions: true,
247
311
  inProcessPermissions: false,
312
+ permissionFloor: true,
313
+ autoPermissionMode: true,
248
314
  modelSwitch: true,
249
315
  permissionModeSwitch: true,
250
316
  // #5609: switching to 'auto' mid-turn is the #3729 panic-button —
@@ -262,9 +328,22 @@ export class CliSession extends BaseSession {
262
328
  resume: true,
263
329
  terminal: false,
264
330
  thinkingLevel: false,
331
+ // #7725: the legacy `claude -p` subprocess never runs
332
+ // detect-thinking-keyword.js, so typing `ultrathink` escalates nothing
333
+ // here. Declared explicitly (like `streaming`) so the matrix stays
334
+ // uniform rather than leaving the flag's absence to be guessed.
335
+ thinkingKeywords: false,
336
+ thinkingLevelEffective: false, // #8700: no report of the applied level
265
337
  // #3932: declared explicitly so the capability matrix matches across
266
338
  // providers — claude-tui is the only one that sets this to false.
267
339
  streaming: true,
340
+ // #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
341
+ // idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
342
+ // cleared by `interrupt()`), and reports admission through
343
+ // `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
344
+ // can travel it as an ordinary user turn. session-wake.js gates on this with
345
+ // strict `=== true`; absent means NOT supported. Never duck-typed.
346
+ daemonTurnInput: true,
268
347
  }
269
348
  }
270
349
 
@@ -288,13 +367,7 @@ export class CliSession extends BaseSession {
288
367
  binary: {
289
368
  name: 'claude',
290
369
  args: ['--version'],
291
- candidates: [
292
- join(homedir(), '.local/bin/claude'),
293
- '/opt/homebrew/bin/claude',
294
- '/usr/local/bin/claude',
295
- join(homedir(), '.claude/local/node_modules/.bin/claude'),
296
- join(homedir(), '.npm-global/bin/claude'),
297
- ],
370
+ candidates: CLAUDE_BINARY_CANDIDATES,
298
371
  installHint: 'install Claude Code CLI',
299
372
  },
300
373
  credentials: {
@@ -399,6 +472,14 @@ export class CliSession extends BaseSession {
399
472
  this._inPlanMode = false
400
473
  this._planAllowedPrompts = null
401
474
  this._waitingForAnswer = false
475
+ // #7457 -- the AskUserQuestion payload behind `_waitingForAnswer`, so a
476
+ // reconnecting client can be handed the question the child is parked on
477
+ // (`getPendingQuestions`). Kept strictly CO-LOCATED with the flag: every
478
+ // line that writes `_waitingForAnswer` writes this in the same statement
479
+ // block, so the two cannot disagree and there is no second lifecycle to
480
+ // leak. `_waitingForAnswer` stays the read gate `respondToQuestion` uses --
481
+ // this is a payload, not a new source of truth.
482
+ this._pendingQuestion = null
402
483
  this._currentCtx = null
403
484
  this._pendingQueue = []
404
485
  this._respawnCount = 0
@@ -430,13 +511,30 @@ export class CliSession extends BaseSession {
430
511
  // Single-use: set by interrupt(), cleared by _handleChildClose / destroy.
431
512
  // The flag itself is declared+initialized on BaseSession (#5375).
432
513
 
514
+ // #7438: latched by the intentional-stop branch of _handleChildClose when
515
+ // that stop leaves us with no child, and consumed by the next sendMessage
516
+ // (_restartAfterStop). It is what makes a stopped session restartable —
517
+ // see _restartAfterStop for why the restart is gated on this rather than
518
+ // on "the child is gone".
519
+ this._stoppedByUser = false
520
+
433
521
  // Hook manager (shared module)
434
522
  this._hookManager = (this._port) ? createPermissionHookManager(this, { settingsPath }) : null
435
523
 
524
+ // #7337: the re-readable permission-mode sidecar. `permission-hook.sh`
525
+ // prefers this file over CHROXY_PERMISSION_MODE, which is frozen at spawn.
526
+ // Created on the first start() when permissions are enabled, reused across
527
+ // respawns, removed on destroy(). Null means "env-var-only" — either
528
+ // permissions are off (no port) or the initial write failed.
529
+ this._permissionModeFile = null
530
+ this._permissionModeDir = null
531
+
436
532
  // Pending-permission bookkeeping for the inactivity timer (#2831).
437
533
  // WsServer calls notifyPermissionPending/Resolved when a hook
438
534
  // permission belonging to this session is broadcast/resolved.
439
- this._pendingPermissionIds = new Set()
535
+ // #7382: `_pendingPermissionIds` now lives on BaseSession so every
536
+ // hook-routed provider has it. The inactivity PAUSE stays CLI-local — it is
537
+ // wired to this provider's timer trio via the _on*Permission* hooks below.
440
538
  this._resultTimeoutPaused = false
441
539
  }
442
540
 
@@ -465,11 +563,20 @@ export class CliSession extends BaseSession {
465
563
  * Start the persistent Claude process. Call once after construction.
466
564
  */
467
565
  start() {
566
+ // #7438: the session is running again by any route (first start, backoff
567
+ // respawn, model-switch respawn, restart-on-input), so the stop latch is
568
+ // spent. Cleared FIRST so a throw below cannot leave it armed.
569
+ this._stoppedByUser = false
570
+
468
571
  // Register permission hook before starting the process (only once, not on respawn)
469
572
  if (this._hookManager && this._respawnCount === 0) {
470
573
  this._hookManager.register()
471
574
  }
472
575
 
576
+ // #7337: must run BEFORE _spawnPersistentProcess, which is where
577
+ // _buildChildEnv() reads `_permissionModeFile` to point the child at it.
578
+ this._ensurePermissionModeSidecar()
579
+
473
580
  // Skills MVP (#2957) — append shared skills to the Claude CLI system prompt.
474
581
  const skillsText = this._buildSystemPrompt()
475
582
 
@@ -506,6 +613,19 @@ export class CliSession extends BaseSession {
506
613
  CLAUDE_HEADLESS: '1',
507
614
  CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING: '1',
508
615
  CHROXY_PERMISSION_MODE: this.permissionMode,
616
+ // #7337: the hook prefers this file and re-reads it on EVERY tool call,
617
+ // so a mid-session mode change reaches even the child already running.
618
+ // CHROXY_PERMISSION_MODE above stays as the fallback for a hook that
619
+ // cannot read the file (deleted /tmp entry, container without the mount).
620
+ //
621
+ // ALWAYS set, never omitted. buildSpawnEnv('claude') is DENYLIST mode, so
622
+ // the whole parent env passes through — and this daemon may itself have
623
+ // been launched from inside another chroxy session, whose sidecar path is
624
+ // then sitting in our env. Omitting the key would let that FOREIGN file
625
+ // decide this session's permissions, since the hook prefers it over our
626
+ // own CHROXY_PERMISSION_MODE. Empty string fails the hook's `[ -n ]` guard
627
+ // and falls through to the env var, which is the documented intent.
628
+ CHROXY_PERMISSION_MODE_FILE: this._permissionModeFile || '',
509
629
  ...(this._port ? { CHROXY_PORT: String(this._port) } : {}),
510
630
  // Pass a short-lived per-session secret instead of the primary API token.
511
631
  // This limits the blast radius if a tool reads process.env — the hook secret
@@ -518,6 +638,12 @@ export class CliSession extends BaseSession {
518
638
  _spawnPersistentProcess(args) {
519
639
  this._cleanupReadlines()
520
640
  this._processReady = false
641
+ // #8038: clear any refusal latched by a PRIOR spawn attempt at the very
642
+ // top of every attempt (mirrors ClaudeTuiSession._spawnPty). A fresh
643
+ // attempt gets a fresh gate verdict — a stale latch from a prior crash
644
+ // respawn must never suppress a NEW attempt's own error or silently
645
+ // survive a revival that is about to succeed.
646
+ this._spawnRefusal = null
521
647
 
522
648
  // #4929: capture which `--resume <id>` (if any) this spawn attempted.
523
649
  // Read off the argv we're about to pass instead of `_sessionId` so the
@@ -537,7 +663,38 @@ export class CliSession extends BaseSession {
537
663
  // for a directly-runnable `.exe` and on POSIX. See utils/win-spawn.js.
538
664
  // Captured so the spawn-time backstop (#6708) verifies the EXACT binary this
539
665
  // attempt used, not a fresh re-resolve that could land on a different path.
540
- const attemptedBinary = resolveClaudeBinary()
666
+ //
667
+ // #8038: routed through the shared binary gate instead of a bare
668
+ // `resolveClaudeBinary()` — this ONE method is what every (re)spawn funnels
669
+ // through (first start, `_killAndRespawn` for a model switch or permission-
670
+ // mode change, `_restartAfterStop`'s post-Stop revival, and `_scheduleRespawn`'s
671
+ // crash backoff), so gating it here covers every entry point in the #8038
672
+ // issue with no per-caller duplication. A refusal here means the gate
673
+ // rejected this attempt (provenance mismatch, quarantine, a vanished pinned
674
+ // path, …): nothing is spawned, the backoff chain resets (the NEXT spawn is
675
+ // user-initiated, mirroring `_killAndRespawn` zeroing `_respawnCount`), and
676
+ // `_scheduleRespawn` is deliberately NOT called — this is not "the child
677
+ // died", it is "we refused to start a child at all", and a timer retrying
678
+ // the same refused gate would just burn the bounded respawn budget into a
679
+ // misleading `respawn_exhausted` ("failed to stay alive"). Revival happens
680
+ // lazily on the next `sendMessage` instead (see there, and `_refuseSpawn`).
681
+ let attemptedBinary
682
+ try {
683
+ attemptedBinary = this._gatedSpawnBinary('claude')
684
+ } catch (err) {
685
+ // The chain that got us here (crash backoff, model switch, …) is over —
686
+ // the next spawn attempt is a fresh, user-initiated one, exactly as
687
+ // `_killAndRespawn` already resets this counter on its own respawn path.
688
+ //
689
+ // On the FIRST start this is only a race (create-time preflight passed
690
+ // moments earlier), and it latches rather than throwing like every other
691
+ // attempt. SessionManager has not broadcast `session_created` yet, so a
692
+ // client can miss this error: the session is listed but never ready,
693
+ // and its first input re-runs the gate and is rejected with the code.
694
+ this._respawnCount = 0
695
+ this._refuseSpawn(err, this._log || log)
696
+ return
697
+ }
541
698
  const spawnSpec = prepareSpawn(attemptedBinary, args)
542
699
  const child = spawn(spawnSpec.command, spawnSpec.args, {
543
700
  cwd: this.cwd,
@@ -548,6 +705,18 @@ export class CliSession extends BaseSession {
548
705
 
549
706
  this._child = child
550
707
 
708
+ // A returned ChildProcess is not ready proof: missing or non-executable
709
+ // binaries report ENOENT/EACCES asynchronously. Only expose readiness and
710
+ // drain startup input after Node confirms the child `spawn` event. Ignore
711
+ // a late event from a child that was replaced during a restart.
712
+ child.once('spawn', () => {
713
+ if (this._destroying || this._child !== child) return
714
+ this._processReady = true
715
+ log.info('Process started, ready for messages')
716
+ this.emit('ready', { sessionId: null, model: this.model, tools: [] })
717
+ this._drainPendingQueue()
718
+ })
719
+
551
720
  // Do NOT close stdin — we write messages to it
552
721
 
553
722
  // Read stdout line by line — each line is a JSON object
@@ -593,6 +762,7 @@ export class CliSession extends BaseSession {
593
762
  })
594
763
 
595
764
  child.on('error', (err) => {
765
+ if (this._child !== child) return
596
766
  this._cleanupReadlines()
597
767
  this._processReady = false
598
768
  this._child = null
@@ -605,20 +775,40 @@ export class CliSession extends BaseSession {
605
775
  this._scheduleRespawn()
606
776
  })
607
777
 
608
- child.on('close', (code) => this._handleChildClose(code))
778
+ child.on('close', (code) => {
779
+ if (this._child !== child) return
780
+ this._handleChildClose(code)
781
+ })
782
+ }
609
783
 
610
- // stdin is writable immediately — process is ready for NDJSON messages.
611
- // system.init arrives with the first response, not at startup.
612
- this._processReady = true
613
- log.info('Process started, ready for messages')
614
- this.emit('ready', { sessionId: null, model: this.model, tools: [] })
784
+ /**
785
+ * Warmup drain: dequeue the next pending message if not already busy.
786
+ * sendMessage() sets _isBusy, so the loop sends at most one message.
787
+ * Remaining items stay in the queue and are drained one-by-one via
788
+ * _clearMessageState() after each result.
789
+ *
790
+ * Called at the end of every _spawnPersistentProcess — i.e. this is what
791
+ * delivers a message queued while the process was down, whether it went down
792
+ * for a crash, a model switch, or a user Stop (#7438).
793
+ */
794
+ /**
795
+ * A startup-queued message is dispatched only while the connection that sent it
796
+ * is still authorized; otherwise it is dropped and reported as not dispatched.
797
+ */
798
+ _admitPendingItem(pending) {
799
+ if (stillAuthorized(pending?.options?.isAuthorized)) return true
800
+ reportInputAdmission(pending?.options, {
801
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: false,
802
+ reason: 'connection_not_authorized',
803
+ message: 'The sending connection is no longer authorized; the input was not dispatched.',
804
+ })
805
+ return false
806
+ }
615
807
 
616
- // Dequeue the next pending message if not already busy.
617
- // sendMessage() sets _isBusy, so the loop sends at most one message.
618
- // Remaining items stay in the queue and are drained one-by-one via
619
- // _clearMessageState() after each result.
808
+ _drainPendingQueue() {
620
809
  while (this._pendingQueue.length > 0 && !this._isBusy) {
621
810
  const pending = this._pendingQueue.shift()
811
+ if (!this._admitPendingItem(pending)) continue
622
812
  // #4828: session-scoped when init has fired (dequeue can race with
623
813
  // the very-first init so the fallback is intentional).
624
814
  ;(this._log || log).info(`Dequeuing pending message (${this._pendingQueue.length} remaining)`)
@@ -673,6 +863,69 @@ export class CliSession extends BaseSession {
673
863
  }, delay)
674
864
  }
675
865
 
866
+ /**
867
+ * #8301: a daemon wake is handed to a session that is READY, or not at all.
868
+ *
869
+ * `sendMessage` on a process that is not ready either respawns it
870
+ * (`_restartAfterStop()`, right for typed input, wrong for a wake) or parks the
871
+ * message in `_pendingQueue`. That queue is drained by `sendMessage` directly
872
+ * from three places (the warmup drain, the post-result drain, and
873
+ * DockerSession's start), none of which consults `admitAtFlush`, so a wake
874
+ * parked there would reach the child after a budget pause or a user Stop had
875
+ * been decided. The only way to keep the flush-time check meaningful is to
876
+ * never let a wake in: any not-ready state refuses. A wake that finds the
877
+ * session still starting is simply dropped; CI completion is not replayed, and
878
+ * the user was notified.
879
+ *
880
+ * `'stopped'` is kept for the two latches because it is the more useful
881
+ * answer (the user, or the binary gate, did this); everything else is
882
+ * `'not-ready'` (pre-init, mid-respawn, crashed).
883
+ *
884
+ * @returns {string|null}
885
+ */
886
+ daemonTurnRefusal() {
887
+ if (this._processReady) return null
888
+ return (this._stoppedByUser || this._spawnRefusal) ? 'stopped' : 'not-ready'
889
+ }
890
+
891
+ /**
892
+ * #8301: a queued daemon item was refused at flush. The base hook just keeps
893
+ * draining `_outgoingQueue`; CliSession has a SECOND queue behind it, and the
894
+ * refused item's slot must not strand it. `_clearMessageState` hands the turn
895
+ * to `_outgoingQueue` first and to `_pendingQueue` only when the former is
896
+ * empty, so a refusal that empties the former has to fall through to the
897
+ * latter exactly as `_clearMessageState` would have.
898
+ */
899
+ _continueDrainAfterRefusal() {
900
+ if (this._destroying) return
901
+ if (this._outgoingQueue.length > 0) {
902
+ this.dequeueNextOutgoing()
903
+ } else {
904
+ this._drainNextPendingAfterResult()
905
+ }
906
+ }
907
+
908
+ /**
909
+ * Dispatch the next message parked while the child was not ready, on the next
910
+ * tick (so synchronous `result` listeners finish first). Shared by the
911
+ * post-result drain in `_clearMessageState` and `_continueDrainAfterRefusal`.
912
+ */
913
+ _drainNextPendingAfterResult() {
914
+ if (!this._processReady || this._pendingQueue.length === 0) return
915
+ process.nextTick(() => {
916
+ if (this._destroying) return
917
+ if (!this._processReady || this._pendingQueue.length === 0) return
918
+ const pending = this._pendingQueue.shift()
919
+ if (!this._admitPendingItem(pending)) {
920
+ this._drainNextPendingAfterResult()
921
+ return
922
+ }
923
+ // #4828: session-scoped (post-result, post-init).
924
+ ;(this._log || log).info(`Dequeuing next pending message after result (${this._pendingQueue.length} remaining)`)
925
+ this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
926
+ })
927
+ }
928
+
676
929
  /**
677
930
  * Send a message to Claude via stdin NDJSON.
678
931
  */
@@ -683,19 +936,53 @@ export class CliSession extends BaseSession {
683
936
  // processing a message" — flushed FIFO on the turn-complete `result` (via
684
937
  // _clearMessageState's drain below). Matches the SDK's behaviour. The
685
938
  // overflow cap + the message_queued mirror live in enqueueOutgoingMessage.
686
- this.enqueueOutgoingMessage({ prompt, attachments, sendOptions: options })
939
+ const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions: options })
940
+ reportInputAdmission(options, queued
941
+ ? { status: 'queued', delivery: 'queued' }
942
+ : {
943
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
944
+ reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
945
+ })
687
946
  return
688
947
  }
689
948
 
690
949
  if (!this._processReady) {
950
+ // #8038: revive FIRST, before deciding whether THIS input can be
951
+ // admitted. `_restartAfterStop` now also fires on a latched spawn
952
+ // refusal (see its doc) so a session left idle by a gate refusal gets
953
+ // the same lazy on-next-input revival a user Stop already got via
954
+ // #7438 — moved ahead of the queue-full check / push below. It used to
955
+ // run AFTER queuing, which is fine when the restart spawns a child (the
956
+ // warmup drain delivers the push), but with a gate that can refuse it
957
+ // would admit this input as `queued` behind a child that never starts.
958
+ this._restartAfterStop()
959
+
960
+ // #8038: the revival attempt above may have hit the SAME gate refusal
961
+ // again (or a fresh one) — reject THIS input immediately with the coded
962
+ // admission instead of queuing it behind a child that is not coming
963
+ // back on its own. Messages already sitting in `_pendingQueue` from
964
+ // BEFORE this refusal are untouched (their admission was already
965
+ // reported as `queued`, and `onInputAdmission` is final after its first
966
+ // call) — they stay queued and are delivered FIFO by the warmup drain
967
+ // once a future revival actually spawns.
968
+ if (this._spawnRefusal) {
969
+ reportInputAdmission(options, spawnRefusalAdmission(this._spawnRefusal))
970
+ return
971
+ }
972
+
691
973
  if (this._pendingQueue.length >= 3) {
692
974
  this.emit('error', { message: 'Pending message queue full (max 3) — message discarded' })
975
+ reportInputAdmission(options, {
976
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
977
+ reason: 'queue_full', message: 'The provider startup queue is full; retry after the session becomes ready.',
978
+ })
693
979
  return
694
980
  }
695
981
  // #4828: session-scoped when init has fired (queuing typically happens
696
982
  // pre-init or during respawn — both can race with the binding).
697
983
  ;(this._log || log).info(`Process not ready, queuing message (queue depth: ${this._pendingQueue.length + 1})`)
698
984
  this._pendingQueue.push({ prompt, attachments, options })
985
+ reportInputAdmission(options, { status: 'queued', delivery: 'queued' })
699
986
  return
700
987
  }
701
988
 
@@ -737,6 +1024,8 @@ export class CliSession extends BaseSession {
737
1024
  }
738
1025
 
739
1026
  this._isBusy = true
1027
+ // #7376: a turn starts with no Stop requested, whatever the last one did.
1028
+ this._stopRequestedThisTurn = false
740
1029
  this._messageCounter++
741
1030
  // `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
742
1031
  // the boot-unique prefix is needed (#3700). Format change does not
@@ -766,9 +1055,15 @@ export class CliSession extends BaseSession {
766
1055
  ;(this._log || log).error(`stdin.write failed (sendMessage): ${err.message}`)
767
1056
  this._clearMessageState()
768
1057
  this.emit('error', { message: `Failed to send message: ${err.message}` })
1058
+ reportInputAdmission(options, {
1059
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1060
+ reason: 'write_failed', message: 'The provider input channel rejected the write.',
1061
+ })
769
1062
  return
770
1063
  }
771
1064
 
1065
+ reportInputAdmission(options, { status: 'accepted', delivery: 'dispatch_started' })
1066
+
772
1067
  // Skills text is committed to the wire — safe to flip the flag now (#3225).
773
1068
  // If the write threw above we returned early, leaving the flag false so
774
1069
  // the next attempt re-injects the prepend bucket.
@@ -865,19 +1160,63 @@ export class CliSession extends BaseSession {
865
1160
  const friendly = formatIdleDuration(this._hardTimeoutMs)
866
1161
  // #4828: session-scoped (hard-cap fires from active turn).
867
1162
  ;(this._log || log).warn(`Hard-cap timeout (${friendly}) — force-clearing busy state`)
868
- // Fire permission_expired for every pending permission we know about
869
- // so the client clears the stale prompt.
870
- for (const requestId of this._pendingPermissionIds) {
871
- this.emit('permission_expired', {
872
- requestId,
873
- message: 'Permission request expired (session timeout)',
874
- })
875
- }
876
- this._pendingPermissionIds.clear()
877
- this._emitInterruptedTurnResult(this._hardTimeoutMs)
1163
+ this._expirePendingPermissions('Permission request expired (session timeout)')
1164
+ this._emitInterruptedTurnResult(this._hardTimeoutMs, 'hard_timeout')
878
1165
  this.emit('error', { message: `Response timed out after ${friendly}` })
879
1166
  }
880
1167
 
1168
+ /**
1169
+ * Emit `permission_expired` for every prompt this session is still blocked
1170
+ * on, then drop the bookkeeping (#2831, extended by #7335).
1171
+ *
1172
+ * A prompt outlives its turn on BOTH sides and neither side says so:
1173
+ * client-side the card stays live until its own 5-minute `expiresAt`, and
1174
+ * server-side the daemon's HTTP handler tears the pending entry down on the
1175
+ * hook's `req 'aborted'` / `res 'close'` without broadcasting anything. So a
1176
+ * user who clicks Allow afterwards gets the "stale/unknown toolUseId …
1177
+ * already resolved" path with nothing explaining which decision died.
1178
+ *
1179
+ * The dashboard's `permission_expired` handler appends the expiry note AND
1180
+ * clears the prompt's `options`, which is what actually retires the dead
1181
+ * Allow button — so emitting here is the whole client-side fix.
1182
+ *
1183
+ * Wired at three sites, and the third is the one that matters:
1184
+ *
1185
+ * - `_clearMessageState` — the FUNNEL. Every turn end reaches it: the
1186
+ * normal `result`, the hard cap, the interrupt safety timeout,
1187
+ * `destroy()`. It is also where the ids used to be dropped silently.
1188
+ * - `_killAndRespawn` — the #3729 panic-button, the auto-mode switch,
1189
+ * mid-turn setModel. Needs its OWN call because it reaches the funnel via
1190
+ * `_emitInterruptedTurnResult`, which early-returns when the session is
1191
+ * not busy.
1192
+ * - `_handleChildClose` — a crash, or user Stop where the child dies. Same
1193
+ * early-return caveat.
1194
+ *
1195
+ * An earlier draft wired only the two death sites and justified skipping the
1196
+ * rest in a table. Review found the table wrong twice over: the interrupt
1197
+ * safety timeout was excused as "the child ignored SIGINT so the prompt is
1198
+ * still answerable", which this file contradicts eleven hundred lines below
1199
+ * (`claude only aborts the current turn` — the hook dies with the turn), and
1200
+ * that path then wiped the ids anyway via `_clearMessageState`, so no later
1201
+ * close could expire them. The plain `result` path was not in the table at
1202
+ * all. Enumerating callers by hand is what produced both errors; wiring the
1203
+ * funnel is what fixes them.
1204
+ *
1205
+ * `_handleStreamStall` is genuinely unreachable with a permission pending —
1206
+ * `notifyPermissionPending` clears the stall timer and `_armResultTimeout`
1207
+ * bails on `_resultTimeoutPaused` — and it routes through the funnel anyway.
1208
+ *
1209
+ * NOT a full solution on its own: this retires the prompt in the CLIENTS. The
1210
+ * daemon's own `pendingPermissions` entry (ws-permissions.js) is still
1211
+ * released explicitly rather than by relying on the hook dying: since #7606
1212
+ * POSIX `killProcessTree` does signal the hook's `bash` → `curl` grandchildren
1213
+ * on a respawn/destroy, but a crash runs no kill at all, and an explicit
1214
+ * release is the only path that covers both. See #7379.
1215
+ *
1216
+ * @param {string} message Reason forwarded on the wire (clients log it; the
1217
+ * user-visible copy is fixed client-side).
1218
+ */
1219
+
881
1220
  // #4467: stream-stall recovery. Fires when the child has been silent
882
1221
  // for `_streamStallTimeoutMs` despite the session being busy — typically
883
1222
  // a half-open TCP to the Anthropic API that the OS hasn't surfaced yet.
@@ -891,7 +1230,7 @@ export class CliSession extends BaseSession {
891
1230
  ;(this._log || log).warn(
892
1231
  `Stream stalled (${friendly}, messageId=${this._currentMessageId}) — clearing busy state for retry`,
893
1232
  )
894
- this._emitInterruptedTurnResult(this._streamStallTimeoutMs)
1233
+ this._emitInterruptedTurnResult(this._streamStallTimeoutMs, 'stream_stall')
895
1234
  this.emit('error', {
896
1235
  code: 'stream_stall',
897
1236
  message: `Stream stalled — no response for ${friendly}. Try sending again.`,
@@ -905,46 +1244,52 @@ export class CliSession extends BaseSession {
905
1244
  *
906
1245
  * @param {string} requestId
907
1246
  */
908
- notifyPermissionPending(requestId) {
909
- if (!requestId || this._pendingPermissionIds.has(requestId)) return
910
- this._pendingPermissionIds.add(requestId)
911
- if (this._pendingPermissionIds.size === 1) {
912
- this._resultTimeoutPaused = true
913
- // #3899: clear BOTH the soft warning and hard cap. Awaiting user
914
- // input is not inactivity; the timer trio re-arms together when
915
- // the last pending permission resolves.
916
- if (this._resultTimeout) {
917
- clearTimeout(this._resultTimeout)
918
- this._resultTimeout = null
919
- }
920
- if (this._hardTimeout) {
921
- clearTimeout(this._hardTimeout)
922
- this._hardTimeout = null
923
- }
924
- // #4467: clear the stall timer too — waiting on the user is not a stall.
925
- if (this._streamStallTimeout) {
926
- clearTimeout(this._streamStallTimeout)
927
- this._streamStallTimeout = null
928
- }
1247
+ /**
1248
+ * #7382: the generic add/remove bookkeeping is BaseSession's. These hooks are
1249
+ * the CLI-specific half — pausing the inactivity trio while the user is being
1250
+ * asked (#2831/#3899/#4467), which is not behaviour every provider shares.
1251
+ */
1252
+ _onFirstPermissionPending() {
1253
+ this._resultTimeoutPaused = true
1254
+ // #3899: clear BOTH the soft warning and the hard cap. Awaiting user input
1255
+ // is not inactivity; the trio re-arms together when the last pending
1256
+ // permission resolves. #4467: the stall timer too — waiting on the user is
1257
+ // not a stall.
1258
+ if (this._resultTimeout) {
1259
+ clearTimeout(this._resultTimeout)
1260
+ this._resultTimeout = null
1261
+ }
1262
+ if (this._hardTimeout) {
1263
+ clearTimeout(this._hardTimeout)
1264
+ this._hardTimeout = null
1265
+ }
1266
+ if (this._streamStallTimeout) {
1267
+ clearTimeout(this._streamStallTimeout)
1268
+ this._streamStallTimeout = null
1269
+ }
1270
+ }
1271
+
1272
+ /** Last prompt ANSWERED — the turn continues, so re-arm the trio. */
1273
+ _onLastPermissionResolved() {
1274
+ this._resultTimeoutPaused = false
1275
+ if (this._isBusy) {
1276
+ this._armResultTimeout()
929
1277
  }
930
1278
  }
931
1279
 
932
1280
  /**
933
- * Notify the session that a permission request has been resolved
934
- * (allow/deny/expired). When the last outstanding permission clears,
935
- * the inactivity timer re-arms for a fresh window. #2831.
1281
+ * Last prompt ABANDONED — the turn that raised it is over, so release the
1282
+ * pause but do NOT re-arm.
936
1283
  *
937
- * @param {string} requestId
1284
+ * #7375: releasing the flag is the load-bearing half. It and the id set are
1285
+ * one piece of bookkeeping, and `notifyPermissionResolved` only unsets the
1286
+ * flag for an id still IN the set — so taking the ids without releasing it
1287
+ * wedged the flag true on any path that does not reach `_clearMessageState`,
1288
+ * leaving the inactivity warning, the hard cap and the stall recovery dead
1289
+ * for the rest of the session.
938
1290
  */
939
- notifyPermissionResolved(requestId) {
940
- if (!requestId || !this._pendingPermissionIds.has(requestId)) return
941
- this._pendingPermissionIds.delete(requestId)
942
- if (this._pendingPermissionIds.size === 0) {
943
- this._resultTimeoutPaused = false
944
- if (this._isBusy) {
945
- this._armResultTimeout()
946
- }
947
- }
1291
+ _onPendingPermissionsAbandoned() {
1292
+ this._resultTimeoutPaused = false
948
1293
  }
949
1294
 
950
1295
  /**
@@ -1038,6 +1383,62 @@ export class CliSession extends BaseSession {
1038
1383
  compactMetadata: meta,
1039
1384
  timestamp: Date.now(),
1040
1385
  })
1386
+ } else if (data.subtype === 'task_started' || data.subtype === 'task_notification') {
1387
+ // #7340: the CLI's subagent lifecycle events. Until now these fell
1388
+ // into the generic branch below, which forwarded the literal string
1389
+ // "task_started" / "task_notification" to the client as a chat
1390
+ // bubble — noise in place of state.
1391
+ //
1392
+ // `task_started` is authoritative in two ways the tool_use block is
1393
+ // not: it carries `is_backgrounded` (the model's `run_in_background`
1394
+ // is a request; this is what the CLI actually did), and it identifies
1395
+ // subagents by `task_type` rather than by tool NAME, so tracking
1396
+ // survives a rename the way `Task` -> `Agent` was not survived.
1397
+ // `task_type: 'local_bash'` is a backgrounded shell — #4307's
1398
+ // surface, tracked separately, and never an agent.
1399
+ //
1400
+ // `task_notification` is the terminal signal. It is the ONLY thing
1401
+ // that clears a backgrounded agent now that the turn-end sweep no
1402
+ // longer does, so it is wired here rather than left to the sweep.
1403
+ // It fires for FAILED and STOPPED subagents too, not just completed
1404
+ // ones — every terminal status must clear the badge, or a subagent
1405
+ // that errored pins the session as working forever.
1406
+ if (data.subtype === 'task_started') {
1407
+ if (data.task_type === 'local_agent') {
1408
+ this._trackAgent({
1409
+ toolUseId: data.tool_use_id,
1410
+ description: typeof data.description === 'string' && data.description
1411
+ ? data.description
1412
+ : 'Background task',
1413
+ background: data.is_backgrounded === true,
1414
+ // #7340: authoritative -- the CLI's own account, so it
1415
+ // overwrites the model's request in BOTH directions. It is
1416
+ // also the evidence that this build emits task lifecycle
1417
+ // messages at all, which is what makes the turn-end exemption
1418
+ // safe: `task_notification` can arrive.
1419
+ authoritative: true,
1420
+ })
1421
+ }
1422
+ } else {
1423
+ this._completeAgent(data.tool_use_id)
1424
+ }
1425
+ } else if (data.subtype === 'status') {
1426
+ // #8153 (review nit): mirrors SdkSession's 'status' branch —
1427
+ // `SDKStatusMessage` carries no `message`/`text` field, just
1428
+ // `status: 'compacting' | 'requesting' | null`, so the generic
1429
+ // fallback below would otherwise forward the bare literal string
1430
+ // "status" as a chat bubble. `status: null` means the previous
1431
+ // status cleared — nothing new to show, so it's suppressed
1432
+ // entirely rather than emitted as an empty/placeholder bubble.
1433
+ const statusText = formatStatusContent(data.status)
1434
+ if (statusText) {
1435
+ this.emit('message', {
1436
+ type: 'system',
1437
+ subtype: 'status',
1438
+ content: statusText,
1439
+ timestamp: Date.now(),
1440
+ })
1441
+ }
1041
1442
  } else {
1042
1443
  // Forward non-init system events (e.g. usage limits, sub-agent
1043
1444
  // notifications) as system messages to the client
@@ -1062,6 +1463,14 @@ export class CliSession extends BaseSession {
1062
1463
  if (!messageId || !ctx) break
1063
1464
 
1064
1465
  switch (event.type) {
1466
+ case 'message_start': {
1467
+ // #7393: a new API message (the next round of a tool loop) restarts
1468
+ // block indexes at 0. A reasoning block the last message never closed
1469
+ // must not absorb this one's block 0.
1470
+ this._closeThinking(ctx)
1471
+ break
1472
+ }
1473
+
1065
1474
  case 'content_block_start': {
1066
1475
  const blockType = event.content_block?.type
1067
1476
  ctx.currentContentBlockType = blockType
@@ -1071,6 +1480,12 @@ export class CliSession extends BaseSession {
1071
1480
  ctx.hasStreamStarted = true
1072
1481
  this.emit('stream_start', { messageId })
1073
1482
  }
1483
+ } else if (blockType === 'thinking' || blockType === 'redacted_thinking') {
1484
+ // #7393: the model's reasoning. Open its stream now (the "it is
1485
+ // thinking" signal); the text is held until the block closes.
1486
+ const key = event.index ?? 0
1487
+ this._thinkingStreams(ctx, messageId).open(key)
1488
+ if (blockType === 'redacted_thinking') (ctx.redactedThinking ??= new Set()).add(key)
1074
1489
  } else if (blockType === 'tool_use') {
1075
1490
  ctx.currentToolName = event.content_block.name
1076
1491
  ctx.toolInputChunks = ''
@@ -1107,6 +1522,14 @@ export class CliSession extends BaseSession {
1107
1522
  }
1108
1523
  ctx.didStreamText = true
1109
1524
  this.emit('stream_delta', { messageId, delta: delta.text })
1525
+ } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
1526
+ // #7393: opening is idempotent, so a delta that beats its
1527
+ // content_block_start still lands in ONE stream. `signature_delta`
1528
+ // is not reasoning and falls through to nothing.
1529
+ const key = event.index ?? 0
1530
+ const streams = this._thinkingStreams(ctx, messageId)
1531
+ streams.open(key)
1532
+ streams.append(key, delta.thinking)
1110
1533
  } else if (delta.type === 'input_json_delta' && ctx.currentContentBlockType === 'tool_use') {
1111
1534
  if (typeof delta.partial_json === 'string' && !ctx.toolInputOverflow) {
1112
1535
  const chunkBytes = Buffer.byteLength(delta.partial_json, 'utf8')
@@ -1121,6 +1544,18 @@ export class CliSession extends BaseSession {
1121
1544
  } else {
1122
1545
  ctx.toolInputChunks += delta.partial_json
1123
1546
  ctx.toolInputBytes += chunkBytes
1547
+ // #8135 (review on #7346): do NOT forward this raw
1548
+ // chunk as a live `tool_input_delta` — a secret can
1549
+ // straddle chunk boundaries (e.g. "export TOKEN=sk-"
1550
+ // in one delta, "ant-api03-…" in the next), so a
1551
+ // per-chunk value can't be redacted safely, and
1552
+ // mid-stream partial JSON can't be parsed to run the
1553
+ // structured sanitizer over it either. The sanitized
1554
+ // FULL input is instead delivered as a single
1555
+ // `tool_input_delta` once the block finalizes — see
1556
+ // `_captureFinalizedToolInput` at `content_block_stop`,
1557
+ // a few ms later (execution, not this streaming
1558
+ // window, is the long part of a Bash call).
1124
1559
  }
1125
1560
  }
1126
1561
  }
@@ -1128,7 +1563,23 @@ export class CliSession extends BaseSession {
1128
1563
  }
1129
1564
 
1130
1565
  case 'content_block_stop': {
1566
+ if (ctx?.thinking) {
1567
+ // #7393: close the reasoning block this stop belongs to (a no-op
1568
+ // for any other block type).
1569
+ const key = event.index ?? 0
1570
+ ctx.thinking.close(key, { redacted: ctx.redactedThinking?.delete(key) === true })
1571
+ }
1131
1572
  if (ctx && ctx.currentToolName) {
1573
+ // #7346: backfill EVERY tool's finalized input (not just the
1574
+ // four special-cased by _applyToolInputSemantics below) so a
1575
+ // generic Bash/Read/etc. call's input rides out on its
1576
+ // tool_result instead of staying null forever — the actual
1577
+ // root cause of the "(no input)" bug, in flight AND after
1578
+ // completion/session-switch replay. Must run before
1579
+ // _applyToolInputSemantics only by convention (the two are
1580
+ // independent; ordering doesn't matter since neither mutates
1581
+ // ctx.toolInputChunks).
1582
+ this._captureFinalizedToolInput(ctx)
1132
1583
  this._applyToolInputSemantics(ctx)
1133
1584
  }
1134
1585
  if (ctx) {
@@ -1152,6 +1603,8 @@ export class CliSession extends BaseSession {
1152
1603
  const ctx = this._currentCtx
1153
1604
  const messageId = this._currentMessageId
1154
1605
  const content = data.message?.content
1606
+ this.emit('assistant_response', { responseId: data.message?.id ?? data.uuid, text: assistantResponseText(content) })
1607
+ if (ctx) ctx.assistantResponseSeen = true
1155
1608
  if (Array.isArray(content) && ctx && messageId) {
1156
1609
  // If stream_event deltas already drove streaming, skip assistant text
1157
1610
  if (ctx.didStreamText) {
@@ -1193,6 +1646,14 @@ export class CliSession extends BaseSession {
1193
1646
  const messageId = this._currentMessageId
1194
1647
  const ctx = this._currentCtx
1195
1648
 
1649
+ if (!ctx?.assistantResponseSeen && typeof data.result === 'string') {
1650
+ this.emit('assistant_response', { text: assistantResponseText(data.result) })
1651
+ }
1652
+
1653
+ // #7393: a turn can end under an open reasoning block; finalise it so the
1654
+ // client's "Thinking…" settles, before anything else this result emits.
1655
+ this._closeThinking(ctx)
1656
+
1196
1657
  // #5064 — Fallback for turns that complete without ever emitting
1197
1658
  // streamed assistant text. The canonical case is `/compact`: the
1198
1659
  // CLI returns the compaction summary in `data.result` but emits
@@ -1263,15 +1724,86 @@ export class CliSession extends BaseSession {
1263
1724
  numTurns: Number.isFinite(data.num_turns) ? data.num_turns : null,
1264
1725
  apiDurationMs: Number.isFinite(data.duration_api_ms) ? data.duration_api_ms : null,
1265
1726
  modelUsage: normalizeSdkModelUsage(data.modelUsage),
1727
+ // #7326: the CLI's result is the same message the SDK's is, so it
1728
+ // carries the same stop_reason / subtype / terminal_reason.
1729
+ declarationEligible: sdkDeclarationEligible(data),
1730
+ ...turnOutcomeField(outcomeFromSdkResult(data)),
1266
1731
  })
1267
1732
 
1268
- // Message complete — ready for next message
1269
- this._clearMessageState()
1733
+ // Message complete — ready for next message.
1734
+ // #7340: the CLI's own `result` message -- the child is alive and
1735
+ // reported the turn over itself, so a confirmed-backgrounded subagent
1736
+ // survives the sweep and clears later on `task_notification`. This and
1737
+ // SdkSession's `result` are the ONLY two sites that may pass this flag;
1738
+ // see the contract on `BaseSession._clearMessageState`.
1739
+ // #7376: `completion: 'normal'` -- the child's own `result` ended the
1740
+ // turn, so a Stop requested during it may have cut its tools off.
1741
+ this._clearMessageState({ turnEndedCleanly: true, completion: 'normal' })
1270
1742
  break
1271
1743
  }
1272
1744
  }
1273
1745
  }
1274
1746
 
1747
+ /**
1748
+ * #7346: backfill the finalized tool input onto `_inFlightToolStarts`
1749
+ * (base-session.js `_recordToolInput`, which sanitizes + size-caps it
1750
+ * — see #8135/#8136) so `tool-result.js`'s `emitToolResults` can
1751
+ * attach it to the matching `tool_result` via `_getTrackedToolInput`.
1752
+ * Runs for every tool (unlike `_applyToolInputSemantics`, which only
1753
+ * parses to drive four special-cased tools' session state) — the
1754
+ * #7346 root cause was that nothing captured the finalized input for
1755
+ * a generic Bash/Read/etc. call, so it stayed `null` forever: not
1756
+ * just in flight, but in the persisted `tool_start` history entry a
1757
+ * session-switch replay rebuilds from.
1758
+ *
1759
+ * #8135 (review): also delivers the SANITIZED full input as a
1760
+ * single-shot `tool_input_delta` right here, so the in-flight panel
1761
+ * lights up within milliseconds of the block finalizing — long
1762
+ * before the tool actually finishes executing (the #4341 client
1763
+ * fallback already renders whatever lands in `toolInputPartial`; one
1764
+ * complete-JSON chunk parses via `tryParseCompleteJson` exactly like
1765
+ * many partial ones would have). This REPLACES the raw per-chunk
1766
+ * `tool_input_delta` streaming `content_block_delta` used to do
1767
+ * (removed — see the comment there): a secret can straddle chunk
1768
+ * boundaries and mid-stream partial JSON can't be sanitized, so the
1769
+ * safe delivery point is "sanitize the complete parsed value, then
1770
+ * send it once."
1771
+ *
1772
+ * Best-effort and silent on failure: a JSON parse error (malformed
1773
+ * chunk) or an empty buffer (the overflow path already reset
1774
+ * `ctx.toolInputChunks` to `''` and told the user via the `error`
1775
+ * event emitted at accumulation time) simply skips both the backfill
1776
+ * and the delta — the tool_start entry's `input` stays `null` and the
1777
+ * client shows the "(input not received yet)" placeholder (#7346
1778
+ * direction 3) rather than a stale or fabricated value.
1779
+ *
1780
+ * @param {{ currentToolUseId: string|null, toolInputChunks: string }} ctx
1781
+ * @private
1782
+ */
1783
+ _captureFinalizedToolInput(ctx) {
1784
+ const toolUseId = ctx.currentToolUseId
1785
+ if (!toolUseId || !ctx.toolInputChunks) return
1786
+ let parsed
1787
+ try {
1788
+ parsed = JSON.parse(ctx.toolInputChunks)
1789
+ } catch {
1790
+ // Malformed/truncated JSON — nothing to backfill or deliver.
1791
+ return
1792
+ }
1793
+ const sanitized = this._recordToolInput(toolUseId, parsed)
1794
+ // `null`/`undefined` means "known to have no input" (or the parse
1795
+ // above legitimately produced one of those) — the placeholder logic
1796
+ // covers that case on its own; don't ship a literal "null" chunk.
1797
+ if (sanitized === null || sanitized === undefined) return
1798
+ const messageId = this._currentMessageId
1799
+ if (!messageId) return
1800
+ this.emit('tool_input_delta', {
1801
+ messageId,
1802
+ toolUseId,
1803
+ partialJson: JSON.stringify(sanitized),
1804
+ })
1805
+ }
1806
+
1275
1807
  /**
1276
1808
  * Apply session-state side effects for tools whose accumulated
1277
1809
  * `toolInputChunks` JSON drives plan-mode flags, agent tracking, or
@@ -1312,8 +1844,13 @@ export class CliSession extends BaseSession {
1312
1844
  ;(this._log || log).error(`Failed to parse AskUserQuestion input: ${err.message}`)
1313
1845
  return
1314
1846
  }
1315
- if (toolName === 'Task') {
1316
- ;(this._log || log).warn(`Failed to parse Task tool input: ${err.message}`)
1847
+ // #7340: `Agent` alongside `Task` here too. Control flow is identical
1848
+ // either way (both `return`), so only the diagnostic differed -- which
1849
+ // is exactly how a roster gets fixed in three places and missed in the
1850
+ // fourth. A subagent spawn whose input failed to parse would have been
1851
+ // logged as a generic tool under the current tool name.
1852
+ if (toolName === 'Task' || toolName === 'Agent') {
1853
+ ;(this._log || log).warn(`Failed to parse ${toolName} tool input: ${err.message}`)
1317
1854
  return
1318
1855
  }
1319
1856
  if (toolName === 'ExitPlanMode') {
@@ -1337,6 +1874,8 @@ export class CliSession extends BaseSession {
1337
1874
  // #4828: session-scoped.
1338
1875
  ;(this._log || log).info(`AskUserQuestion detected (${toolUseId})`)
1339
1876
  this._waitingForAnswer = true
1877
+ // #7457 -- co-located with the flag (see the constructor).
1878
+ this._pendingQuestion = { toolUseId, questions: semantics.payload.questions ?? [] }
1340
1879
  this.emit('user_question', {
1341
1880
  toolUseId,
1342
1881
  questions: semantics.payload.questions,
@@ -1345,13 +1884,19 @@ export class CliSession extends BaseSession {
1345
1884
  }
1346
1885
  case 'task': {
1347
1886
  if (!parseSucceeded) return
1348
- const agentInfo = {
1887
+ // #7340: this records the MODEL'S REQUEST (`run_in_background`) into
1888
+ // `background`. It does NOT exempt the agent from the turn-end sweep —
1889
+ // `backgroundConfirmed` does, and only the CLI's own `task_started` can
1890
+ // set that. Exempting on an unconfirmed request would strand an agent
1891
+ // on a build that emits no task lifecycle events, because the same
1892
+ // event is what proves a terminal `task_notification` can arrive.
1893
+ // `task_started` may correct this value in EITHER direction;
1894
+ // `_trackAgent` upgrades rather than re-emits, so either order is fine.
1895
+ this._trackAgent({
1349
1896
  toolUseId,
1350
1897
  description: semantics.payload.description,
1351
- startedAt: Date.now(),
1352
- }
1353
- this._activeAgents.set(toolUseId, agentInfo)
1354
- this.emit('agent_spawned', agentInfo)
1898
+ background: semantics.payload.background,
1899
+ })
1355
1900
  return
1356
1901
  }
1357
1902
  case 'enter_plan': {
@@ -1366,15 +1911,55 @@ export class CliSession extends BaseSession {
1366
1911
  }
1367
1912
  }
1368
1913
 
1914
+ /**
1915
+ * #7393 — the turn's reasoning streams, created on first use. Lives on the
1916
+ * per-turn `ctx` so it dies with the turn, and is built lazily so a ctx built
1917
+ * without it (tests, an older shape) still works.
1918
+ */
1919
+ _thinkingStreams(ctx, messageId) {
1920
+ return (ctx.thinking ??= new ThinkingStreams((event, data) => this.emit(event, data), messageId))
1921
+ }
1922
+
1923
+ /**
1924
+ * #7393 — finish every open reasoning block of `ctx` and forget which of them
1925
+ * were `redacted_thinking`. The two must go together: a redacted block that
1926
+ * never got its stop would otherwise leave its index in the set, and a later
1927
+ * plain block at that index would be shown as the redacted marker.
1928
+ */
1929
+ _closeThinking(ctx) {
1930
+ if (!ctx) return
1931
+ // A redacted block closes as the marker even when its stop never came.
1932
+ for (const key of ctx.redactedThinking ?? []) ctx.thinking?.close(key, { redacted: true })
1933
+ ctx.thinking?.closeAll()
1934
+ ctx.redactedThinking?.clear()
1935
+ }
1936
+
1369
1937
  /**
1370
1938
  * Clear per-message state, marking us as ready for the next message.
1371
1939
  * After clearing, drains the next item from _pendingQueue (if any) so
1372
1940
  * that all queued messages are eventually delivered in FIFO order.
1373
1941
  */
1374
- _clearMessageState() {
1375
- super._clearMessageState()
1942
+ // #7340: forward the opts to super. `turnEndedCleanly` decides whether a
1943
+ // confirmed-backgrounded subagent survives BaseSession's turn-end sweep;
1944
+ // an override that drops it silently disables the exemption.
1945
+ _clearMessageState(opts) {
1946
+ super._clearMessageState(opts)
1376
1947
  this._waitingForAnswer = false
1948
+ this._pendingQuestion = null // #7457 -- co-located with the flag.
1377
1949
  this._currentCtx = null
1950
+ // #7335: this is the ONE funnel every turn end passes through — the normal
1951
+ // `result`, the hard cap, the interrupt safety timeout, destroy() — and it
1952
+ // used to drop `_pendingPermissionIds` on the floor without telling anyone.
1953
+ // Expiring here rather than only at the individual death sites is the
1954
+ // difference between a guard wired to the callers someone remembered and
1955
+ // one wired to all of them (docs/false-safety-guards.md). Idempotent: a
1956
+ // no-op when the set is already empty, which it is on the paths that
1957
+ // expired explicitly moments earlier.
1958
+ // #7382: the expire itself moved to BaseSession._clearMessageState (called
1959
+ // by super above), so every provider inherits it rather than each wiring
1960
+ // its own. The explicit calls in _killAndRespawn / _handleChildClose stay:
1961
+ // both reach this funnel via _emitInterruptedTurnResult, which early-returns
1962
+ // when the session is not busy.
1378
1963
  // Reset permission pause bookkeeping — the next message starts fresh.
1379
1964
  this._pendingPermissionIds.clear()
1380
1965
  this._resultTimeoutPaused = false
@@ -1411,14 +1996,7 @@ export class CliSession extends BaseSession {
1411
1996
  if (this._outgoingQueue.length > 0) {
1412
1997
  this.dequeueNextOutgoing()
1413
1998
  } else if (this._pendingQueue.length > 0) {
1414
- process.nextTick(() => {
1415
- if (this._destroying) return
1416
- if (!this._processReady || this._pendingQueue.length === 0) return
1417
- const pending = this._pendingQueue.shift()
1418
- // #4828: session-scoped (post-result, post-init).
1419
- ;(this._log || log).info(`Dequeuing next pending message after result (${this._pendingQueue.length} remaining)`)
1420
- this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
1421
- })
1999
+ this._drainNextPendingAfterResult()
1422
2000
  }
1423
2001
  }
1424
2002
  }
@@ -1426,13 +2004,52 @@ export class CliSession extends BaseSession {
1426
2004
  /**
1427
2005
  * Kill the current child process (if any) and respawn.
1428
2006
  * Suppresses auto-respawn during the kill, clears timers, and starts fresh.
2007
+ *
2008
+ * @param {string} [terminatedReason] #7376: why the turn is being ended
2009
+ * (`permission_mode_switch` / `model_switch`). Passed in by each caller
2010
+ * rather than inferred -- this is shared by the panic-button and a mid-turn
2011
+ * model change -- and stamped onto the synthetic `tool_result` of every tool
2012
+ * the dying turn left in flight.
1429
2013
  */
1430
- _killAndRespawn() {
2014
+ _killAndRespawn(terminatedReason) {
2015
+ // #7335: retire the prompts the dying turn was blocked on BEFORE
2016
+ // _emitInterruptedTurnResult, which reaches _clearMessageState and wipes
2017
+ // `_pendingPermissionIds` silently. Ordering is the whole fix: after that
2018
+ // call there is nothing left to tell the client about, which is exactly
2019
+ // how the card ended up stranded live on screen with a dead Allow button.
2020
+ this._expirePendingPermissions('Permission request expired (the turn it belonged to was interrupted and the session restarted)')
2021
+
2022
+ // #7340: the child is about to be gone (or already is), and with it every
2023
+ // subagent it was running. `task_notification` -- the ONLY signal that
2024
+ // clears a confirmed-backgrounded agent now that the turn-end sweep spares
2025
+ // it -- can never arrive, so drain them here or the session claims to be
2026
+ // working for the rest of the daemon's life.
2027
+ //
2028
+ // Needs its OWN call for the same reason `_expirePendingPermissions` above
2029
+ // does (#7335): both reach the `_clearMessageState` funnel via
2030
+ // `_emitInterruptedTurnResult`, which early-returns when the session is not
2031
+ // busy -- and "not busy with a backgrounded agent still running" is the
2032
+ // exact state the exemption creates. Idempotent, and the funnel's own
2033
+ // unconditional sweep covers the busy case.
2034
+ this._completeAgents()
2035
+
2036
+ // #7611: the same child-is-going-away reasoning for background SHELLS.
2037
+ // `killProcessTree` below (since #7608) signals the child's whole descendant
2038
+ // tree, which includes the shells the agent started with
2039
+ // `run_in_background`, and nothing can poll or hear back from them after
2040
+ // this. Forget them here — before `_emitInterruptedTurnResult`, so a
2041
+ // listener of its `result` already sees the truthful `isRunning` — or the
2042
+ // tracker keeps the session 'running' (immune to the idle timeout) until the
2043
+ // 4 h hard-quiesce reap. NOT `_destroyPendingBackgroundShells`: that is the
2044
+ // end-of-session teardown and also drops the activity tree. A no-op for a
2045
+ // provider that tracks no shells.
2046
+ this._clearPendingBackgroundShells()
2047
+
1431
2048
  // #4471: emit synthetic terminating events BEFORE setting _respawning,
1432
2049
  // otherwise the _handleChildClose guard short-circuits and the dashboard
1433
2050
  // never receives `agent_idle` — Stop stays stuck on panic-button +
1434
2051
  // mid-turn setModel paths.
1435
- this._emitInterruptedTurnResult()
2052
+ this._emitInterruptedTurnResult(0, terminatedReason)
1436
2053
 
1437
2054
  this._respawning = true
1438
2055
  this._processReady = false
@@ -1533,7 +2150,8 @@ export class CliSession extends BaseSession {
1533
2150
  // shim wrapping a `.cmd` provider (claude/codex/…); the real node
1534
2151
  // grandchild is orphaned and the wrapper's `close` above then cancels the
1535
2152
  // forceKill escalation before it can fire. killProcessTree reaps the whole
1536
- // tree (POSIX behaviour is an identical graceful SIGTERM).
2153
+ // tree — since #7606 on POSIX too (graceful SIGTERM to every descendant,
2154
+ // enumerated before the child is signalled).
1537
2155
  killProcessTree(oldChild)
1538
2156
  } else {
1539
2157
  this._respawning = false
@@ -1564,18 +2182,181 @@ export class CliSession extends BaseSession {
1564
2182
  _onModelChanged() {
1565
2183
  // #4828: session-scoped if init has fired before the model change.
1566
2184
  ;(this._log || log).info(`Model changed to ${this.model || 'default'}, restarting process`)
1567
- this._killAndRespawn()
2185
+ this._killAndRespawn('model_switch')
2186
+ }
2187
+
2188
+ /**
2189
+ * Base dir for the per-session permission-mode sidecar dirs (#7337).
2190
+ * Exposed so the boot sweep and its tests name it once.
2191
+ */
2192
+ static get PERMISSION_MODE_SIDECAR_BASE() { return join(tmpdir(), 'chroxy-claude-cli') }
2193
+
2194
+ /**
2195
+ * #7337: boot-time sweep of sidecar dirs orphaned by a crash. destroy()
2196
+ * removes a session's own dir, but a SIGKILL leaks it, so a long-lived host
2197
+ * accumulates one per crashed session. Same ownership rule as the claude-tui
2198
+ * sink sweep and the same implementation — only dirs whose `owner.pid` is
2199
+ * DEAD are removed, so a live daemon's dirs (including this one's) are kept
2200
+ * and the sweep is safe to run unconditionally at boot.
2201
+ *
2202
+ * @param {object} [logger] - logger with info/warn (defaults to module log)
2203
+ * @returns {{swept:number, kept:number}}
2204
+ */
2205
+ static sweepStaleSidecarDirs(logger = log) {
2206
+ return sweepStaleOwnedDirs(CliSession.PERMISSION_MODE_SIDECAR_BASE, {
2207
+ logger,
2208
+ label: 'claude-cli permission-mode sidecar',
2209
+ })
2210
+ }
2211
+
2212
+ /**
2213
+ * #7337: create the re-readable permission-mode sidecar and seed it with the
2214
+ * session's current mode. Idempotent — a respawn calls start() again and must
2215
+ * keep the SAME path, because the sidecar the still-draining old child holds
2216
+ * in its env has to stay valid until that child is gone.
2217
+ *
2218
+ * Only meaningful when permissions are enabled: with no port there is no hook
2219
+ * endpoint, so `permission-hook.sh` never runs and the mode is moot. A failed
2220
+ * initial write leaves `_permissionModeFile` null and the session falls back
2221
+ * to env-var-only mode — losing the ability to hot-swap the mode is bad, but
2222
+ * failing session start over a /tmp write is worse (same trade ClaudeTuiSession
2223
+ * makes at #4013).
2224
+ */
2225
+ _ensurePermissionModeSidecar() {
2226
+ if (!this._port) return
2227
+ const mode = this.permissionMode || 'approve'
2228
+
2229
+ // Re-seed on EVERY start(), not only the first. The path is kept stable
2230
+ // across a respawn (a still-draining old child holds it in its env), but
2231
+ // the CONTENTS must be re-asserted, because the file outranks the env var
2232
+ // in the hook's resolution order. Without this, a mid-session write that
2233
+ // failed (ENOSPC / EROFS / EIO) left the sidecar holding the OLD mode while
2234
+ // the respawned child carried the NEW one in CHROXY_PERMISSION_MODE — and
2235
+ // the hook read the file. A tighten to `approve` would then keep
2236
+ // auto-allowing for the rest of the session while the daemon, the state
2237
+ // file and the UI all said `approve`. The respawn was documented as the
2238
+ // repair and was not one.
2239
+ if (this._permissionModeFile) {
2240
+ try {
2241
+ writePermissionModeSidecarAtomic(this._permissionModeFile, mode)
2242
+ return
2243
+ } catch (err) {
2244
+ // The existing file is now untrustworthy — and a stale file is WORSE
2245
+ // than none, because it outranks the correct env var. Drop it so the
2246
+ // hook falls back to CHROXY_PERMISSION_MODE, then try a fresh dir below.
2247
+ ;(this._log || log).warn(`permission-mode sidecar re-seed failed (${err.message}) — dropping the stale sidecar so the hook falls back to the env var`)
2248
+ this._cleanupPermissionModeSidecar()
2249
+ }
2250
+ }
2251
+
2252
+ let dir = null
2253
+ try {
2254
+ const base = ensureOwnedBaseDir(CliSession.PERMISSION_MODE_SIDECAR_BASE)
2255
+ dir = join(base, `s-${randomUUID()}`)
2256
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
2257
+ // Stamp the owning pid so the boot-time sweep can tell a live daemon's
2258
+ // dir from one orphaned by a crash. Best-effort: a missing pidfile just
2259
+ // makes the dir sweep-eligible after a grace window, which is the safe
2260
+ // default for an orphan.
2261
+ try { writeFileSync(join(dir, OWNER_PID_FILE), String(process.pid)) } catch { /* best effort */ }
2262
+ const path = join(dir, 'permission-mode')
2263
+ writePermissionModeSidecarAtomic(path, mode)
2264
+ this._permissionModeDir = dir
2265
+ this._permissionModeFile = path
2266
+ } catch (err) {
2267
+ // Remove the dir we just created, if we got that far — otherwise a
2268
+ // persistent write failure leaks one dir per respawn, and because
2269
+ // owner.pid names this LIVE daemon the boot sweep keeps every one of
2270
+ // them for the daemon's whole lifetime.
2271
+ if (dir) { try { rmSync(dir, { recursive: true, force: true }) } catch { /* best effort */ } }
2272
+ ;(this._log || log).warn(`permission-mode sidecar unavailable (${err.message}) — falling back to env-var-only mode; a mid-session permission switch will not reach the running process until it respawns`)
2273
+ this._permissionModeFile = null
2274
+ this._permissionModeDir = null
2275
+ }
2276
+ }
2277
+
2278
+ /** Remove the sidecar dir created by _ensurePermissionModeSidecar. */
2279
+ _cleanupPermissionModeSidecar() {
2280
+ if (this._permissionModeDir) {
2281
+ try { rmSync(this._permissionModeDir, { recursive: true, force: true }) }
2282
+ catch (err) { (this._log || log).warn(`permission-mode sidecar cleanup failed: ${err.message}`) }
2283
+ }
2284
+ this._permissionModeDir = null
2285
+ this._permissionModeFile = null
1568
2286
  }
1569
2287
 
1570
2288
  _onPermissionModeChanged(mode) {
2289
+ // #7337: publish to the sidecar FIRST. `permission-hook.sh` prefers the
2290
+ // file over CHROXY_PERMISSION_MODE and re-reads it on every tool call, so
2291
+ // this takes effect immediately — including for the child that is still
2292
+ // alive right now. Without it the only channel was the respawn below, which
2293
+ // does not land until the old child's `close` fires (up to the 10s
2294
+ // force-kill grace in _killAndRespawn), and every PreToolUse hook that old
2295
+ // child raises in the meantime resolves the STALE mode. That is #7337: a
2296
+ // Bash approval card on a session whose state file already read `"auto"`.
2297
+ if (this._permissionModeFile) {
2298
+ try {
2299
+ writePermissionModeSidecarAtomic(this._permissionModeFile, mode)
2300
+ } catch (err) {
2301
+ // Hook precedence is file -> env var, so a sidecar left holding the
2302
+ // PREVIOUS mode outranks the correct value in CHROXY_PERMISSION_MODE —
2303
+ // and on a TIGHTEN that is fail-open. Remove it rather than leave it:
2304
+ // the hook then falls back to the env var, and start()'s re-seed
2305
+ // rebuilds a fresh sidecar on the respawn below. Leaving it in place
2306
+ // pinned the old mode for the whole session.
2307
+ ;(this._log || log).warn(`failed to write permission-mode sidecar (${err.message}) — removing it so the hook falls back to the spawn env var until the respawn re-seeds`)
2308
+ this._cleanupPermissionModeSidecar()
2309
+ }
2310
+ }
2311
+
1571
2312
  // #3729 panic-button semantics: BaseSession.setPermissionMode lets `'auto'`
1572
2313
  // bypass the `_isBusy` guard, so flipping to auto mid-turn IS destructive —
1573
2314
  // the in-flight `claude -p` process is killed and respawned, dropping the
1574
2315
  // current turn. This is by design (parity with SDK auto-resolve of pending
1575
- // prompts); see #3735 for the regression test pinning this behavior.
2316
+ // prompts); see #3735 for the regression test pinning this behavior. The
2317
+ // respawn is still required for the OTHER mode channel: `--permission-mode
2318
+ // bypassPermissions` / `plan` is argv, not env, so only a new process picks
2319
+ // it up (buildClaudeCliArgs). The sidecar covers the hook; the respawn
2320
+ // covers claude's own flag.
1576
2321
  // #4828: session-scoped if init has fired.
1577
2322
  ;(this._log || log).info(`Permission mode changed to ${mode}, restarting process`)
1578
- this._killAndRespawn()
2323
+ this._killAndRespawn('permission_mode_switch')
2324
+ }
2325
+
2326
+ getRestartBlockers() {
2327
+ const reasons = super.getRestartBlockers()
2328
+ // Messages acknowledged as `queued` while the CLI child warms up or
2329
+ // respawns live here, NOT in `_outgoingQueue` (see sendMessage's
2330
+ // `!_processReady` branch) — a restart would drop them (#8324).
2331
+ const pending = this._pendingQueue.length
2332
+ if (pending > 0) reasons.push(`${pending} message(s) queued while the CLI is not ready`)
2333
+ return reasons
2334
+ }
2335
+
2336
+ /**
2337
+ * #7457 -- the AskUserQuestion this child is parked on stdin for, if any.
2338
+ *
2339
+ * A read-through of `_pendingQuestion`, which is written and cleared in the
2340
+ * same statement block as `_waitingForAnswer` at every one of that flag's
2341
+ * four sites -- construction, the emit, the `_clearMessageState` turn-end
2342
+ * funnel ("the ONE funnel every turn end passes through": normal `result`,
2343
+ * hard cap, interrupt safety timeout, destroy) and `respondToQuestion`. So it
2344
+ * cannot report a question the child has stopped waiting on.
2345
+ *
2346
+ * It reads `_pendingQuestion` ALONE and does not re-check `_waitingForAnswer`.
2347
+ * The two are set and cleared together, so the extra clause could never
2348
+ * change an answer -- and it would make every one of those null-outs
2349
+ * unfalsifiable, since the flag would mask a leaked payload
2350
+ * (docs/false-safety-guards.md: a guard whose only two states are green).
2351
+ * `tests/pending-question-resend.test.js` asserts the co-location mechanically
2352
+ * rather than trusting this paragraph.
2353
+ *
2354
+ * @returns {{ toolUseId: string, questions: object[] }[]}
2355
+ */
2356
+ getPendingQuestions() {
2357
+ const pending = this._pendingQuestion
2358
+ if (!pending) return []
2359
+ return [{ toolUseId: pending.toolUseId, questions: pending.questions }]
1579
2360
  }
1580
2361
 
1581
2362
  /**
@@ -1586,6 +2367,7 @@ export class CliSession extends BaseSession {
1586
2367
  respondToQuestion(text) {
1587
2368
  if (!this._child || !this._waitingForAnswer) return
1588
2369
  this._waitingForAnswer = false
2370
+ this._pendingQuestion = null // #7457 -- co-located with the flag.
1589
2371
  const ndjson = JSON.stringify({
1590
2372
  type: 'user',
1591
2373
  message: {
@@ -1606,15 +2388,22 @@ export class CliSession extends BaseSession {
1606
2388
  // the dashboard's streamingMessageId/isIdle. Without it, an interrupted
1607
2389
  // turn leaves Stop stuck visible and "Thinking…" permanent.
1608
2390
  // Mirrors TUI #4010. cost:null skips session-manager billing.
1609
- _emitInterruptedTurnResult(duration = 0) {
2391
+ //
2392
+ // #7376: `terminatedReason` says WHY, so the tools this turn left in flight
2393
+ // are reported as "the turn was terminated under it" rather than as failed
2394
+ // commands. Supplied by each caller -- this is shared by the panic-button,
2395
+ // mid-turn setModel, Stop, a crash and both watchdogs -- and never inferred.
2396
+ _emitInterruptedTurnResult(duration = 0, terminatedReason) {
1610
2397
  if (!this._isBusy || !this._currentMessageId) return
1611
2398
  const messageId = this._currentMessageId
1612
2399
  const sessionId = this._sessionId
2400
+ this._closeThinking(this._currentCtx) // #7393
1613
2401
  if (this._currentCtx?.hasStreamStarted) {
1614
2402
  this.emit('stream_end', { messageId })
1615
2403
  }
1616
- this._clearMessageState()
1617
- this.emit('result', { cost: null, duration, usage: null, sessionId })
2404
+ this._clearMessageState({ terminatedReason })
2405
+ // #7072: terminal but not a completed turn (internal; not on the wire).
2406
+ this.emit('result', { cost: null, duration, usage: null, sessionId, interrupted: true })
1618
2407
  }
1619
2408
 
1620
2409
  _handleChildClose(code) {
@@ -1643,7 +2432,34 @@ export class CliSession extends BaseSession {
1643
2432
  if (this._destroying) return
1644
2433
  if (this._respawning) return
1645
2434
 
1646
- this._emitInterruptedTurnResult()
2435
+ // #7335: the child is gone, so every PreToolUse hook it had blocked on
2436
+ // died with it and its prompt can never be answered — same stranded card
2437
+ // as the respawn path, reached a different way. This covers a crash AND a
2438
+ // user Stop (interrupt() → SIGINT → the child exits here, NOT through
2439
+ // _killAndRespawn). Before _emitInterruptedTurnResult for the same reason:
2440
+ // that call reaches _clearMessageState, which drops the ids silently.
2441
+ //
2442
+ // The respawn path already expired them and set `_respawning`, so the
2443
+ // close it causes returns above — no double emit; pinned by a test.
2444
+ this._expirePendingPermissions('Permission request expired (the session process exited before it could be answered)')
2445
+
2446
+ // #7340: the child is about to be gone (or already is), and with it every
2447
+ // subagent it was running. `task_notification` -- the ONLY signal that
2448
+ // clears a confirmed-backgrounded agent now that the turn-end sweep spares
2449
+ // it -- can never arrive, so drain them here or the session claims to be
2450
+ // working for the rest of the daemon's life.
2451
+ //
2452
+ // Needs its OWN call for the same reason `_expirePendingPermissions` above
2453
+ // does (#7335): both reach the `_clearMessageState` funnel via
2454
+ // `_emitInterruptedTurnResult`, which early-returns when the session is not
2455
+ // busy -- and "not busy with a backgrounded agent still running" is the
2456
+ // exact state the exemption creates. Idempotent, and the funnel's own
2457
+ // unconditional sweep covers the busy case.
2458
+ this._completeAgents()
2459
+
2460
+ // #7376: Stop (SIGINT -> the child exits here) and a crash both reach this
2461
+ // point; the tools they leave in flight are worded differently.
2462
+ this._emitInterruptedTurnResult(0, wasIntentionalStop ? 'user_stop' : 'process_exit')
1647
2463
 
1648
2464
  // #4602: user-initiated Stop sent SIGINT via interrupt(). The child
1649
2465
  // exited cleanly as a result — do NOT show "exited unexpectedly" and
@@ -1651,6 +2467,12 @@ export class CliSession extends BaseSession {
1651
2467
  if (wasIntentionalStop) {
1652
2468
  // #4828: session-scoped if init had fired before the stop.
1653
2469
  ;(this._log || log).info(`Process exited (code ${code}) after user stop`)
2470
+ // #7438: NOT a respawn — the user asked for this child to stop and it
2471
+ // stays stopped. This only records that the session is stoppable-but-
2472
+ // revivable, so the next sendMessage can bring it back (see
2473
+ // _restartAfterStop). Stop halts the turn; it must not end the session's
2474
+ // ability to answer the follow-up.
2475
+ this._stoppedByUser = true
1654
2476
  this.emit('stopped', { code })
1655
2477
  return
1656
2478
  }
@@ -1750,12 +2572,122 @@ export class CliSession extends BaseSession {
1750
2572
  return
1751
2573
  }
1752
2574
 
2575
+ // #7599: give a containerized subclass a chance to classify this exit as a
2576
+ // vanished container (a distinct, non-respawnable-but-recoverable state)
2577
+ // BEFORE the generic crash→respawn path. Reached only for a genuine
2578
+ // unexpected exit — the intentional-stop and resume-unknown branches above
2579
+ // have already returned. Base returns false synchronously (no behavior
2580
+ // change for host sessions); DockerSession returns a Promise that PROBES the
2581
+ // container, so the generic respawn is DEFERRED until the probe resolves and
2582
+ // skipped entirely on a confirmed vanish.
2583
+ const maybeVanish = this._handleContainerGoneOnClose(code)
2584
+ if (maybeVanish && typeof maybeVanish.then === 'function') {
2585
+ maybeVanish.then((handled) => {
2586
+ if (!handled && !this._destroying) this._respawnAfterUnexpectedClose(code)
2587
+ })
2588
+ return
2589
+ }
2590
+ if (maybeVanish) return
2591
+ this._respawnAfterUnexpectedClose(code)
2592
+ }
2593
+
2594
+ /**
2595
+ * #7599 — hook for a containerized subclass to intercept a child-close it can
2596
+ * attribute to its container vanishing, before the generic respawn. The base
2597
+ * host-CLI session has no container, so it never intercepts (returns false
2598
+ * synchronously — the generic respawn then runs inline as before).
2599
+ *
2600
+ * @param {number} _code exit code of the closed child
2601
+ * @returns {boolean|Promise<boolean>} true to suppress the generic crash→respawn
2602
+ */
2603
+ _handleContainerGoneOnClose(_code) {
2604
+ return false
2605
+ }
2606
+
2607
+ /** #7599 — the generic "exited unexpectedly → restart" tail, extracted so the
2608
+ * container-vanish hook can defer or skip it. */
2609
+ _respawnAfterUnexpectedClose(code) {
1753
2610
  // #4828: session-scoped if init had fired.
1754
2611
  ;(this._log || log).info(`Process exited (code ${code}), scheduling respawn`)
1755
2612
  this.emit('error', { message: 'Claude process exited unexpectedly, restarting...' })
1756
2613
  this._scheduleRespawn()
1757
2614
  }
1758
2615
 
2616
+ /**
2617
+ * #7438 — restart-on-next-input for a session the user Stopped.
2618
+ *
2619
+ * Stop (interrupt → SIGINT → child exits) deliberately does NOT respawn
2620
+ * (#4602): respawning at stop time fights the thing the user just asked for.
2621
+ * But nothing else restarted the child either, so the next sendMessage hit
2622
+ * the `!_processReady` branch, pushed into `_pendingQueue` — and stranded
2623
+ * there forever, because the queue only drains on a start() warmup or after a
2624
+ * `result`, and with no child neither can ever fire. The follow-up was
2625
+ * silently eaten and the 4th one discarded outright ("queue full"). Stop
2626
+ * ended the conversation instead of interrupting a turn.
2627
+ *
2628
+ * So the respawn is lazy: it happens here, when the user actually asks for
2629
+ * more work. start() passes `--resume this._sessionId`, so the new child
2630
+ * re-attaches to the SAME claude conversation rather than starting cold, and
2631
+ * its warmup drain delivers the queued message.
2632
+ *
2633
+ * Gated on `_stoppedByUser` rather than on the broader "there is no child",
2634
+ * deliberately: every OTHER way to lose a child either already owns its own
2635
+ * restart (a crash schedules a backoff respawn; a model switch runs
2636
+ * _killAndRespawn) or is a considered terminal give-up — the respawn cap, the
2637
+ * rate cap, `resume_unknown_exhausted`. Typing into one of those must not
2638
+ * re-arm a flapping session behind the cap that just stopped it.
2639
+ *
2640
+ * #8038: ALSO fires on `_spawnRefusal` — a binary-gate refusal (model
2641
+ * switch / permission-mode change / crash respawn the gate rejected) is
2642
+ * revivable in exactly the same "nothing else will bring this child back"
2643
+ * sense a user Stop is, unlike the terminal give-ups listed above: the gate
2644
+ * refused a SPECIFIC verdict (this binary, right now), and a later input
2645
+ * is a legitimate reason to ask it again (the operator may have restored
2646
+ * the ledger, re-approved the hash, fixed the quarantine, …). Both flags
2647
+ * share this one restart path rather than two near-identical copies.
2648
+ */
2649
+ _restartAfterStop() {
2650
+ if (!this._stoppedByUser && !this._spawnRefusal) return
2651
+ if (this._destroying) return
2652
+ if (this._respawning) return
2653
+ if (this._respawnScheduled) return
2654
+ // A child already exists — whoever spawned it owns the warmup drain.
2655
+ if (this._child) return
2656
+
2657
+ ;(this._log || log).info(this._spawnRefusal
2658
+ ? 'Re-running the binary gate to restart claude for a new message (its last spawn was refused)'
2659
+ : 'Restarting the stopped claude process to deliver a new message')
2660
+ // Consume the latches BEFORE starting, not inside start(): DockerSession
2661
+ // overrides start() and defers super.start() behind an async container
2662
+ // launch, so a second message arriving in that window would otherwise see
2663
+ // `_stoppedByUser` still armed and no child yet, and start a SECOND
2664
+ // container. Single-shot here makes the restart at-most-once regardless of
2665
+ // what a subclass's start() does or how long it takes.
2666
+ this._stoppedByUser = false
2667
+ // #8038: the refusal latch is consumed too. The gate re-runs inside start()
2668
+ // and re-latches only if it refuses AGAIN; left armed, a synchronous throw
2669
+ // from elsewhere in start() would get this input rejected under the
2670
+ // previous refusal's code instead of its own error.
2671
+ this._spawnRefusal = null
2672
+ try {
2673
+ this.start()
2674
+ } catch (err) {
2675
+ // Re-arm the latch: start() threw synchronously (spawn/arg failure) BEFORE
2676
+ // any child or container launch, so nothing was started. Without this the
2677
+ // latch stays consumed and the next sendMessage would only enqueue — never
2678
+ // retry the restart — re-stranding the follow-up behind a start-time error
2679
+ // (the exact #7438 failure mode). Re-arming lets the next user input retry;
2680
+ // it is not a loop — a retry only happens on a fresh send. It is re-armed
2681
+ // for a refusal-triggered restart as well (#8038): a gate refusal never
2682
+ // throws (_spawnPersistentProcess latches it and returns), so reaching
2683
+ // here means a DIFFERENT failure, and `_stoppedByUser` is the latch that
2684
+ // keeps a childless session revivable whatever took its child away.
2685
+ this._stoppedByUser = true
2686
+ ;(this._log || log).error(`Restart on new input failed: ${err.message}`)
2687
+ this.emit('error', { message: `Failed to restart the Claude process: ${err.message}` })
2688
+ }
2689
+ }
2690
+
1759
2691
  /** Interrupt the current message (send SIGINT to child process) */
1760
2692
  interrupt() {
1761
2693
  // #5936: a deliberate Stop cancels the owner's queued follow-ups (cancel,
@@ -1773,6 +2705,7 @@ export class CliSession extends BaseSession {
1773
2705
  // current turn), the next natural exit will be a real crash — the flag
1774
2706
  // is cleared in _handleChildClose on whichever exit fires first.
1775
2707
  this.markIntentionalStop()
2708
+ this._noteTurnStopRequested() // #7376
1776
2709
 
1777
2710
  // #4828: session-scoped if init has fired.
1778
2711
  ;(this._log || log).info('Sending SIGINT to claude process')
@@ -1794,7 +2727,7 @@ export class CliSession extends BaseSession {
1794
2727
  if (this._isBusy) {
1795
2728
  // #4828: session-scoped.
1796
2729
  ;(this._log || log).warn('Interrupt safety timeout — force-clearing busy state')
1797
- this._emitInterruptedTurnResult()
2730
+ this._emitInterruptedTurnResult(0, 'user_stop')
1798
2731
  }
1799
2732
  }, 5000)
1800
2733
  // #6043: fire-and-forget busy-state safety net — never gate process exit on
@@ -1865,6 +2798,18 @@ export class CliSession extends BaseSession {
1865
2798
  this._child = null
1866
2799
  }
1867
2800
 
2801
+ // #7337: remove the sidecar dir so long-lived daemons don't leak one
2802
+ // directory per session under /tmp. Nulls `_permissionModeFile` too, so a
2803
+ // setPermissionMode() after destroy() no-ops cleanly.
2804
+ //
2805
+ // Deliberately AFTER the kill above, not before it. The child stays alive
2806
+ // for up to the 3s force-kill grace and can fire a PreToolUse hook in that
2807
+ // window; removing the sidecar first makes that hook fall back to the
2808
+ // spawn-frozen CHROXY_PERMISSION_MODE, which is fail-open on a session that
2809
+ // was tightened since spawn (spawned `auto`, switched to `approve`, then
2810
+ // destroyed).
2811
+ this._cleanupPermissionModeSidecar()
2812
+
1868
2813
  // Emit completions for any tracked agents and clear busy state.
1869
2814
  // Must happen before removeAllListeners() so events are delivered.
1870
2815
  this._clearMessageState()