@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -7,6 +7,7 @@
7
7
  * SdkSession, and GeminiSession don't duplicate them.
8
8
  */
9
9
  import { EventEmitter } from 'events'
10
+ import { stillAuthorized } from './connection-authority.js'
10
11
  import { randomBytes } from 'crypto'
11
12
  import { resolveModelId } from './models.js'
12
13
  import {
@@ -15,13 +16,27 @@ import {
15
16
  } from './skills-loader.js'
16
17
  import { SkillsManager } from './skills-manager.js'
17
18
  import { BackgroundShellTracker } from './background-shell-tracker.js'
19
+ import { deriveBusyReason } from './session-busy-state.js'
18
20
  import { isOperatorTimeoutInRange } from './duration.js'
19
21
  import { createLogger } from './logger.js'
20
22
  import { ActivityRegistry } from './activity-registry.js'
21
23
  import { ALLOWED_PERMISSION_MODE_IDS } from './handler-utils.js'
24
+ import { assertProviderPermissionModeSupported, getProviderPermissionModeSupport } from './permission-mode-support.js'
25
+ import { AGENT_DESCRIPTION_MAX } from './claude-stream-parser.js'
26
+ import { sanitizeToolInput } from './redaction.js'
27
+ import { isTurnTerminationReason, describeTurnTermination } from '@chroxy/protocol'
28
+ import { isTurnOutcome } from './turn-outcome.js'
29
+ import { PROJECT_INSTRUCTION_BUDGET_BYTES } from './provider-customization.js'
22
30
 
23
31
  const log = createLogger('base-session')
24
32
 
33
+ // #8252: the text of a synthesized `tool_result` for a tool whose turn ended
34
+ // with no result and no termination reason (see `_sweepUnresolvedToolStarts`).
35
+ // A termination reason gets its own `describeTurnTermination(reason).summary`;
36
+ // this is the protocol's neutral wording for "no reason known", so the two cannot
37
+ // drift and neither claims the tool did not run.
38
+ export const UNFINISHED_TOOL_RESULT_TEXT = describeTurnTermination().summary
39
+
25
40
  // #3805: opt-in Chroxy context paragraph. Prepended to `_buildSystemPrompt()`
26
41
  // output when `chroxyContextHint` is true so the model knows it's running
27
42
  // inside Chroxy's remote-terminal front-end and can adjust its output for
@@ -40,6 +55,47 @@ export const CHROXY_CONTEXT_HINT_TEXT =
40
55
  // turn token overhead predictable.
41
56
  export const SESSION_PREAMBLE_MAX_LENGTH = 4000
42
57
 
58
+ // #8743: the events that mean the provider is doing something, stamped by the
59
+ // emit() override below and read as `providerActivityAgeMs` by the idle-only
60
+ // auto-deploy (daemon-idle-state.js). It is the conversation stream a working
61
+ // turn produces, so it is independent of the turn bookkeeping that `isBusy`
62
+ // reads: in trial run B2-cy-codex that bookkeeping said the turn was over while
63
+ // codex kept emitting for 17 minutes, and the deploy restarted the daemon under
64
+ // it. Events that are not evidence of work are in NOT_PROVIDER_ACTIVITY_EVENTS
65
+ // below, because one that recurs would hold every deploy off.
66
+ // tests/daemon-idle.test.js and tests/provider-custom-events-overlap.test.js put
67
+ // every forwarded session event (proxied, built-in transient, and each
68
+ // provider's `customEvents`) in exactly one of the two lists, and check that
69
+ // every name here is emitted somewhere.
70
+ export const PROVIDER_ACTIVITY_EVENTS = Object.freeze([
71
+ 'stream_start', 'stream_delta', 'stream_end', 'message',
72
+ 'tool_start', 'tool_input_delta', 'tool_result', 'result', 'stopped',
73
+ 'user_question', 'multi_question_intervention', 'background_tasks_changed',
74
+ 'agent_spawned', 'agent_event', 'agent_completed',
75
+ 'plan_started', 'plan_ready',
76
+ ])
77
+ const PROVIDER_ACTIVITY_EVENT_SET = new Set(PROVIDER_ACTIVITY_EVENTS)
78
+
79
+ // #8743: forwarded session events that do NOT stamp provider activity.
80
+ export const NOT_PROVIDER_ACTIVITY_EVENTS = Object.freeze([
81
+ // a boot or respawn handshake, and often the daemon's own failure, repeatable
82
+ // in a crash/respawn loop
83
+ 'ready', 'error',
84
+ // a prompt waiting on a human: the idle verdict counts it as pending already
85
+ 'permission_request', 'permission_resolved', 'permission_expired',
86
+ // the user's input queue, not the provider (queued input is a restart blocker)
87
+ 'message_queued', 'message_dequeued',
88
+ // derived from the tool and shell events, and recomputed on sweeps
89
+ 'activity_delta', 'activity_snapshot', 'background_work_changed', 'busy_cleared',
90
+ // configuration, environment and daemon housekeeping
91
+ 'mcp_servers', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
92
+ 'inactivity_warning', 'stdin_dropped_totals', 'setup_log', 'respawn_exhausted',
93
+ // #8700: a session's thinking level changed or was reported — a model switch,
94
+ // a setting, or Claude Code's report at the start of a turn the turn's own
95
+ // stream already stamps
96
+ 'thinking_level_changed',
97
+ ])
98
+
43
99
  // #5936 (epic #5935): explicit overflow cap for the shared outgoing-message
44
100
  // queue (`_outgoingQueue`). Replaces the SDK's hard-coded mid-turn cap of 3
45
101
  // (#5711) with one bounded, surfaced limit shared by SDK + CLI. A send-while-
@@ -48,6 +104,39 @@ export const SESSION_PREAMBLE_MAX_LENGTH = 4000
48
104
  // burst of owner follow-ups while still bounding memory if a client wedges.
49
105
  export const OUTGOING_QUEUE_MAX = 10
50
106
 
107
+ /**
108
+ * Report the provider's input-admission boundary without waiting for the turn.
109
+ * Async sendMessage implementations call this before their first await when
110
+ * possible, or later when an async transport handshake proves admission.
111
+ */
112
+ export function reportInputAdmission(sendOptions, admission) {
113
+ const callback = sendOptions?.onInputAdmission
114
+ if (typeof callback === 'function') callback(admission)
115
+ return admission
116
+ }
117
+
118
+ /**
119
+ * #8038 (extracted from #8030's `_refuseTurnBeforeDispatch`): the shared
120
+ * admission shape for an input the binary gate refused before anything was
121
+ * dispatched — a per-turn provider's turn (SdkSession, JsonlSubprocessSession)
122
+ * OR a persistent provider's spawn/respawn (CliSession, ClaudeTuiSession).
123
+ * Exported so both refusal paths report the identical wire shape instead of a
124
+ * hand-rolled second literal drifting from this one.
125
+ *
126
+ * `_refuseTurnBeforeDispatch` below is the ORIGINAL caller and its wire shape
127
+ * must stay byte-identical — this is a pure extraction, not a behavior change.
128
+ *
129
+ * @param {Error & { code?: string }} [err]
130
+ * @returns {{status: string, delivery: string, retrySafe: boolean, reason: string, message: string}}
131
+ */
132
+ export function spawnRefusalAdmission(err) {
133
+ return {
134
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
135
+ reason: err?.code || 'turn_refused',
136
+ message: 'The provider refused this turn before it was dispatched; see the session error for the cause.',
137
+ }
138
+ }
139
+
51
140
  // #3884 / #3749 / #3899: default SOFT inactivity warning (ms). Activity-based
52
141
  // — every provider event (SDK iterator message, CLI stdout JSONL line)
53
142
  // resets the timer; the window only bounds *silent stretches*, not wall-
@@ -130,10 +219,15 @@ export const BASE_SESSION_OPT_KEYS = [
130
219
  'promptEvaluatorSkipPattern',
131
220
  'chroxyContextHint',
132
221
  'sessionPreamble',
222
+ 'projectInstructions',
133
223
  'resultTimeoutMs',
134
224
  'hardTimeoutMs',
135
225
  'streamStallTimeoutMs',
136
226
  'backgroundShellHardQuiesceMs',
227
+ 'permissionRuleStore',
228
+ // #8035: see the ctor param doc below — closes the middle-layer trap for
229
+ // JsonlSubprocessSession's picker subclasses (Gemini/Codex-exec).
230
+ 'spawnPreflight',
137
231
  ]
138
232
 
139
233
  // #5367: pick the BaseSession opts out of a subclass's full opts bag and merge
@@ -183,7 +277,81 @@ function _coerceSessionPreambleOpt(value) {
183
277
  return trimmed
184
278
  }
185
279
 
280
+ /**
281
+ * #7095 — normalise `result.duration` to a whole, non-negative number of milliseconds.
282
+ *
283
+ * Applied on BaseSession's `emit()` override, the one method every `result` passes
284
+ * through (see the override's own note: a prior review missed 3 of 8 direct-emit
285
+ * sites). That placement is what makes this cover BOTH consumers — the live wire path
286
+ * in `event-normalizer.js` and the persisted `session-message-history.js` replay path,
287
+ * which read the same emitted object.
288
+ *
289
+ * Needed because four producers hand through values nothing guarantees:
290
+ * - cli-session.js `data.duration_ms` (Claude CLI stream-json)
291
+ * - sdk-session.js `msg.duration_ms` (Agent SDK)
292
+ * - codex-app-server-session.js `turn?.durationMs`
293
+ * - byok-session.js `Date.now() - turnStartedAt` (NEGATIVE on a backwards clock jump)
294
+ *
295
+ * #7083 closed only the CONFIG route into this field (`sdk-session.js`'s stall-timeout
296
+ * fallback); the three third-party routes stayed open. Without this, adding
297
+ * `.int().nonnegative()` to `ServerResultSchema` would make a real provider frame
298
+ * wire-illegal — the exact trade #7093 deliberately refused to make blind.
299
+ *
300
+ * `Math.round`, not `Math.trunc`: this is a MEASURED elapsed time, so the nearest whole
301
+ * ms is the faithful value. (#7083 chose truncation for CONFIG values, where the risk
302
+ * was rounding an out-of-range value UP into legality — a different problem.)
303
+ *
304
+ * `null` and absent pass through untouched — the field is nullable on the wire.
305
+ * Non-finite and past-2^53 values become `null`: both are unrepresentable, and `null`
306
+ * ("unknown") is honest where a clamped number would be a precise-looking lie.
307
+ *
308
+ * @param {unknown} payload
309
+ * @returns {unknown} the payload, or a copy with `duration` normalised
310
+ */
311
+ function normalizeResultDuration(payload) {
312
+ if (!payload || typeof payload !== 'object') return payload
313
+ const { duration } = payload
314
+ if (typeof duration !== 'number' || !Number.isFinite(duration)) {
315
+ // Non-finite: emit null rather than passing through. JSON.stringify turns
316
+ // Infinity/NaN into `null` on the wire and on disk ANYWAY, so passing them
317
+ // through does not preserve a visible failure — it just leaves the in-process
318
+ // object disagreeing with what every consumer actually receives. Doing it here
319
+ // makes the two agree.
320
+ if (typeof duration === 'number') return { ...payload, duration: null }
321
+ return payload
322
+ }
323
+ if (duration < 0) return { ...payload, duration: 0 }
324
+ const rounded = Math.round(duration)
325
+ // Math.round preserves Number.isInteger but NOT Number.isSafeInteger, and Zod's
326
+ // `.int()` enforces the SAFE-integer range. Rounding can even manufacture the
327
+ // problem: 9007199254740991.5 rounds UP to 2^53, which is an integer and is
328
+ // wire-illegal. A duration past 2^53 ms is ~285,000 years, i.e. garbage from a
329
+ // broken clock or a provider bug — so null ("unknown", the field is nullable) is
330
+ // the honest answer. Clamping to MAX_SAFE_INTEGER would render a precise-looking
331
+ // 285,000-year turn, which is the #7081 lesson: an absent value beats a false one.
332
+ if (!Number.isSafeInteger(rounded)) return { ...payload, duration: null }
333
+ if (rounded === duration) return payload
334
+ return { ...payload, duration: rounded }
335
+ }
336
+
186
337
  export class BaseSession extends EventEmitter {
338
+ /** Binary version observed by this live runtime, or `unknown`. */
339
+ get providerBinaryVersion() {
340
+ return 'unknown'
341
+ }
342
+
343
+ /** Runtime-negotiated capability states; static UI capabilities are separate. */
344
+ get providerRuntimeCapabilities() {
345
+ return {}
346
+ }
347
+
348
+ /** Provider-owned restart locator; generic persistence never reconstructs it. */
349
+ get nativeResumeState() { return null }
350
+
351
+ get providerInstructionProjection() {
352
+ return this._projectInstructionProjection
353
+ }
354
+
187
355
  /**
188
356
  * Custom event names emitted by this provider class that should be proxied
189
357
  * by SessionManager in addition to the built-in PROXIED_EVENTS list.
@@ -262,6 +430,9 @@ export class BaseSession extends EventEmitter {
262
430
  // SESSION_PREAMBLE_MAX_LENGTH on construction. Empty string (or any
263
431
  // non-string input) is the byte-identical-to-pre-#4660 default.
264
432
  sessionPreamble,
433
+ // #7835: separately bounded required project policy. This does not share
434
+ // the 4k user-preamble or runtime-skill pruning budgets.
435
+ projectInstructions,
265
436
  // #3749 / #3884 / #3899: configurable SOFT-warning timeout (the
266
437
  // inactivity safety net). Subclasses arm this timer; when it fires
267
438
  // they emit an `inactivity_warning` event so the client can render
@@ -287,9 +458,44 @@ export class BaseSession extends EventEmitter {
287
458
  // BACKGROUND_SHELL_HARD_QUIESCE_MS (4h); 0 disables hard-reaping (revert
288
459
  // to #5247 advisory-only). Forwarded from config via SessionManager.
289
460
  backgroundShellHardQuiesceMs,
461
+ // #6771 — the daemon-wide durable PermissionRuleStore (persistent per-project
462
+ // "always allow / deny"). A runtime handle (not serialized), forwarded from
463
+ // SessionManager; the in-process permission providers (SDK / BYOK / codex)
464
+ // hand it to their PermissionManager so an `allowAlways` decision persists a
465
+ // project-scoped rule and new sessions in the same cwd seed from it.
466
+ permissionRuleStore,
467
+ // #8035: per-spawn binary re-verification gate. SessionManager wires this
468
+ // to `_verifyPinnedSpawn` (re-runs the full binary gate against the EXACT
469
+ // path create-time preflight verified) whenever preflight ran and the
470
+ // provider isn't containerised. Lives on BaseSession — not read directly
471
+ // by a subclass's opts bag — so every picker subclass built via
472
+ // `buildBaseSessionOpts` (GeminiSession, CodexSession, …) inherits it for
473
+ // free; reading `opts.spawnPreflight` in a middle layer instead would hit
474
+ // the trap documented in [[feedback_jsonl_subprocess_middle_layer]] and
475
+ // `BASE_SESSION_OPT_KEYS` above is what the opt-forwarding lint checks.
476
+ // null when absent — callers fall back to a plain
477
+ // `this.constructor.resolvedBinary` read via `_gatedSpawnBinary` below,
478
+ // same as pre-#8030/#8035 (a direct constructor call that bypasses
479
+ // SessionManager, or a test).
480
+ spawnPreflight,
290
481
  } = {}) {
291
482
  super()
292
483
  this.cwd = cwd || process.cwd()
484
+ // #6771 — durable per-project permission rule store (see the opt doc above).
485
+ // Read by the in-process permission providers when they build their
486
+ // PermissionManager; null on providers/tests that don't wire it.
487
+ this._permissionRuleStore = permissionRuleStore || null
488
+ // #8035 — see the ctor param doc above. Stored here (not in SdkSession, not
489
+ // read ad hoc off `opts` in JsonlSubprocessSession) so both the per-turn SDK
490
+ // exec and the per-turn subprocess spawn (Gemini/Codex-exec) share one
491
+ // source of truth via `_gatedSpawnBinary` below.
492
+ this._spawnPreflight = typeof spawnPreflight === 'function' ? spawnPreflight : null
493
+ // #8038 — latched by `_refuseSpawn` when a (re)spawn attempt's binary gate
494
+ // (CliSession._spawnPersistentProcess, ClaudeTuiSession._spawnPty /
495
+ // _respawnPty) throws instead of returning a verified path. null means
496
+ // "no refusal outstanding" — the normal state, and the state after a
497
+ // revival succeeds. See `_refuseSpawn`'s doc for the full contract.
498
+ this._spawnRefusal = null
293
499
  this.model = model || null
294
500
  // Actual model the underlying CLI/SDK reports at init time. May differ
295
501
  // from `this.model` (the user's requested override) when no override
@@ -300,13 +506,14 @@ export class BaseSession extends EventEmitter {
300
506
  // Set by subclasses in their init handlers (#3687).
301
507
  this.bootedModel = null
302
508
  this.permissionMode = permissionMode || 'approve'
509
+ assertProviderPermissionModeSupported(this.constructor, this.permissionMode)
303
510
  // #3185: per-session toggle for the auto-evaluator chain (parent epic
304
511
  // #3068). Default `false` — the existing manual `evaluate_draft` flow
305
512
  // (PR #3089) is unaffected by this flag. Coerced to a strict boolean
306
513
  // here so JSON.stringify produces `true`/`false` (not `1`/`null`) on
307
514
  // the auth_ok / session_list wires.
308
515
  this.promptEvaluator = !!promptEvaluator
309
- // #3639: per-session regex source string used by `shouldSkipEvaluator`
516
+ // #3639: per-session regex source string used by `shouldSkipEvaluatorAsync`
310
517
  // to extend the default continuation/ack skip list. Mirrors the
311
518
  // server-wide `config.promptEvaluatorSkipPattern` from #3187 but is
312
519
  // evaluated FIRST in input-handlers.js so a per-session override
@@ -330,9 +537,39 @@ export class BaseSession extends EventEmitter {
330
537
  // smuggle in unbounded text. The runtime setter (setSessionPreamble)
331
538
  // does the same coercion and reports rejection on type mismatch.
332
539
  this.sessionPreamble = _coerceSessionPreambleOpt(sessionPreamble)
540
+ this.projectInstructions = typeof projectInstructions === 'string' ? projectInstructions : ''
541
+ const projectInstructionBytes = Buffer.byteLength(this.projectInstructions, 'utf8')
542
+ if (projectInstructionBytes > PROJECT_INSTRUCTION_BUDGET_BYTES) {
543
+ throw new Error(`projectInstructions exceeds ${PROJECT_INSTRUCTION_BUDGET_BYTES} UTF-8 bytes`)
544
+ }
545
+ this._projectInstructionProjection = {
546
+ status: this.projectInstructions ? 'delivered' : 'unknown',
547
+ enforcement: 'instructional',
548
+ compilerVersion: '1',
549
+ budgetBytes: this.projectInstructions ? PROJECT_INSTRUCTION_BUDGET_BYTES : 0,
550
+ totalBytes: projectInstructionBytes,
551
+ sources: [], rules: [], includedRequiredRuleIds: [],
552
+ }
333
553
 
334
- this._isBusy = false
554
+ this._busyFlag = false
335
555
  this._processReady = false
556
+ // #8743: when the provider last produced output, on the monotonic
557
+ // `_providerActivityClock()`. null until it first does. See noteProviderActivity.
558
+ this._providerActivityAtMs = null
559
+ // #7382: outstanding hook-routed permission prompts, by requestId. Hoisted
560
+ // from CliSession, where it was written for #2831 and stayed provider-local
561
+ // through #7375/#7379 — so claude-tui, then DEFAULT_PROVIDER, which routes
562
+ // its prompts through the SAME permission-hook.sh into the SAME daemon map,
563
+ // silently had none of it. `ws-permissions` guards its calls with
564
+ // `typeof ownerSession.notifyPermissionPending === 'function'`, so the
565
+ // missing methods were not an error — they were a skip, which is the
566
+ // success-and-not-checking shape in docs/false-safety-guards.md.
567
+ //
568
+ // Lives here so a THIRD hook-routed provider inherits it rather than
569
+ // re-implementing it. A derived-roster test (hook-routed-permission-
570
+ // bookkeeping.test.js) fails if any `*-session.js` that mints a
571
+ // `_hookSecret` lacks the API.
572
+ this._pendingPermissionIds = new Set()
336
573
  // #5375: user-initiated stop vs crash. Set by interrupt() (markIntentionalStop),
337
574
  // captured-and-cleared by the provider's close/error handler
338
575
  // (_consumeIntentionalStop) so a clean stop is not reported as an error.
@@ -342,6 +579,20 @@ export class BaseSession extends EventEmitter {
342
579
  // `finally` safety-net clear (the interrupt-races-result case), and collapsing
343
580
  // them would reopen that race.
344
581
  this._intentionalStop = false
582
+ // #7376: a Stop was requested while THIS turn was running. Unlike
583
+ // `_intentionalStop` (consumed by the child-close / query-catch handler, and
584
+ // not armed at all when the provider acknowledges the interrupt with a
585
+ // normal `result`), this one lives exactly as long as the turn: set by
586
+ // `_noteTurnStopRequested`, read by the orphan sweep, and reset by
587
+ // `_clearMessageState`. It is what lets a Stop that COMPLETES normally still
588
+ // tag the tools it cut off as `user_stop`.
589
+ this._stopRequestedThisTurn = false
590
+ // #8461: per Stop REQUEST (reset by `markIntentionalStop`, not per turn): a
591
+ // `stopped` event has gone out for it, and the one `emit('result')` sent in
592
+ // place of the Stopped chip, which a later `stopped` for the same Stop (the
593
+ // CLI child's exit, a late abort rejection) must not repeat.
594
+ this._stoppedSinceStopRequest = false
595
+ this._stopAckedByResult = false
345
596
  // #4307/#5177/#5247/#5265: pending background-shell tracking + the reaping
346
597
  // sweep live in BackgroundShellTracker (#5376). BaseSession composes one and
347
598
  // delegates the public surface (trackBackgroundShell / clearBackgroundShell /
@@ -375,6 +626,22 @@ export class BaseSession extends EventEmitter {
375
626
  // forever AND persist the orphan to session-state.json. Companion
376
627
  // path: SessionMessageHistory.sweepUnresolvedToolStarts (#4617/#4619)
377
628
  // catches stragglers at restore-time as a backstop.
629
+ //
630
+ // #7346: entries may also carry a finalized `input` field, set via
631
+ // `_recordToolInput` once the provider knows the tool's full input
632
+ // (CliSession: parsed `content_block_stop` buffer; SdkSession: the
633
+ // full assistant-message `block.input`, no buffering needed). Both
634
+ // `content_block_start`'s `tool_start` and the Anthropic wire
635
+ // protocol's `content_block_start` for a tool_use carry `input: null`
636
+ // — the finalized value only exists once the block closes — so this
637
+ // is the one place both providers can stash it for `tool-result.js`'s
638
+ // `emitToolResults` to read back (`_getTrackedToolInput`) and attach
639
+ // to the matching `tool_result`, which lets the client (and
640
+ // persisted history, via session-message-history.js) backfill the
641
+ // `tool_start` entry that was `input: null` when first emitted.
642
+ // BYOK never calls `_trackToolStart`, so this map stays empty there
643
+ // and `_getTrackedToolInput` always returns `undefined` — BYOK's
644
+ // `tool_result` is unaffected.
378
645
  this._inFlightToolStarts = new Map()
379
646
  // #5160: per-session activity registry (Control Room). A thin unifying
380
647
  // layer that maps the signals BaseSession already emits (tool_start /
@@ -389,6 +656,22 @@ export class BaseSession extends EventEmitter {
389
656
  emit: (event, payload) => this.emit(event, payload),
390
657
  })
391
658
  this._setupActivityRegistry()
659
+ // #6832: `mcp_servers` is a transient event (sdk/cli parse it off the live
660
+ // stream-json `system/init`; claude-tui re-derives the CONFIGURED list on
661
+ // warmup/respawn — see claude-tui-session.js `_emitConfiguredMcpServers`,
662
+ // #6820/#6831) — forwarded to currently-connected clients but never
663
+ // recorded in history. A client that subscribes to an already-warmed
664
+ // session (dashboard reconnect, second client joining a shared session)
665
+ // never received the list until the NEXT emission. Cache the last payload
666
+ // here — self-listening on the session's own emit, so every provider that
667
+ // emits `mcp_servers` through `this.emit(...)` feeds this for free, same
668
+ // as `_setupActivityRegistry` above — and expose it via
669
+ // `getMcpServersSnapshot()` so `ws-history.sendSessionInfo`'s snapshot-on-
670
+ // subscribe can replay it, mirroring the `activity_snapshot` /
671
+ // `permission_rules_updated` late-join pattern. Cleared on full teardown
672
+ // (see `removeAllListeners` below).
673
+ this._lastMcpServers = null
674
+ this.on('mcp_servers', (data) => { this._lastMcpServers = data })
392
675
  this._messageCounter = 0
393
676
  // Boot-unique prefix mixed into every emitted messageId (#3700).
394
677
  // The dashboard caches up to 100 messages per session in localStorage
@@ -508,6 +791,110 @@ export class BaseSession extends EventEmitter {
508
791
  }
509
792
  }
510
793
 
794
+ /**
795
+ * #8035 — the one spawn-path helper every per-turn provider (SdkSession,
796
+ * JsonlSubprocessSession's Gemini/Codex-exec subclasses) uses instead of
797
+ * reading `this.constructor.resolvedBinary` directly. With a gate wired
798
+ * (`_spawnPreflight`, set from SessionManager's `spawnPreflight` opt — see
799
+ * the ctor doc above), it re-runs the full binary-provenance gate against
800
+ * the exact path create-time preflight verified and returns THAT path,
801
+ * pinned regardless of what `resolvedBinary` would resolve to right now.
802
+ * Without a gate (no SessionManager, a direct constructor call, most
803
+ * tests), it falls back to the plain static read — the pre-#8030 behavior.
804
+ *
805
+ * A non-string or empty result would leave the caller launching an
806
+ * unverified binary (e.g. the SDK falling back to its own bundled claude),
807
+ * so that case throws instead of returning — `PROVIDER_BINARY_UNVERIFIED`,
808
+ * with `binaryLabel` in the message so the two callers keep their own
809
+ * wording (SdkSession passes 'claude'; JsonlSubprocessSession passes
810
+ * `Klass.providerName`). Any error the gate itself throws (
811
+ * `PROVIDER_BINARY_PROVENANCE`, `PROVIDER_BINARY_QUARANTINED`,
812
+ * `PROVIDER_BINARY_NOT_FOUND`, …) propagates unchanged — this method adds
813
+ * exactly one new failure mode, it doesn't wrap existing ones.
814
+ *
815
+ * @param {string} binaryLabel — human name for the empty-path error text
816
+ * @returns {string} the verified path to spawn
817
+ * @throws {Error} PROVIDER_BINARY_UNVERIFIED, or whatever the gate throws
818
+ */
819
+ _gatedSpawnBinary(binaryLabel) {
820
+ const path = this._spawnPreflight ? this._spawnPreflight() : this.constructor.resolvedBinary
821
+ if (typeof path !== 'string' || path.length === 0) {
822
+ const err = new Error(`No verified ${binaryLabel} binary path is available for this turn.`)
823
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
824
+ throw err
825
+ }
826
+ return path
827
+ }
828
+
829
+ /**
830
+ * #8035 — the shared refusal path for a turn the binary gate stopped
831
+ * BEFORE dispatch (paired with `_gatedSpawnBinary` above). Hoisted out of
832
+ * SdkSession (#8030) so JsonlSubprocessSession's per-turn spawn gets the
833
+ * same wire shape rather than a hand-rolled second copy.
834
+ *
835
+ * Deliberately does NOT run any error-text rewriter: a provenance message
836
+ * embeds a hex hash prefix (e.g. "...a4291b0c...") that can match a
837
+ * rate-limit ("429") or auth ("401") pattern in a text-classification table
838
+ * and get silently rewritten into a wrong, misleading message instead of
839
+ * the real cause (see SdkSession's #8030 comment on `_enrichErrorMessage`).
840
+ *
841
+ * @param {Error & { code?: string }} err
842
+ * @param {object} sendOptions — this turn's sendMessage options (for the admission callback)
843
+ * @param {{ error: Function }} logger — the caller's logger (`this._log || log`)
844
+ */
845
+ _refuseTurnBeforeDispatch(err, sendOptions, logger) {
846
+ logger.error(`Turn refused before dispatch: ${err.message}`)
847
+ // An uncoded throw (e.g. from a subclass's augment hook) is not a
848
+ // binary-verification failure, so it gets a neutral code.
849
+ this.emit('error', { code: err.code || 'TURN_REFUSED', message: err.message })
850
+ // #8038: extracted to spawnRefusalAdmission() so CliSession/ClaudeTuiSession's
851
+ // spawn-refusal-on-send path reports the identical wire shape — see that
852
+ // function's doc. Byte-identical to the pre-#8038 inline literal.
853
+ reportInputAdmission(sendOptions, spawnRefusalAdmission(err))
854
+ }
855
+
856
+ /**
857
+ * #8038 — the shared refusal path for a (re)SPAWN the binary gate stopped,
858
+ * as opposed to `_refuseTurnBeforeDispatch` above (which refuses a single
859
+ * TURN on a provider that spawns fresh per turn). CliSession's
860
+ * `_spawnPersistentProcess` and ClaudeTuiSession's `_respawnPty` call this
861
+ * when `_gatedSpawnBinary` (or, for the TUI native route, the equivalent
862
+ * `_connectionRuntimePreflight` re-check) throws instead of returning a
863
+ * verified path — nothing was spawned, so there is no child/PTY error to
864
+ * report through the normal exit-handling path. #8044: the TUI native
865
+ * route's `claude auth status` verdict (logged out, a non-first-party route,
866
+ * unreadable status) is refused the same way, also before any spawn.
867
+ * #8057 is the one post-spawn case: the native endpoint-marker verdict
868
+ * arrives after the PTY launched, so `_spawnPty` kills and drops that PTY
869
+ * first and the refusal then follows these same semantics — no live child
870
+ * remains, and no exit-handling path reports it either.
871
+ *
872
+ * Latches `this._spawnRefusal = err` so:
873
+ * - the provider's own respawn machinery can tell "the gate refused this
874
+ * attempt" apart from "the child/PTY actually died" and skip scheduling
875
+ * a backoff timer for a spawn that was never going to happen anyway
876
+ * (which would otherwise burn the bounded respawn budget into a
877
+ * misleading `respawn_exhausted` / "failed to stay alive");
878
+ * - the next `sendMessage` re-runs the gate once (CliSession via
879
+ * `_restartAfterStop`, ClaudeTuiSession via `_respawnPty`) and, if it
880
+ * refuses again, rejects THAT input with `spawnRefusalAdmission` instead
881
+ * of queuing it behind a child that will never start.
882
+ *
883
+ * Emits the SAME coded `error` shape `_refuseTurnBeforeDispatch` does
884
+ * (`code: err.code || …, message: err.message`) with NO error-text
885
+ * rewriter — see that method's doc for why (a provenance message embeds a
886
+ * hex hash that can spuriously match a 429/401 text-classification
887
+ * pattern and get rewritten into a wrong, misleading message).
888
+ *
889
+ * @param {Error & { code?: string }} err
890
+ * @param {{ error: Function }} logger — the caller's logger (`this._log || log`)
891
+ */
892
+ _refuseSpawn(err, logger) {
893
+ this._spawnRefusal = err
894
+ logger.error(`Spawn refused: ${err.message}`)
895
+ this.emit('error', { code: err?.code || 'SPAWN_REFUSED', message: err.message })
896
+ }
897
+
511
898
  /**
512
899
  * #5376: delegate to SkillsManager. Kept as a session method because
513
900
  * settings-handlers.js calls `session._loadSkills()` to rebuild after a
@@ -574,6 +961,27 @@ export class BaseSession extends EventEmitter {
574
961
  return this._skillsManager.deactivateSkill(skillName)
575
962
  }
576
963
 
964
+ /**
965
+ * #8259: the model is mid-turn. Every provider assigns `_isBusy = true` when it
966
+ * dispatches a turn to its backend (including a queued follow-up when the queue
967
+ * flushes) and BaseSession clears it at every turn end, so this accessor is the
968
+ * ONE place a turn starting or ending is observable. A change emits
969
+ * `turn_state` `{ active }` (internal: not in the proxied event list) so the
970
+ * SessionManager can persist "a turn was in flight" and, after a daemon
971
+ * restart, tell a turn that was cut off from one that merely has no `result`
972
+ * in its history.
973
+ */
974
+ get _isBusy() {
975
+ return this._busyFlag === true
976
+ }
977
+
978
+ set _isBusy(value) {
979
+ const next = !!value
980
+ if (this._busyFlag === next) return
981
+ this._busyFlag = next
982
+ this.emit('turn_state', { active: next })
983
+ }
984
+
577
985
  /**
578
986
  * #4307: a session is "running" — i.e. NOT idle, NOT subject to
579
987
  * `SessionTimeoutManager` reaping — when EITHER:
@@ -602,6 +1010,36 @@ export class BaseSession extends EventEmitter {
602
1010
  return this._backgroundShellTracker.size > 0
603
1011
  }
604
1012
 
1013
+ /**
1014
+ * #8302: the model is mid-turn. The first half of `isRunning`, exposed alone
1015
+ * so a publisher can tell "working" from "held busy by a background shell".
1016
+ * @returns {boolean}
1017
+ */
1018
+ get turnActive() {
1019
+ return !!this._isBusy
1020
+ }
1021
+
1022
+ /**
1023
+ * #8302: how many background shells the tracker holds. The tracker's `size`,
1024
+ * which counts shells the advisory mtime sweep has hidden from
1025
+ * `getPendingBackgroundShells()` (they still hold `isRunning` true).
1026
+ * @returns {number}
1027
+ */
1028
+ get backgroundShellCount() {
1029
+ return this._backgroundShellTracker.size
1030
+ }
1031
+
1032
+ /**
1033
+ * #8302: why `isRunning` is true — `'turn'`, `'background-shells'` (idle model,
1034
+ * tracked shells only), or `null` when the session is not busy. Derived from
1035
+ * `isRunning` itself so a subclass that overrides it (the user shell's PTY
1036
+ * liveness) keeps `busyReason === null <=> !isRunning`.
1037
+ * @returns {'turn'|'background-shells'|null}
1038
+ */
1039
+ get busyReason() {
1040
+ return deriveBusyReason(this.isRunning, this.turnActive, this.backgroundShellCount)
1041
+ }
1042
+
605
1043
  /**
606
1044
  * #4307: read-only snapshot of pending background shells.
607
1045
  * #5376: delegates to BackgroundShellTracker.
@@ -712,6 +1150,21 @@ export class BaseSession extends EventEmitter {
712
1150
  const remaining = this._outgoingQueue.length
713
1151
  process.nextTick(() => {
714
1152
  if (this._destroying) return
1153
+ // #8301: an item that carries `sendOptions.admitAtFlush` is re-checked HERE,
1154
+ // at the moment it would be dispatched — after the preceding turn's
1155
+ // `result` has been broadcast and processed on every turn-end path. Its
1156
+ // admission at enqueue time can be stale by then (the result can trip the
1157
+ // cost-budget pause). The predicate is a LOCAL callback: it is never put on
1158
+ // the wire (`message_queued` carries only id/text/length) and the queue is
1159
+ // not persisted. Typed input does not set it, so its behaviour is unchanged.
1160
+ // A refusal — or a throwing predicate, which fails safe — cancels just this
1161
+ // item and goes on to consider the next, so the queue keeps draining.
1162
+ if (!this._admitQueuedItem(item)) {
1163
+ this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'cancelled' })
1164
+ ;(this._log || log).warn(`Dropped queued follow-up at flush: admission refused (${remaining} remaining)`)
1165
+ this._continueDrainAfterRefusal()
1166
+ return
1167
+ }
715
1168
  this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'flush' })
716
1169
  ;(this._log || log).info(`Dequeuing follow-up message (${remaining} remaining)`)
717
1170
  this.sendMessage(item.prompt, item.attachments, item.sendOptions)
@@ -719,6 +1172,57 @@ export class BaseSession extends EventEmitter {
719
1172
  return item
720
1173
  }
721
1174
 
1175
+ /**
1176
+ * #8301: the refused item held this turn's drain slot, so keep draining. The
1177
+ * default continues with the next outgoing item. A provider with a second
1178
+ * queue behind `_outgoingQueue` (CliSession's startup queue) overrides this to
1179
+ * fall through to it, exactly as its own turn-end drain would have.
1180
+ */
1181
+ _continueDrainAfterRefusal() {
1182
+ if (this._outgoingQueue.length && !this._destroying) this.dequeueNextOutgoing()
1183
+ }
1184
+
1185
+ /**
1186
+ * #8301: evaluate a queued item's optional flush-time admission predicate.
1187
+ * No predicate means admitted (every typed input). A predicate that returns
1188
+ * anything but `true`, or throws, means NOT admitted.
1189
+ *
1190
+ * @param {{ sendOptions?: { admitAtFlush?: () => boolean } }} item
1191
+ * @returns {boolean}
1192
+ */
1193
+ _admitQueuedItem(item) {
1194
+ // The connection that queued this follow-up may have ended while it waited:
1195
+ // a revoked or expired credential must not get its queued input dispatched.
1196
+ if (!stillAuthorized(item?.sendOptions?.isAuthorized)) return false
1197
+ const predicate = item?.sendOptions?.admitAtFlush
1198
+ if (typeof predicate !== 'function') return true
1199
+ try {
1200
+ return predicate() === true
1201
+ } catch (err) {
1202
+ ;(this._log || log).warn(`Queued follow-up admission check threw; dropping it: ${err?.message || err}`)
1203
+ return false
1204
+ }
1205
+ }
1206
+
1207
+ /**
1208
+ * #8301: why a DAEMON-authored turn (the CI wake) must not be handed to this
1209
+ * session right now, or `null` when it may. The provider's half of the one
1210
+ * refusal seam `SessionManager.daemonTurnRefusal` asks — before dispatch and
1211
+ * again when a queued wake is about to flush.
1212
+ *
1213
+ * This is a stricter question than "can the user type here": a typed input
1214
+ * may legitimately revive a stopped session or surface an error, but a
1215
+ * daemon wake that does so is a side effect nobody asked for. A provider
1216
+ * overrides it for the states in which `sendMessage` would do that (respawn,
1217
+ * discard the queue, report a user-visible error). The default is `null`: a
1218
+ * provider that has no such state is always willing.
1219
+ *
1220
+ * @returns {string|null} a short reason, or null
1221
+ */
1222
+ daemonTurnRefusal() {
1223
+ return null
1224
+ }
1225
+
722
1226
  /**
723
1227
  * #5936: drop every queued outgoing message. Called by `interrupt()` so a
724
1228
  * deliberate Stop cancels the owner's pending follow-ups rather than letting
@@ -839,12 +1343,36 @@ export class BaseSession extends EventEmitter {
839
1343
  // shape with the right argument count.
840
1344
  if (eventName === undefined) {
841
1345
  this._activity.clear()
1346
+ // #6832: clear the cached mcp_servers snapshot on full teardown too —
1347
+ // a destroyed session must not replay a stale server list to a client
1348
+ // that later subscribes to a NEW session that happens to reuse the id
1349
+ // (or to any lingering reference to this now-dead session object).
1350
+ this._lastMcpServers = null
842
1351
  // #5177: stop the background-shell sweep on full teardown too. Most
843
1352
  // providers (cli/jsonl/gemini/codex) destroy via removeAllListeners()
844
1353
  // and never call _destroyPendingBackgroundShells, so this is the
845
1354
  // chokepoint that guarantees no provider leaks the recurring timer.
846
1355
  this._stopBackgroundShellSweep()
847
- return super.removeAllListeners()
1356
+ // #7340: drop EVERY tracked subagent, foreground and backgrounded alike.
1357
+ // Before #7340 the turn-end sweep guaranteed this map was empty by the
1358
+ // time a session was torn down; agents that outlive their turn break that
1359
+ // guarantee, so the same chokepoint that stops the shell sweep clears
1360
+ // them. A destroy landing MID-TURN also has foreground agents tracked,
1361
+ // which is why this is an unconditional clear and not a filtered one --
1362
+ // the `backgroundConfirmed` predicate belongs to the turn-end sweep, where the
1363
+ // question is "did this outlive its turn", not to teardown, where there
1364
+ // is no next turn for anything to outlive. No `agent_completed` emit: the
1365
+ // session is being destroyed, its clients drop its state wholesale, and
1366
+ // the listeners come off on the next line anyway.
1367
+ this._activeAgents.clear()
1368
+ const removed = super.removeAllListeners()
1369
+ // A turn aborted by this teardown can still emit 'error' after the
1370
+ // listeners are gone; with none attached that throws ERR_UNHANDLED_ERROR.
1371
+ // SessionManager.destroySession adds a no-op listener, but the provider's
1372
+ // own destroy() ends here and would drop it. Re-add it for a session that
1373
+ // is being destroyed.
1374
+ if (this._destroying) super.on('error', () => {})
1375
+ return removed
848
1376
  }
849
1377
  return super.removeAllListeners(eventName)
850
1378
  }
@@ -859,15 +1387,108 @@ export class BaseSession extends EventEmitter {
859
1387
  this._activity.setSessionId(sessionId)
860
1388
  }
861
1389
 
862
- /**
863
- * #5160: full current activity tree as an `activity_snapshot` message.
864
- * Served to a fresh subscriber (snapshot-on-subscribe) and on resync.
865
- * @returns {object} the `activity_snapshot` wire message
866
- */
1390
+ /** Project durable session intent into the existing activity tree. */
1391
+ setDeclaredStatusActivity(status) {
1392
+ this._activity.onDeclaredStatus(status)
1393
+ }
1394
+
1395
+ getDecisionActivityState() {
1396
+ return this._activity.getDecisionState()
1397
+ }
1398
+
1399
+ restoreDeclaredStatusActivity(status, state) {
1400
+ this._activity.restoreDecisionState(status, state)
1401
+ }
1402
+
1403
+ /** Full current tree for fresh subscribers and resync. */
867
1404
  getActivitySnapshot() {
868
1405
  return this._activity.getSnapshotMessage()
869
1406
  }
870
1407
 
1408
+ /**
1409
+ * #7340: the subagents this session is currently tracking, as the wire
1410
+ * fields of an `agent_spawned` message.
1411
+ *
1412
+ * Serves the same purpose `getActivitySnapshot()` does for the Control Room
1413
+ * tree, for the surface that has no tree: `agent_spawned` / `agent_completed`
1414
+ * are transient (`builtinTransient` in SessionManager) and are NOT replayed
1415
+ * from history, so both clients WIPE `activeAgents` at `history_replay_start`
1416
+ * and nothing put it back. That was harmless while no agent outlived its
1417
+ * turn; once one does, a 2s cellular drop or a tab switch returned the
1418
+ * session to `idle` with subagents still running -- #7340's exact symptom,
1419
+ * reached a different way.
1420
+ *
1421
+ * Re-emitting the live set AFTER the replay makes the wipe a snapshot
1422
+ * REPLACE rather than a loss: the wipe clears whatever the client held
1423
+ * (including a completion it missed while offline, which is why the wipe is
1424
+ * kept rather than carved out the way #4466 did for `activeTools`), and this
1425
+ * re-asserts what is actually running. Both clients dedupe `agent_spawned`
1426
+ * by `toolUseId`, so re-emitting to a client that never lost the entry is a
1427
+ * no-op.
1428
+ *
1429
+ * Projected to the three fields `event-normalizer` puts on the wire -- the
1430
+ * record's `background` / `backgroundConfirmed` are server-side bookkeeping
1431
+ * and must not start leaking to clients through this path.
1432
+ *
1433
+ * @returns {{ toolUseId: string, description: string, startedAt: number }[]}
1434
+ */
1435
+ getActiveAgents() {
1436
+ // Keyed by the MAP KEY, not `agent.toolUseId` -- the same invariant
1437
+ // `_completeAgents` states. A record whose field drifted from its key would
1438
+ // otherwise be re-announced under one id and completed under another, and
1439
+ // the client's dedupe and its filter would key on different ids, leaving a
1440
+ // badge entry nothing can clear.
1441
+ return Array.from(this._activeAgents, ([toolUseId, { description, startedAt }]) => ({
1442
+ toolUseId,
1443
+ description,
1444
+ startedAt,
1445
+ }))
1446
+ }
1447
+
1448
+ /**
1449
+ * #7457: the AskUserQuestion prompts this session's turn is still BLOCKED on.
1450
+ *
1451
+ * Read by `ws-history.resendPendingQuestions`, which re-sends each one as a
1452
+ * LIVE `user_question` frame after every replay's `history_replay_end`. Until
1453
+ * then the only path a pending question had to a reconnecting client was the
1454
+ * history replay itself -- and `history_replay_end`'s sweep stamps every
1455
+ * replay-delivered prompt `answered: '(resolved)'`, so an ordinary reconnect
1456
+ * destroyed the answer path for a question the agent was still waiting on.
1457
+ *
1458
+ * Deliberately a READ-THROUGH to whatever store the provider already uses to
1459
+ * hold the blocked resolver -- `PermissionManager._pendingUserAnswer` for the
1460
+ * in-process providers, `_pendingUserAnswers` for claude-tui,
1461
+ * `_pendingQuestion` for cli-session. A mirrored copy would need a lifecycle
1462
+ * of its own, and a leaked mirror entry re-delivers a dead question to every
1463
+ * client that ever connects again; a read-through cannot leak, because the
1464
+ * record IS the thing blocking the turn.
1465
+ *
1466
+ * The default is EMPTY, not "unsupported": a provider with no question
1467
+ * surface has nothing pending, and `resendPendingQuestions` calls this
1468
+ * unguarded -- a feature-detect that can never fail only converts a future
1469
+ * regression into a silent no-op (docs/false-safety-guards.md).
1470
+ *
1471
+ * @returns {{ toolUseId: string, questions: object[] }[]}
1472
+ */
1473
+ getPendingQuestions() {
1474
+ return []
1475
+ }
1476
+
1477
+ /**
1478
+ * #6832: last-known `mcp_servers` payload, wrapped as the wire message
1479
+ * shape (`{ type: 'mcp_servers', servers }`). Served to a fresh subscriber
1480
+ * (snapshot-on-subscribe, via `ws-history.sendSessionInfo`) so a client
1481
+ * that joins an already-warmed session sees the current list without
1482
+ * waiting on the next emission — mirroring `getActivitySnapshot()` above.
1483
+ * Returns `null` when this session has never emitted `mcp_servers` (no
1484
+ * snapshot to replay; nothing to send).
1485
+ * @returns {{type: 'mcp_servers', servers: object[]} | null}
1486
+ */
1487
+ getMcpServersSnapshot() {
1488
+ if (!this._lastMcpServers) return null
1489
+ return { type: 'mcp_servers', servers: this._lastMcpServers.servers }
1490
+ }
1491
+
871
1492
  /**
872
1493
  * #5269 (Control Room Phase 2a): cancel a single in-flight activity node by
873
1494
  * its `activityId` (an `activity_snapshot`/`activity_delta` entry id).
@@ -926,6 +1547,22 @@ export class BaseSession extends EventEmitter {
926
1547
  return this._backgroundShellTracker._isBackgroundShellQuiesced(entry)
927
1548
  }
928
1549
 
1550
+ /**
1551
+ * #7611: forget every pending background shell WITHOUT tearing the session
1552
+ * down — for a provider that has just killed the process tree the shells
1553
+ * lived in and is about to start a fresh one. Unlike
1554
+ * `_destroyPendingBackgroundShells` it leaves the activity registry and the
1555
+ * intra-turn command map alone (the session carries on, and those belong to
1556
+ * the turn machinery), and it emits `background_work_changed` so the banner
1557
+ * drops the dead shells. delegates to BackgroundShellTracker.clearAll().
1558
+ *
1559
+ * @returns {number} how many pending shells were forgotten
1560
+ * @private
1561
+ */
1562
+ _clearPendingBackgroundShells() {
1563
+ return this._backgroundShellTracker.clearAll()
1564
+ }
1565
+
929
1566
  /**
930
1567
  * #4307: clear the pending map on session destroy. Pulled into a
931
1568
  * helper so subclasses can call it from their own `destroy()` after
@@ -1007,6 +1644,40 @@ export class BaseSession extends EventEmitter {
1007
1644
  */
1008
1645
  markIntentionalStop() {
1009
1646
  this._intentionalStop = true
1647
+ // #8461: a new Stop request is acknowledged on its own.
1648
+ this._stoppedSinceStopRequest = false
1649
+ this._stopAckedByResult = false
1650
+ }
1651
+
1652
+ /**
1653
+ * #8374/#8430: the USER pressed Stop. Record it on the session's permission
1654
+ * manager for the rest of the turn, so the abort that follows resolves the
1655
+ * prompts open now -- and any raised before the abort lands -- as `stopped`
1656
+ * rather than `aborted`. Called by the `interrupt` message handler only -- never
1657
+ * from a provider's `interrupt()`, which the scheduler and teardown also call --
1658
+ * because a turn failed by a stalled stream or a dead provider process aborts
1659
+ * the same controller and is not a Stop. A Stop pressed with no turn running and no
1660
+ * prompt open records nothing (there is nothing for it to cancel), and a session with no
1661
+ * in-process permission manager has nothing to record on.
1662
+ * Cleared by `_clearMessageState`, which every turn end reaches.
1663
+ */
1664
+ markUserStopInFlight() {
1665
+ // A turn is running, or a prompt is still open (a stalled turn's query can
1666
+ // outlive its busy flag and raise one): either way there is something for
1667
+ // this Stop to cancel. Otherwise there is nothing to label.
1668
+ if (!this._isBusy && !this._permissions?.hasPendingPrompt?.()) return
1669
+ this._permissions?.markUserStopInFlight?.()
1670
+ }
1671
+
1672
+ /**
1673
+ * #7376: record that a Stop was requested during the turn that is running
1674
+ * now. A no-op when idle, so a Stop pressed between turns cannot leak into the
1675
+ * next one. Called by the providers whose `interrupt()` can be acknowledged by
1676
+ * a NORMAL `result` (claude-cli, claude-sdk) rather than only by a child exit
1677
+ * or a thrown abort; the flag is turn-scoped and reset by `_clearMessageState`.
1678
+ */
1679
+ _noteTurnStopRequested() {
1680
+ if (this._isBusy) this._stopRequestedThisTurn = true
1010
1681
  }
1011
1682
 
1012
1683
  /**
@@ -1069,6 +1740,9 @@ export class BaseSession extends EventEmitter {
1069
1740
  if (!ALLOWED_PERMISSION_MODE_IDS.has(mode)) {
1070
1741
  return false
1071
1742
  }
1743
+ if (!getProviderPermissionModeSupport(this.constructor, mode).supported) {
1744
+ return false
1745
+ }
1072
1746
  // 'auto' is the panic-button: a user mid-turn (i.e. _isBusy=true)
1073
1747
  // staring at a permission prompt should be able to flip to bypass and
1074
1748
  // have it actually take effect. The non-auto modes still defer until
@@ -1179,10 +1853,10 @@ export class BaseSession extends EventEmitter {
1179
1853
  * stored value changes and `false` for either invalid input or a
1180
1854
  * redundant set — same idempotent contract as `setPromptEvaluator`.
1181
1855
  *
1182
- * The compiled regex itself isn't stored: `shouldSkipEvaluator` owns
1856
+ * The compiled regex itself isn't stored: `shouldSkipEvaluatorAsync` owns
1183
1857
  * the compile cache (LRU keyed by source string) so a stale per-session
1184
1858
  * pattern won't pin a closure here. The validation done here is
1185
- * defence-in-depth — `shouldSkipEvaluator` also try/catches its own
1859
+ * defence-in-depth — `shouldSkipEvaluatorAsync` also try/catches its own
1186
1860
  * compile, so a session that somehow ends up with a bad source still
1187
1861
  * fails-open to default-only skip rules.
1188
1862
  *
@@ -1213,10 +1887,6 @@ export class BaseSession extends EventEmitter {
1213
1887
  return true
1214
1888
  }
1215
1889
 
1216
- /**
1217
- * Clear per-message state. Subclasses should call super._clearMessageState()
1218
- * and then clear their own additional state (plan mode, pending permissions, etc.).
1219
- */
1220
1890
  /**
1221
1891
  * Parse a JSONL line from a subprocess stdout.
1222
1892
  * Returns the parsed object or null if the line is empty or invalid JSON.
@@ -1309,22 +1979,46 @@ export class BaseSession extends EventEmitter {
1309
1979
  */
1310
1980
  _buildSystemPrompt() {
1311
1981
  const skillsText = typeof this._skillsText === 'string' ? this._skillsText : ''
1312
- // Order (#4660 + #3805): user preamble → chroxy hint → skills text.
1313
- // The user-authored preamble rides at the FRONT so it takes precedence
1314
- // over the canned chroxy hint and the skills bucket — those are
1315
- // chroxy-controlled context, the preamble is the user's voice.
1982
+ // Order (#7835 + #4660 + #3805): verified required project policy → user
1983
+ // preamble → chroxy hint → skills text. Required policy has its own budget
1984
+ // and cannot be displaced by optional/prunable context. The user-authored
1985
+ // preamble still precedes the canned hint and runtime-skills bucket.
1316
1986
  //
1317
1987
  // When BOTH the preamble is empty AND the chroxy hint is OFF, the
1318
1988
  // return value is byte-identical to pre-#3805 (skillsText only) so
1319
1989
  // existing users see no observable behaviour change. Each layer is
1320
1990
  // joined by `\n\n` so the model sees clean paragraph breaks.
1321
1991
  const parts = []
1992
+ if (this.projectInstructions) parts.push(this.projectInstructions)
1322
1993
  if (this.sessionPreamble) parts.push(this.sessionPreamble)
1323
1994
  if (this.chroxyContextHint) parts.push(CHROXY_CONTEXT_HINT_TEXT)
1324
1995
  if (skillsText) parts.push(skillsText)
1325
1996
  return parts.length === 0 ? '' : parts.join('\n\n')
1326
1997
  }
1327
1998
 
1999
+ _installProjectInstructionProjection(projection) {
2000
+ if (!projection) {
2001
+ this.projectInstructions = ''
2002
+ this._projectInstructionProjection = {
2003
+ status: 'unknown', enforcement: 'instructional', compilerVersion: '1', budgetBytes: 0, totalBytes: 0,
2004
+ sources: [], rules: [], includedRequiredRuleIds: [],
2005
+ }
2006
+ return
2007
+ }
2008
+ const bytes = Buffer.byteLength(projection.text, 'utf8')
2009
+ if (bytes !== projection.totalBytes || bytes > projection.budgetBytes
2010
+ || projection.budgetBytes > PROJECT_INSTRUCTION_BUDGET_BYTES) {
2011
+ throw new Error('Invalid project-instruction projection byte metadata')
2012
+ }
2013
+ this.projectInstructions = projection.text
2014
+ this._projectInstructionProjection = {
2015
+ status: 'delivered', enforcement: 'instructional', compilerVersion: projection.compilerVersion,
2016
+ budgetBytes: projection.budgetBytes, totalBytes: projection.totalBytes,
2017
+ sources: projection.sources, rules: projection.rules,
2018
+ includedRequiredRuleIds: projection.includedRequiredRuleIds,
2019
+ }
2020
+ }
2021
+
1328
2022
  /**
1329
2023
  * Return the formatted skills text for prepending to the first user
1330
2024
  * message (Codex, Gemini default; any provider when a skill declares
@@ -1406,6 +2100,78 @@ export class BaseSession extends EventEmitter {
1406
2100
  this._inFlightToolStarts.delete(toolUseId)
1407
2101
  }
1408
2102
 
2103
+ /**
2104
+ * #7346: attach the finalized tool input onto the in-flight tracking
2105
+ * entry created by `_trackToolStart`, so `_getTrackedToolInput` can
2106
+ * hand it back to `tool-result.js`'s `emitToolResults` when the
2107
+ * matching `tool_result` fires. No-op when the toolUseId isn't
2108
+ * tracked (already resolved/swept, or `_trackToolStart` was never
2109
+ * called for this provider — e.g. BYOK).
2110
+ *
2111
+ * #8135/#8136 (review on #7346): this is the ONE choke point both
2112
+ * providers' finalized-input capture flows through
2113
+ * (`cli-session.js`'s `_captureFinalizedToolInput`,
2114
+ * `sdk-session.js`'s `_handleToolUseBlock`), so it runs every input
2115
+ * through `sanitizeToolInput` (`redaction.js`, the same #6029 floor
2116
+ * `permission-manager.js`/`ws-permissions.js` already apply on the
2117
+ * permission-request path) BEFORE storing it — never the raw value.
2118
+ * That one call does double duty: it redacts secret-shaped values
2119
+ * (key-name AND value-shape passes, recursively) and caps the
2120
+ * serialized size to `MAX_INPUT_CHARS` (10KB, the existing broadcast
2121
+ * cap — falling back to a `{ _truncated, summary }` shape when the
2122
+ * whole object is oversized), so a 100KB+ `Write`/`Edit` input can
2123
+ * never reach `_getTrackedToolInput`, `tool_result`, or the persisted
2124
+ * `tool_start` history entry ungated. Every reader of this map
2125
+ * therefore gets an already-safe value for free — there is no second
2126
+ * place that needs to sanitize or cap.
2127
+ *
2128
+ * Returns the sanitized value (not just `undefined`) so a caller that
2129
+ * wants to deliver it somewhere else too (e.g. a single-shot
2130
+ * `tool_input_delta` for the in-flight view) doesn't need a redundant
2131
+ * `_getTrackedToolInput` round-trip.
2132
+ *
2133
+ * @param {string} toolUseId
2134
+ * @param {unknown} input - the finalized (fully parsed) tool input
2135
+ * @returns {unknown} the sanitized value that was stored (or `input`
2136
+ * unchanged if `toolUseId` wasn't tracked — still sanitized, just
2137
+ * not stored anywhere)
2138
+ */
2139
+ _recordToolInput(toolUseId, input) {
2140
+ const sanitized = sanitizeToolInput(input)
2141
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) return sanitized
2142
+ const entry = this._inFlightToolStarts.get(toolUseId)
2143
+ if (entry) {
2144
+ entry.input = sanitized
2145
+ // #8371: tell the owner of the history ring buffer right now, not at
2146
+ // result time. The `tool_start` entry was recorded with `input: null`
2147
+ // and a replay (session switch, dashboard reload) during a still-running
2148
+ // tool would otherwise show no INPUT until the result lands. Only for a
2149
+ // TRACKED id (BYOK never tracks, so its streamed partials never reach
2150
+ // here) and only the sanitised value -- never the raw input.
2151
+ if (sanitized !== null && sanitized !== undefined) {
2152
+ this.emit('tool_input_recorded', { toolUseId, input: sanitized })
2153
+ }
2154
+ }
2155
+ return sanitized
2156
+ }
2157
+
2158
+ /**
2159
+ * #7346: read back the finalized tool input recorded via
2160
+ * `_recordToolInput`, if any. Returns `undefined` when nothing was
2161
+ * recorded — either the toolUseId isn't tracked at all (BYOK never
2162
+ * calls `_trackToolStart`, so this is always `undefined` there and
2163
+ * `tool_result` stays exactly as it was) or `_recordToolInput` was
2164
+ * never called for it (parse failure / overflow discard on the CLI
2165
+ * path). Already sanitized/capped — see `_recordToolInput`.
2166
+ *
2167
+ * @param {string} toolUseId
2168
+ * @returns {unknown}
2169
+ */
2170
+ _getTrackedToolInput(toolUseId) {
2171
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) return undefined
2172
+ return this._inFlightToolStarts.get(toolUseId)?.input
2173
+ }
2174
+
1409
2175
  /**
1410
2176
  * #4628: sweep any tool_starts that never got their matching
1411
2177
  * tool_result and emit synthetic tool_result events for each.
@@ -1420,44 +2186,559 @@ export class BaseSession extends EventEmitter {
1420
2186
  * are diagnostic hints — the wire schema strips them on parse but
1421
2187
  * they stay grep-able on disk in the persisted history.
1422
2188
  *
2189
+ * #7376: when `reason` is a turn-TERMINATION reason (a permission-mode
2190
+ * switch, Stop, a crash, a watchdog — see `TURN_TERMINATION_REASONS`), the
2191
+ * tool did not fail, its turn was ended underneath it. The result then also
2192
+ * carries `terminatedReason` (the one diagnostic-adjacent field that IS on
2193
+ * the wire, `ServerToolResultSchema.terminatedReason`) and says so in its
2194
+ * text, so a client can render "cut off by the turn ending; check whether it took effect" instead of
2195
+ * the failure styling. Every other sweep reason (the natural turn end that
2196
+ * simply never saw a result) says only that the tool did not finish
2197
+ * (#8252) and carries no `terminatedReason`: those really are
2198
+ * indistinguishable from a failure.
2199
+ *
1423
2200
  * @param {string} reason — short identifier for the sweep cause
1424
2201
  * @returns {number} count of sweeps emitted
1425
2202
  */
1426
- _sweepUnresolvedToolStarts(reason = 'stream_completed_without_result') {
2203
+ _sweepUnresolvedToolStarts(reason = 'stream_completed_without_result', exempt = null, { completion } = {}) {
1427
2204
  if (this._inFlightToolStarts.size === 0) return 0
1428
- const count = this._inFlightToolStarts.size
1429
- for (const [toolUseId, entry] of this._inFlightToolStarts) {
2205
+ // #7376: a Stop the provider acknowledged with a NORMAL result reaches here
2206
+ // with a generic reason, because the path that ended the turn did not know a
2207
+ // Stop had been requested. The turn-scoped flag does, and the tools still
2208
+ // unresolved were cut off by it.
2209
+ //
2210
+ // ONLY on a normal completion -- the caller says so with
2211
+ // `completion: 'normal'`, and nothing else is inferred. A failure cleanup
2212
+ // (a query that threw, a child that died, a destroy) has already observed
2213
+ // its own outcome, and a Stop that lands while it is still awaiting
2214
+ // something (the SDK's container classification) must not relabel that
2215
+ // outcome as the user's doing. An explicit termination reason is never
2216
+ // overridden either.
2217
+ if (completion === 'normal' && this._stopRequestedThisTurn && !isTurnTerminationReason(reason)) {
2218
+ reason = 'user_stop'
2219
+ }
2220
+ let count = 0
2221
+ for (const [toolUseId] of [...this._inFlightToolStarts]) {
2222
+ // #7340: a confirmed-backgrounded subagent that has not reported back is
2223
+ // NOT an orphan -- it is running. Synthesising an `isError` result for it
2224
+ // would report a failure that did not happen and terminate its activity
2225
+ // node. Its `tool_start` stays in flight, to be swept by whichever turn
2226
+ // end or death path finally does complete it.
2227
+ if (exempt && exempt.has(toolUseId)) continue
2228
+ count++
2229
+ this._inFlightToolStarts.delete(toolUseId)
2230
+ const terminated = isTurnTerminationReason(reason)
1430
2231
  this.emit('tool_result', {
1431
2232
  toolUseId,
1432
- result: `Tool ${entry.tool} did not emit a result before the turn ended (reason: ${reason}). Chroxy synthesized this result to clear the stale activeTools entry.`,
2233
+ // #8252: plain words only. The sweep reason is a slug and the fact that
2234
+ // the daemon fabricated this result is bookkeeping, so neither is in the
2235
+ // text a person reads. They stay on the in-process event as `reason` and
2236
+ // `synthetic` for listeners on the session; the wire
2237
+ // (`event-normalizer.js`) and the persisted history
2238
+ // (`session-message-history.js`) carry only `isError` and
2239
+ // `terminatedReason`, so a non-terminated sweep's slug does not leave the
2240
+ // process. The tool's name is already on the row.
2241
+ result: terminated
2242
+ ? describeTurnTermination(reason).summary
2243
+ : UNFINISHED_TOOL_RESULT_TEXT,
1433
2244
  truncated: false,
1434
2245
  synthetic: true,
1435
2246
  interrupted: true,
1436
2247
  isError: true,
1437
2248
  reason,
2249
+ ...(terminated ? { terminatedReason: reason } : {}),
1438
2250
  })
1439
2251
  }
1440
- this._inFlightToolStarts.clear()
1441
2252
  return count
1442
2253
  }
1443
2254
 
1444
2255
  /**
1445
- * #4628: emit `result` after sweeping any in-flight tool_starts. All
1446
- * provider sessions should route through this rather than calling
1447
- * `this.emit('result', ...)` directly, so orphan tool_starts get
1448
- * paired with a synthetic tool_result BEFORE the result fires (and
1449
- * BEFORE state is persisted, since session-message-history listens
1450
- * for both events).
2256
+ * #4628: emit `result` after sweeping any in-flight tool_starts. Provider
2257
+ * sessions should route through this WHEN they need the orphan sweep, so
2258
+ * orphan tool_starts get paired with a synthetic tool_result BEFORE the
2259
+ * result fires (and BEFORE state is persisted, since session-message-history
2260
+ * listens for both events). Some providers deliberately emit `this.emit(
2261
+ * 'result', ...)` directly (they don't want the sweep); the queueLength stamp
2262
+ * is applied to those too via the emit() override below.
1451
2263
  *
1452
2264
  * @param {object} payload — the result event payload ({cost, duration, usage, sessionId})
1453
2265
  * @param {string} [sweepReason] — optional override for the sweep reason
2266
+ * @param {{ completion?: 'normal' }} [opts] — #7376: `completion: 'normal'`
2267
+ * says the turn ended with the provider's own `result`; see
2268
+ * `_sweepUnresolvedToolStarts` for what that permits.
1454
2269
  */
1455
- _emitResult(payload, sweepReason = 'stream_completed_without_result') {
1456
- this._sweepUnresolvedToolStarts(sweepReason)
2270
+ _emitResult(payload, sweepReason = 'stream_completed_without_result', opts = {}) {
2271
+ this._sweepUnresolvedToolStarts(sweepReason, null, opts)
2272
+ // queueLength is stamped centrally in the emit() override below (#6627/#6706).
1457
2273
  this.emit('result', payload)
1458
2274
  }
1459
2275
 
1460
- _clearMessageState() {
2276
+ /**
2277
+ * #6627 / #6706: single choke point for the turn-boundary queue-length stamp.
2278
+ *
2279
+ * Every `result` event carries the session's authoritative outgoing-queue
2280
+ * length so clients reconcile a stale "Queued" bubble on a turn boundary — a
2281
+ * dropped/late `message_dequeued` no longer leaves a stale badge until the
2282
+ * next queue event. The count is pre-flush (the imminent dequeue emits its own
2283
+ * event); `reconcileQueueLength` only trims confirmed orphans, never a live
2284
+ * entry, so it is safe to stamp on every result.
2285
+ *
2286
+ * Stamping here (rather than at each call site) is deliberate: `_emitResult`
2287
+ * is NOT the only emitter — several providers emit `result` directly (CLI /
2288
+ * exec-codex / gemini / byok / stall fallbacks) because they don't want the
2289
+ * orphan sweep, and the #6705 review missed 3 of the 8 sites. Centralizing on
2290
+ * the one method every `result` passes through makes the self-heal uniform
2291
+ * and un-forgettable for future emit sites too.
2292
+ *
2293
+ * Idempotent: a payload that already carries `queueLength` (none today, but a
2294
+ * caller could pre-stamp) is left untouched. `_outgoingQueue` is a BaseSession
2295
+ * field initialized before any subclass method can run; the `?` guard is
2296
+ * belt-and-braces and yields 0 for the should-never-happen case of a subclass
2297
+ * emitting `result` inside `super()` before the field is set.
2298
+ *
2299
+ * @param {string} event
2300
+ * @param {...any} args
2301
+ * @returns {boolean} whether the event had listeners (EventEmitter contract)
2302
+ */
2303
+ emit(event, ...args) {
2304
+ if (PROVIDER_ACTIVITY_EVENT_SET.has(event)) this.noteProviderActivity()
2305
+ if (event === 'stopped') {
2306
+ // #8461: this Stop was already confirmed in place of the chip; not twice.
2307
+ if (this._stopAckedByResult) {
2308
+ this._stopAckedByResult = false
2309
+ return false
2310
+ }
2311
+ this._stoppedSinceStopRequest = true
2312
+ }
2313
+ let ackStop = false
2314
+ if (event === 'result') {
2315
+ let payload = args[0]
2316
+ if (payload && typeof payload === 'object' && payload.queueLength === undefined) {
2317
+ payload = { ...payload, queueLength: this._outgoingQueue ? this._outgoingQueue.length : 0 }
2318
+ }
2319
+ payload = normalizeResultDuration(payload)
2320
+ // #7326: the wire carries a closed vocabulary. Anything else a provider
2321
+ // puts on `turnOutcome` is dropped here rather than left to fail the
2322
+ // client's parse of the whole `result` frame.
2323
+ if (payload && typeof payload === 'object' && payload.turnOutcome !== undefined && !isTurnOutcome(payload.turnOutcome)) {
2324
+ const { turnOutcome: _dropped, ...rest } = payload
2325
+ payload = rest
2326
+ }
2327
+ // #8461: a requested Stop (the user's, or the scheduler's / orchestration
2328
+ // watchdog's, which also call `interrupt()`) is acknowledged by
2329
+ // `session_stopped` on every provider whose `interrupt()` ends the turn with
2330
+ // a `stopped` event (ACP, Codex, Gemini, ...). claude-sdk and claude-cli can
2331
+ // instead answer it with a NORMAL `result` carrying `terminal_reason:
2332
+ // aborted_*`, which maps to `stopped`; and then the SDK's catch branch (the
2333
+ // `stopped` emit) never runs. Left alone, only those two providers would
2334
+ // show a "Stopped" chip for a Stop that was asked for. The chip is for a turn
2335
+ // that ended UNDER the caller, so it is dropped and the quiet `stopped`
2336
+ // confirmation is sent in its place (once per Stop request, see
2337
+ // `_stoppedSinceStopRequest`). An agent that cancelled on its own (ACP
2338
+ // `cancelled`) keeps its chip.
2339
+ this._stopAckedByResult = false
2340
+ // #7072: a result whose outcome is `stopped` is terminal but NOT a success,
2341
+ // and an orchestration TurnDriver hears nothing else for the turn -- the
2342
+ // `stopped` that follows it (acknowledgement below, or a provider's own) lands
2343
+ // after the driver has already settled. Mark it here, before the chip is
2344
+ // dropped for a requested Stop, so every provider that maps an abort onto a
2345
+ // result gets it. Internal only: event-normalizer whitelists the wire fields.
2346
+ if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped' && payload.interrupted !== true) {
2347
+ payload = { ...payload, interrupted: true }
2348
+ }
2349
+ if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped' && this._stopRequestedThisTurn) {
2350
+ const { turnOutcome: _userStop, ...rest } = payload
2351
+ payload = rest
2352
+ ackStop = !this._stoppedSinceStopRequest
2353
+ }
2354
+ // #7326: a marked outcome (anything but `completed`) becomes a chip in the
2355
+ // transcript, and the chip needs an identity that the live `result` frame
2356
+ // and the history entry replayed later AGREE on -- a `result` has no id, and
2357
+ // without one a reconnect that replays the turn the client already watched
2358
+ // would add a second chip. The timestamp is stamped ONCE, here, and both
2359
+ // the event normalizer and the history ring read it off this payload.
2360
+ if (payload && typeof payload === 'object' && isTurnOutcome(payload.turnOutcome) && payload.turnOutcome !== 'completed'
2361
+ && typeof payload.timestamp !== 'number') {
2362
+ payload = { ...payload, timestamp: Date.now() }
2363
+ }
2364
+ if (payload !== args[0]) args[0] = payload
2365
+ }
2366
+ const delivered = super.emit(event, ...args)
2367
+ if (ackStop) {
2368
+ this._stoppedSinceStopRequest = true
2369
+ this._stopAckedByResult = true
2370
+ super.emit('stopped', {})
2371
+ }
2372
+ return delivered
2373
+ }
2374
+
2375
+ /**
2376
+ * How many permission requests are waiting on a human for this session,
2377
+ * across both routes: the hook-routed ids (CLI / TUI, #2831) and the
2378
+ * in-process PermissionManager's map that `wirePermissionManager` installs
2379
+ * as `_pendingPermissions` (SDK / BYOK / Codex).
2380
+ *
2381
+ * A read-only count for callers outside the session — the idle-only
2382
+ * auto-deploy probe (#8324) — so they never reach into either private field.
2383
+ *
2384
+ * @returns {number}
2385
+ */
2386
+ getPendingPermissionCount() {
2387
+ const inProcess = this._pendingPermissions instanceof Map ? this._pendingPermissions.size : 0
2388
+ return this._pendingPermissionIds.size + inProcess
2389
+ }
2390
+
2391
+ /**
2392
+ * #8743: record that the provider just produced output. The emit() override
2393
+ * calls it for every PROVIDER_ACTIVITY_EVENTS event; a provider calls it
2394
+ * directly for input that maps to no event (a Codex sub-agent's notifications,
2395
+ * or a straggler from a turn codex already ended), which is exactly the
2396
+ * activity the turn bookkeeping cannot see.
2397
+ */
2398
+ noteProviderActivity() {
2399
+ this._providerActivityAtMs = this._providerActivityClock()
2400
+ }
2401
+
2402
+ /**
2403
+ * #8743: the clock `noteProviderActivity` stamps with. Monotonic, so a wall
2404
+ * clock step cannot make recent activity look old. A test replaces it on the
2405
+ * instance to move time.
2406
+ * @returns {number}
2407
+ */
2408
+ _providerActivityClock() {
2409
+ return Math.trunc(performance.now())
2410
+ }
2411
+
2412
+ /**
2413
+ * #8743: how long ago the provider last produced output, in ms, or null when
2414
+ * it has not since this session object was created. The idle-only auto-deploy
2415
+ * holds off a restart while this is recent (daemon-idle-state.js).
2416
+ * @returns {number|null}
2417
+ */
2418
+ get providerActivityAgeMs() {
2419
+ if (this._providerActivityAtMs === null) return null
2420
+ return Math.max(0, this._providerActivityClock() - this._providerActivityAtMs)
2421
+ }
2422
+
2423
+ /**
2424
+ * Work a daemon restart would lose that `isBusy` does not report (#8324).
2425
+ *
2426
+ * `isBusy` is "a turn is running or a background shell is tracked". A restart
2427
+ * can also cut off a background agent that outlived its turn (`_activeAgents`
2428
+ * keeps it after `_clearMessageState({ turnEndedCleanly: true })`) and input
2429
+ * the session has accepted but not yet dispatched (`_outgoingQueue`, which
2430
+ * every provider shares for mid-turn sends). Subclasses with a queue or an
2431
+ * input path of their own extend this list; they call `super` first.
2432
+ *
2433
+ * Fail-closed contract for callers: an empty array means nothing blocks a
2434
+ * restart, so an override must never return `[]` merely because it could not
2435
+ * check — throw instead.
2436
+ *
2437
+ * @returns {string[]} human-readable reasons; empty = nothing blocks a restart
2438
+ */
2439
+ getRestartBlockers() {
2440
+ const reasons = []
2441
+ const agents = this._activeAgents.size
2442
+ if (agents > 0) reasons.push(`${agents} active background agent(s)`)
2443
+ const queued = this._outgoingQueue.length
2444
+ if (queued > 0) reasons.push(`${queued} queued message(s) not yet dispatched`)
2445
+ return reasons
2446
+ }
2447
+
2448
+ /**
2449
+ * A hook-routed permission request belonging to this session is outstanding.
2450
+ * Called by ws-permissions when the hook's POST /permission is parked (#2831).
2451
+ */
2452
+ notifyPermissionPending(requestId) {
2453
+ if (!requestId || this._pendingPermissionIds.has(requestId)) return
2454
+ this._pendingPermissionIds.add(requestId)
2455
+ if (this._pendingPermissionIds.size === 1) this._onFirstPermissionPending()
2456
+ }
2457
+
2458
+ /**
2459
+ * A hook-routed permission resolved (allow / deny / expired). Called by
2460
+ * ws-permissions' shared cleanup on every resolution path.
2461
+ */
2462
+ notifyPermissionResolved(requestId) {
2463
+ if (!requestId || !this._pendingPermissionIds.has(requestId)) return
2464
+ this._pendingPermissionIds.delete(requestId)
2465
+ if (this._pendingPermissionIds.size === 0) this._onLastPermissionResolved()
2466
+ }
2467
+
2468
+ /**
2469
+ * Emit `permission_expired` for every prompt this session is still blocked on,
2470
+ * then drop the bookkeeping (#2831, #7375, generalised in #7382).
2471
+ *
2472
+ * A prompt outlives its turn on BOTH sides and neither says so: the client
2473
+ * card stays live until its own expiry, and the daemon's HTTP entry is not
2474
+ * released by the child dying, because killing the child does not signal the
2475
+ * hook's `curl` grandchild. Emitting here drives both — the clients retire the
2476
+ * card, and #7381's `release_permission` after-effect releases the daemon
2477
+ * entry so a reconnect cannot resurrect it.
2478
+ *
2479
+ * Call it from the provider's turn-end FUNNEL, not from hand-enumerated death
2480
+ * sites. Enumerating by hand is what missed the plain `result` path and the
2481
+ * interrupt-safety timeout in #7375.
2482
+ *
2483
+ * @param {string} message Reason forwarded on the wire (clients log it; the
2484
+ * user-visible copy is fixed client-side). Falsy or empty is coerced to a
2485
+ * generic reason — the wire schema declares `message: z.string()`, so an
2486
+ * empty one would fail validation at the client.
2487
+ */
2488
+ _expirePendingPermissions(message) {
2489
+ if (this._pendingPermissionIds.size === 0) return
2490
+ // The doc below used to say `message` must be non-empty "because the wire
2491
+ // schema requires it" and then not enforce it — a comment describing a
2492
+ // stronger guarantee than the code delivers, which is the defect class this
2493
+ // whole change belongs to. ServerPermissionExpiredSchema declares
2494
+ // `message: z.string()`, so a caller passing '' or undefined would emit a
2495
+ // frame that fails validation at the client. Default rather than throw: the
2496
+ // callers are turn-teardown paths, and taking a session down over a missing
2497
+ // log string would be a worse failure than a generic one.
2498
+ const reason = typeof message === 'string' && message.length > 0
2499
+ ? message
2500
+ : 'Permission request expired (the turn it belonged to ended)'
2501
+ for (const requestId of this._pendingPermissionIds) {
2502
+ this.emit('permission_expired', { requestId, message: reason })
2503
+ }
2504
+ this._pendingPermissionIds.clear()
2505
+ this._onPendingPermissionsAbandoned()
2506
+ }
2507
+
2508
+ /**
2509
+ * Timer hooks for the pending-permission lifecycle. No-ops by default: the
2510
+ * bookkeeping above is provider-agnostic, but "don't time out while the user
2511
+ * is being asked" is not — CliSession pauses its inactivity trio, while
2512
+ * ClaudeTuiSession suspends only its silence backstops (for these prompts
2513
+ * and, through its own mechanism, for a pending AskUserQuestion) and
2514
+ * deliberately keeps its hard cap armed.
2515
+ *
2516
+ * Kept as THREE hooks rather than one because the abandon path must NOT
2517
+ * re-arm: the turn it belonged to is over. Collapsing them re-creates the
2518
+ * #7375 regression where a cleared pause left the safety timers wedged.
2519
+ */
2520
+ _onFirstPermissionPending() {}
2521
+ _onLastPermissionResolved() {}
2522
+ _onPendingPermissionsAbandoned() {}
2523
+
2524
+ /**
2525
+ * #7340: finalize a tracked subagent by its `tool_use_id` -- the ONE
2526
+ * implementation of "this agent is done". Drops it from `_activeAgents` and
2527
+ * balances its `agent_spawned` with a matching `agent_completed`.
2528
+ *
2529
+ * Idempotent (guarded on `has`), which is what lets an optimistic finalize
2530
+ * and the provider's natural terminal signal both call it without emitting a
2531
+ * duplicate completion.
2532
+ *
2533
+ * This matters more since backgrounded agents stopped being swept at turn
2534
+ * end: the sweep used to be a backstop that eventually cleared everything, so
2535
+ * a missed finalize was invisible. It is now the ONLY way a backgrounded
2536
+ * agent clears, and a provider that tracks a background spawn without wiring
2537
+ * a terminal signal leaves the session claiming to be working forever.
2538
+ *
2539
+ * @param {unknown} toolUseId
2540
+ * @param {{ reason?: string }} [opts]
2541
+ * @protected
2542
+ */
2543
+ _completeAgent(toolUseId, { reason } = {}) {
2544
+ if (typeof toolUseId !== 'string' || !toolUseId) return
2545
+ if (!this._activeAgents.has(toolUseId)) return
2546
+ this._activeAgents.delete(toolUseId)
2547
+ // #7396: `reason` is present only when the session ENDED the agent itself
2548
+ // (a watchdog gave up waiting for the provider's signal) rather than the
2549
+ // provider reporting it finished. In-process only: the wire message is built
2550
+ // field by field in event-normalizer and carries just the id.
2551
+ this.emit('agent_completed', reason ? { toolUseId, reason } : { toolUseId })
2552
+ }
2553
+
2554
+ /**
2555
+ * #7340: complete tracked subagents in bulk and report which ones survived.
2556
+ *
2557
+ * The ONE implementation of "drain the agent map", shared by the turn-end
2558
+ * sweep and by the provider-death sites that cannot reach that sweep. Emits a
2559
+ * balancing `agent_completed` for every agent it drops, so a client's badge
2560
+ * clears whichever route got here.
2561
+ *
2562
+ * `exempt` is the set of ids to spare, computed ONCE by `_clearMessageState`
2563
+ * and shared with the orphan sweep so the two cannot disagree about what is
2564
+ * still running. Default empty -- a bare call is a total drain, which is what
2565
+ * every death path wants.
2566
+ *
2567
+ * Keyed by the MAP KEY, not `agent.toolUseId`: a record whose field has
2568
+ * drifted from its key would otherwise leak and complete the wrong id.
2569
+ *
2570
+ * Every agent it completes emits `agent_completed`, which the registry turns
2571
+ * into a node termination AND a clearing of that agent's outlives-turn mark
2572
+ * -- which is what lets `ActivityRegistry.reset()` simply read the marks
2573
+ * afterwards instead of being handed a second copy of this predicate.
2574
+ *
2575
+ * @param {{ exempt?: Set<string> }} [opts]
2576
+ * @protected
2577
+ */
2578
+ _completeAgents({ exempt = null } = {}) {
2579
+ for (const toolUseId of [...this._activeAgents.keys()]) {
2580
+ if (exempt && exempt.has(toolUseId)) continue
2581
+ this._activeAgents.delete(toolUseId)
2582
+ this.emit('agent_completed', { toolUseId })
2583
+ }
2584
+ }
2585
+
2586
+ /**
2587
+ * #7340: record a spawned subagent and announce it. Shared by every provider
2588
+ * that reads the Agent/Task tool off a Claude Code stream, so the record
2589
+ * shape (notably `backgroundConfirmed`, which decides whether the turn-end
2590
+ * sweep may complete it) cannot drift between them.
2591
+ *
2592
+ * Re-registering an already-tracked id UPGRADES the record rather than
2593
+ * replacing it, and re-emits nothing. That is the `task_started` case: the
2594
+ * tool_use block arrives first and carries `run_in_background`, then
2595
+ * `task_started` arrives with `is_backgrounded`. Whichever order they land
2596
+ * in, exactly one `agent_spawned` is emitted.
2597
+ *
2598
+ * TWO fields, because the two producers do not carry the same authority and
2599
+ * collapsing them is what would strand an agent:
2600
+ *
2601
+ * - `background` -- best-known value. The tool input's `run_in_background`
2602
+ * is the model's REQUEST; `task_started`'s `is_backgrounded` is what the
2603
+ * provider actually did. (`is_backgrounded` is ABSENT on a foreground
2604
+ * spawn, not `false`, so every producer compares with a strict `=== true`
2605
+ * -- that derivation is what the parser tests pin.)
2606
+ * - `backgroundConfirmed` -- set ONLY from `task_started` (`authoritative:
2607
+ * true`). This, not `background`, is what exempts an agent from the
2608
+ * turn-end sweep, and the reason is a liveness one rather than a
2609
+ * correctness one: `task_notification` is the ONLY signal that clears a
2610
+ * backgrounded agent, and a provider build that emits no task lifecycle
2611
+ * messages at all emits neither. `task_started` having arrived is
2612
+ * therefore the evidence that a terminal signal CAN arrive. Exempting on
2613
+ * the model's unconfirmed request would pin such a session as "working"
2614
+ * until the provider dies -- which #7340 names as the worse failure.
2615
+ * (`cancelActivity` already feature-detects those builds the same way.)
2616
+ *
2617
+ * The upgrade is asymmetric for the same reason. A non-authoritative signal
2618
+ * may only raise `background` (`false` never overwrites `true`), because the
2619
+ * two producers can land in either order and the tool input carries no news
2620
+ * when it disagrees. An authoritative one OVERWRITES in both directions --
2621
+ * `task_started` is the provider's own account and must be able to correct
2622
+ * the model's request DOWNWARD, or an agent the model asked to background
2623
+ * and the provider ran in the foreground is exempted from the sweep it needs.
2624
+ *
2625
+ * @param {{ toolUseId: string, description?: string, background?: boolean, authoritative?: boolean, startedAt?: number }} info
2626
+ * @protected
2627
+ */
2628
+ _trackAgent({ toolUseId, description = 'Background task', background = false, authoritative = false, startedAt = Date.now() } = {}) {
2629
+ if (typeof toolUseId !== 'string' || !toolUseId) return
2630
+ const existing = this._activeAgents.get(toolUseId)
2631
+ if (existing) {
2632
+ if (authoritative === true) {
2633
+ existing.background = background === true
2634
+ existing.backgroundConfirmed = background === true
2635
+ // #7340: the registry is TOLD, never left to re-derive. This is the
2636
+ // upgrade path -- `task_started` landing after the tool_use block --
2637
+ // and it emits no event, so without this call the activity node would
2638
+ // never learn that it outlives its turn.
2639
+ this._activity.setAgentOutlivesTurn(toolUseId, existing.backgroundConfirmed)
2640
+ } else if (background === true) {
2641
+ existing.background = true
2642
+ }
2643
+ return
2644
+ }
2645
+ // Clamp HERE, not in each caller. `task_started`'s `description` is
2646
+ // provider-supplied and reaches the wire verbatim via `agent_spawned`;
2647
+ // only the tool-input path was clamped before, so the second producer
2648
+ // #7340 added would have shipped an unbounded field (the wire schema
2649
+ // declares `description: z.string().optional()` with no max, so nothing
2650
+ // downstream would have caught it either).
2651
+ const agentInfo = {
2652
+ toolUseId,
2653
+ description: String(description).slice(0, AGENT_DESCRIPTION_MAX),
2654
+ startedAt,
2655
+ background: background === true,
2656
+ backgroundConfirmed: authoritative === true && background === true,
2657
+ }
2658
+ this._activeAgents.set(toolUseId, agentInfo)
2659
+ this.emit('agent_spawned', agentInfo)
2660
+ // #7340: after the spawn, so the node exists to be marked. The other
2661
+ // arrival order (`task_started` first) is handled by the upgrade above.
2662
+ if (agentInfo.backgroundConfirmed) this._activity.setAgentOutlivesTurn(toolUseId, true)
2663
+ }
2664
+
2665
+ /**
2666
+ * #7340 / #7396: the subagents that outlive a turn end -- `null` (nothing
2667
+ * survives, a total drain) unless the provider itself reported the turn over.
2668
+ *
2669
+ * The ONE implementation of the survival predicate, shared by
2670
+ * `_clearMessageState` and by providers whose turn end does not run through it
2671
+ * (claude-tui's Stop-hook path). A second copy of "backgroundConfirmed and the
2672
+ * turn ended cleanly" is how two providers come to disagree about what
2673
+ * "survives" means. Opt-IN for the same reason `_clearMessageState`'s
2674
+ * `turnEndedCleanly` is: a caller that forgets to pass it gets the sweep.
2675
+ *
2676
+ * @param {boolean} turnEndedCleanly
2677
+ * @returns {Set<string> | null}
2678
+ * @protected
2679
+ */
2680
+ _survivingAgentIds(turnEndedCleanly) {
2681
+ if (turnEndedCleanly !== true) return null
2682
+ return new Set(
2683
+ [...this._activeAgents]
2684
+ .filter(([, agent]) => agent?.backgroundConfirmed === true)
2685
+ .map(([toolUseId]) => toolUseId),
2686
+ )
2687
+ }
2688
+
2689
+ /**
2690
+ * Clear per-message state at the end of a turn.
2691
+ *
2692
+ * @param {{ turnEndedCleanly?: boolean }} [opts]
2693
+ * `turnEndedCleanly` says the PROVIDER IS STILL ALIVE and reported the turn
2694
+ * over itself -- the stream-json `result` message, and nothing else. It is
2695
+ * the only thing that permits a confirmed-backgrounded subagent to survive
2696
+ * the sweep below (#7340).
2697
+ *
2698
+ * It is opt-IN, and that direction is the whole safety argument. Fourteen
2699
+ * call sites reach this method and all but two are a provider that DIED --
2700
+ * Stop/SIGINT, a child crash, `_killAndRespawn`, the SDK hard timeout,
2701
+ * stream-stall recovery, `interrupt()`, `destroy()`, a failed stdin write.
2702
+ * `task_notification` can never arrive on any of them, so an agent exempted
2703
+ * there is stranded and the session claims to be working for the rest of
2704
+ * the daemon's life. Defaulting to the sweep means a call site nobody
2705
+ * updated -- including a death path added years from now -- inherits the
2706
+ * RECOVERABLE failure (a badge cleared early) rather than the unrecoverable
2707
+ * one. #7340 names stuck-busy as the worse of the two, and it is.
2708
+ *
2709
+ * Subclasses that override this MUST forward the opts to `super`. One that
2710
+ * drops them fails safe (it sweeps), which is why the forwarding is a
2711
+ * correctness nicety here rather than a hazard.
2712
+ *
2713
+ * @param {{ turnEndedCleanly?: boolean, terminatedReason?: string, completion?: 'normal' }} [opts]
2714
+ * `completion: 'normal'` (#7376) says the turn ended with the provider's own
2715
+ * `result`. Only then may a Stop requested during the turn tag the tools it
2716
+ * left unresolved as `user_stop`: every other caller is a failure or teardown
2717
+ * path that has already observed its own outcome, and keeps it.
2718
+ *
2719
+ * `terminatedReason` (#7376) is WHY the turn is being ended underneath
2720
+ * whatever tool is still in flight -- a `TURN_TERMINATION_REASONS` value
2721
+ * (`permission_mode_switch`, `user_stop`, `process_exit`, ...). It becomes
2722
+ * the orphan sweep's reason, so the synthetic `tool_result` of each such
2723
+ * tool says "the turn was terminated" rather than looking like a failed
2724
+ * command. The CALLER supplies it, never this method: it is shared by every
2725
+ * death path (and Stop, where the user already knows why), so inferring it
2726
+ * here would mislabel. Omitted on the paths that have no considered cause --
2727
+ * those keep the generic `message_state_cleared` sweep.
2728
+ */
2729
+ _clearMessageState({ turnEndedCleanly = false, terminatedReason, completion } = {}) {
2730
+ // #7382 (review): expire HERE, so inheriting the bookkeeping also inherits
2731
+ // the BEHAVIOUR. Hoisting the API alone bought a new provider the methods
2732
+ // and none of the wiring — and the roster guard, which only checked that
2733
+ // the methods existed, passed for a provider that never called them. A
2734
+ // check that passes for everything is #7273's shape.
2735
+ //
2736
+ // Idempotent (no-op on an empty set), so providers that already expired at
2737
+ // an earlier point in their teardown are unaffected.
2738
+ this._expirePendingPermissions('Permission request expired (the turn it belonged to ended before it was answered)')
2739
+ // #8430: a user Stop belongs to the turn it was pressed on. Every turn end,
2740
+ // abort and failure included, reaches here, so the next turn starts clear.
2741
+ this._permissions?.clearUserStopInFlight?.()
1461
2742
  this._isBusy = false
1462
2743
  this._currentMessageId = null
1463
2744
 
@@ -1478,15 +2759,34 @@ export class BaseSession extends EventEmitter {
1478
2759
  // with a synthetic tool_result rather than silently dropped — so
1479
2760
  // the dashboard's activeTools clears whether result fires next or
1480
2761
  // never fires at all.
1481
- this._sweepUnresolvedToolStarts('message_state_cleared')
1482
-
1483
- // Emit completions for any tracked agents so the app clears badges
1484
- if (this._activeAgents.size > 0) {
1485
- for (const agent of this._activeAgents.values()) {
1486
- this.emit('agent_completed', { toolUseId: agent.toolUseId })
1487
- }
1488
- this._activeAgents.clear()
1489
- }
2762
+ // #7340: the ids that will outlive this turn, computed ONCE and shared by
2763
+ // all three sweeps below so they cannot disagree. Empty on every
2764
+ // provider-death path, which is what makes those a total drain.
2765
+ //
2766
+ // Computed BEFORE the orphan sweep, and that ordering is load-bearing: the
2767
+ // sweep fabricates a `tool_result` with `isError: true` for every
2768
+ // unresolved `tool_start`, and a backgrounded subagent that has not
2769
+ // reported back yet looks exactly like an orphan. Sweeping it told the
2770
+ // client the subagent had failed -- while it was running fine -- and ended
2771
+ // its activity node on the way past.
2772
+ const survivingAgents = this._survivingAgentIds(turnEndedCleanly)
2773
+
2774
+ this._sweepUnresolvedToolStarts(
2775
+ isTurnTerminationReason(terminatedReason) ? terminatedReason : 'message_state_cleared',
2776
+ survivingAgents,
2777
+ { completion },
2778
+ )
2779
+ // #7376: the turn is over; a Stop requested during it must not tag the next.
2780
+ this._stopRequestedThisTurn = false
2781
+
2782
+ // #7340: complete the tracked subagents this turn end owns, and no more.
2783
+ // A confirmed-backgrounded subagent deliberately outlives its turn, so
2784
+ // completing it here would report finished work that is still running --
2785
+ // which is the bug #7340 was filed for. It survives ONLY when the provider
2786
+ // itself said the turn ended (see `turnEndedCleanly` above); on every death
2787
+ // path the sweep stays total, because the signal that would clear it later
2788
+ // can no longer arrive.
2789
+ this._completeAgents({ exempt: survivingAgents })
1490
2790
 
1491
2791
  // #5160: turn-end reconciliation for the activity registry. Ends any
1492
2792
  // tool/agent/blocked node still marked running/blocked (orphans the
@@ -1495,6 +2795,18 @@ export class BaseSession extends EventEmitter {
1495
2795
  // terminate their nodes first; reset() is the belt-and-braces sweep for
1496
2796
  // anything the canonical signals didn't clear. Shell nodes survive
1497
2797
  // turn-end (#4307) and clear via background_work_changed.
2798
+ //
2799
+ // #7340: an agent that survived the sweep must survive `reset()` too, or
2800
+ // the two surfaces disagree -- AgentMonitorPanel says running while the
2801
+ // Control Room tree says done, and `cancelActivity` answers `not-found`
2802
+ // for the entire time the subagent runs. #4307 set this precedent one
2803
+ // branch above for shells, for the same reason.
2804
+ //
2805
+ // No argument: the registry reads its own outlives-turn marks, and
2806
+ // `_completeAgents` above has just cleared the mark of every agent it
2807
+ // completed (via `agent_completed`). So the set it spares is exactly the
2808
+ // set that survived here -- by construction rather than by a second copy
2809
+ // of the predicate.
1498
2810
  this._activity.reset()
1499
2811
 
1500
2812
  if (this._resultTimeout) {