@chroxy/server 0.10.0

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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,1773 @@
1
+ import { query } from '@anthropic-ai/claude-agent-sdk'
2
+ import { join } from 'path'
3
+ import { homedir } from 'os'
4
+ import { updateModels, saveModelsCache, updateContextWindow, getModels, ALLOWED_MODEL_IDS } from './models.js'
5
+ import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
6
+ import { BaseSession, buildBaseSessionOpts } from './base-session.js'
7
+ import { buildContentBlocks } from './content-blocks.js'
8
+ import { MessageTransformPipeline } from './message-transform.js'
9
+ import { emitToolResults } from './tool-result.js'
10
+ import {
11
+ parseBackgroundShellId,
12
+ parseBackgroundShellOutputPath,
13
+ isRunInBackgroundInput,
14
+ parseBashOutputShellId,
15
+ } from './background-shells.js'
16
+ import { buildToolStartData, extractToolInputSemantics } from './claude-stream-parser.js'
17
+ import { createLogger, loggerForSession } from './logger.js'
18
+ import { PermissionManager, wirePermissionManager } from './permission-manager.js'
19
+ import { formatBytes } from './utils/format-bytes.js'
20
+ import { formatIdleDuration } from './session-timeout-manager.js'
21
+ import { detectThinkingKeyword } from './detect-thinking-keyword.js'
22
+ import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
23
+
24
+ const log = createLogger('sdk')
25
+
26
+ /**
27
+ * Manages a Claude Code session using the Agent SDK.
28
+ *
29
+ * Same EventEmitter interface as CliSession so SessionManager and WsServer
30
+ * work identically regardless of which session type is in use.
31
+ *
32
+ * Key advantages over CliSession:
33
+ * - In-process permission handling via canUseTool (no HTTP hook pipeline)
34
+ * - setModel/setPermissionMode work live without process restart
35
+ * - One query() call per user message, SDK manages conversation state
36
+ *
37
+ * Events emitted (identical to CliSession):
38
+ * ready { sessionId, model, tools }
39
+ * stream_start { messageId }
40
+ * stream_delta { messageId, delta }
41
+ * stream_end { messageId }
42
+ * message { type, content, timestamp }
43
+ * tool_start { messageId, tool, input }
44
+ * result { cost, duration, usage, sessionId }
45
+ * error { message }
46
+ * permission_request { requestId, tool, description, input }
47
+ * user_question { toolUseId, questions }
48
+ * agent_spawned { toolUseId, description, startedAt }
49
+ * agent_completed { toolUseId }
50
+ * tool_result { toolUseId, result, truncated }
51
+ */
52
+
53
+ // Default max accumulated size for tool_use input (~256KB)
54
+ const DEFAULT_MAX_TOOL_INPUT_LENGTH = 262144
55
+ // #5936 (epic #5935): the mid-turn follow-up queue moved to BaseSession's shared
56
+ // `_outgoingQueue` (capped at OUTGOING_QUEUE_MAX), so both SDK and CLI now QUEUE
57
+ // send-while-busy follow-ups and flush them FIFO on `result` — replacing the
58
+ // SDK's old `_pendingInput` (cap 3, #5711) and the CLI's "Already processing a
59
+ // message" reject with one consistent queue → flush-on-complete behaviour.
60
+
61
+ // Marker stamped on a proc the first time _attachSidecarProcessListeners()
62
+ // wires its default listeners (#3504 review). Subsequent calls on the same
63
+ // proc short-circuit instead of attaching duplicate listeners — without this
64
+ // guard a re-wiring caller (resume/reconnect path, future K8s session class
65
+ // re-spawning into the same proc) would emit N copies of every warn-log.
66
+ // Symbol-keyed so it cannot collide with consumer code or test stubs.
67
+ const SIDECAR_LISTENERS_ATTACHED = Symbol('sdk-session.sidecarListenersAttached')
68
+
69
+ // Cumulative byte threshold for escalating stdin_dropped to error (#3506).
70
+ // Defaults to 10 MiB — equivalent to ten full pre-dial-cap chunks. Once the
71
+ // running total of dropped bytes meets or exceeds this, a single error log
72
+ // is emitted (one-shot per crossing) so operators triaging "why did my
73
+ // prompt vanish?" get a loud signal even on a flood of small drops.
74
+ export const STDIN_DROPPED_BYTES_ERROR_THRESHOLD = 10 * 1024 * 1024
75
+
76
+ // Drop-count cadence for re-escalating stdin_dropped to error (#3506).
77
+ // In addition to the byte threshold, every Nth drop event is logged at error
78
+ // level so a stream of zero-byte / unknown-size drops still raises a loud
79
+ // signal. Set to 10 to balance signal-to-noise.
80
+ export const STDIN_DROPPED_ESCALATION_EVERY_N = 10
81
+
82
+ // Minimum interval between refused-sendMessage warn logs (#3575).
83
+ // PR #3560 (#3539) added a warn on every refused sendMessage when
84
+ // `_stdinForwardingDisabled` is latched, but a stuck client retrying in a
85
+ // hot loop floods operator logs with the same line. The per-call `error`
86
+ // event still fires every time so client UI feedback is unaffected — only
87
+ // the log line is gated. 30s balances visibility ("the session is still
88
+ // stuck") with noise control.
89
+ export const REFUSED_SENDMESSAGE_WARN_INTERVAL_MS = 30 * 1000
90
+
91
+ export class SdkSession extends BaseSession {
92
+ // #5858: marks this as a Claude-family provider — the single source of truth
93
+ // for `isClaudeProvider()` (drives the createSession soft-fallback for stale
94
+ // model ids + the shared models registry). Docker subclasses inherit it.
95
+ static claudeFamily = true
96
+
97
+ /**
98
+ * Human-readable label shown in the startup banner and anywhere else the
99
+ * server needs to name this provider (#2953). Each provider owns its own
100
+ * display name so `server-cli.js` no longer has to maintain a hardcoded
101
+ * `PROVIDER_LABELS` map that drifts every time a new provider lands.
102
+ */
103
+ static get displayLabel() {
104
+ return 'Claude Code (SDK)'
105
+ }
106
+
107
+ /**
108
+ * Root data directory for this provider (#2965).
109
+ * Consumers (conversation-scanner, ws-file-ops) use this to locate
110
+ * provider-specific subdirs (projects/, agents/, commands/) without
111
+ * hardcoding the path.
112
+ */
113
+ static get dataDir() {
114
+ return join(homedir(), '.claude')
115
+ }
116
+
117
+ static get capabilities() {
118
+ return {
119
+ permissions: true,
120
+ inProcessPermissions: true,
121
+ modelSwitch: true,
122
+ permissionModeSwitch: true,
123
+ // #5609: SDK applies a mid-turn switch to 'auto' in-process (clears
124
+ // rules + auto-resolves pending prompts at the next tool check) without
125
+ // killing the turn. Declared false so the capability matrix is uniform —
126
+ // CliSession is the only provider where the auto-switch is destructive.
127
+ interruptsTurnOnAutoSwitch: false,
128
+ planMode: false,
129
+ resume: true,
130
+ terminal: false,
131
+ thinkingLevel: true,
132
+ // #3932: explicit `streaming` so the capability matrix is uniform across
133
+ // providers — claude-tui sets this to false (deliver-on-complete), all
134
+ // others stream incremental deltas via stream_delta during a turn.
135
+ streaming: true,
136
+ // #3209/#3246: SDK rebuilds systemPrompt.append on every turn
137
+ // (see sdk-session.js#_callQuery), so a runtime toggle of
138
+ // _activeManualSkills + _loadSkills() takes effect on the next
139
+ // user message. Subprocess providers don't get this for free —
140
+ // they snapshot the skills text at session start.
141
+ skillToggle: true,
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Custom event names this provider emits beyond the BaseSession defaults.
147
+ *
148
+ * #3544: `stdin_dropped_totals` carries the cumulative running total of
149
+ * bytes dropped at the SidecarProcess pre-dial cap so operators (mobile
150
+ * users, dashboard-only operators) who can't tail the server log still
151
+ * see how much input has been silently lost. SessionManager forwards
152
+ * customEvents as transient session_events — they aren't recorded in
153
+ * history and aren't replayed on reconnect, but the cumulative counters
154
+ * are session-lifetime so a fresh emit on the next drop re-publishes
155
+ * the running total.
156
+ *
157
+ * @returns {string[]}
158
+ */
159
+ static get customEvents() {
160
+ return ['stdin_dropped_totals']
161
+ }
162
+
163
+ /**
164
+ * #3209: SDK is the only provider that rebuilds the system prompt
165
+ * each turn, so manual-skill toggles propagate to the wire here.
166
+ * Subprocess providers (CliSession, CodexSession, GeminiSession)
167
+ * inherit the BaseSession default of `false`.
168
+ */
169
+ supportsRuntimeSkillToggle() {
170
+ return true
171
+ }
172
+
173
+ /**
174
+ * Preflight dependency spec used by `chroxy doctor`.
175
+ * SDK mode spawns the `claude` binary under the hood, so the same
176
+ * binary check applies. Credentials can come from ANTHROPIC_API_KEY,
177
+ * CLAUDE_CODE_OAUTH_TOKEN, or a prior `claude login` subscription.
178
+ */
179
+ static get preflight() {
180
+ return {
181
+ label: 'Claude SDK',
182
+ binary: {
183
+ name: 'claude',
184
+ args: ['--version'],
185
+ candidates: [
186
+ '/opt/homebrew/bin/claude',
187
+ '/usr/local/bin/claude',
188
+ ],
189
+ installHint: 'install Claude Code CLI (required by the Agent SDK)',
190
+ },
191
+ credentials: {
192
+ envVars: ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'],
193
+ hint: 'run `claude login` or set ANTHROPIC_API_KEY',
194
+ optional: true,
195
+ },
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Resolve runtime auth state for the dashboard (#4769).
201
+ *
202
+ * Tries env vars first; falls back to the on-disk `claude login` OAuth
203
+ * probe so the dashboard reports ready when the user has logged in via
204
+ * subscription without exporting a key. Without the probe the dashboard
205
+ * would lie about ready=true after #3674.
206
+ *
207
+ * @param {NodeJS.ProcessEnv} env
208
+ * @param {{ hasClaudeOAuthCreds: () => boolean }} helpers
209
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string, billingClass:string}}
210
+ */
211
+ static resolveAuth(env, helpers) {
212
+ const credSpec = this.preflight.credentials
213
+ const envVars = credSpec.envVars
214
+ const hint = credSpec.hint || `set ${envVars.join(' or ')}`
215
+ // Era read at call time so a long-running daemon flips OAuth/credit-pool
216
+ // copy at the 2026-06-15 boundary without a restart (#5629).
217
+ const era = isProgrammaticCreditEra()
218
+
219
+ const matched = envVars.find(v => env[v])
220
+ if (matched) {
221
+ // An explicit ANTHROPIC_API_KEY is a raw API account (per-token billing),
222
+ // NOT the subscription/credit pool — bill it `api-key` in BOTH eras
223
+ // (#5630 refinement). CLAUDE_CODE_OAUTH_TOKEN and any other matched var
224
+ // is the OAuth/credit-pool path, era-gated like the on-disk OAuth branch.
225
+ const isApiKey = matched === 'ANTHROPIC_API_KEY'
226
+ if (isApiKey) {
227
+ return {
228
+ ready: true,
229
+ source: 'env',
230
+ envVar: matched,
231
+ envVars,
232
+ hint: '',
233
+ detail: `Anthropic API (${matched} set)`,
234
+ billingClass: BILLING_CLASSES.API_KEY,
235
+ }
236
+ }
237
+ const identity = matched === 'CLAUDE_CODE_OAUTH_TOKEN'
238
+ ? 'Anthropic API (OAuth token)'
239
+ : 'Claude subscription'
240
+ return {
241
+ ready: true,
242
+ source: 'env',
243
+ envVar: matched,
244
+ envVars,
245
+ hint: '',
246
+ detail: era
247
+ ? `Programmatic credit pool — monthly metered credits (${matched} set)`
248
+ : `${identity} (${matched} set)`,
249
+ billingClass: era ? BILLING_CLASSES.PROGRAMMATIC_CREDIT : BILLING_CLASSES.SUBSCRIPTION,
250
+ }
251
+ }
252
+
253
+ if (helpers.hasClaudeOAuthCreds()) {
254
+ return {
255
+ ready: true,
256
+ source: 'oauth',
257
+ envVar: null,
258
+ envVars,
259
+ hint,
260
+ detail: era
261
+ ? 'Programmatic credit pool — monthly metered credits (OAuth from `claude login`)'
262
+ : 'Claude subscription (OAuth from `claude login`)',
263
+ billingClass: era ? BILLING_CLASSES.PROGRAMMATIC_CREDIT : BILLING_CLASSES.SUBSCRIPTION,
264
+ }
265
+ }
266
+
267
+ return {
268
+ ready: false,
269
+ source: 'none',
270
+ envVar: null,
271
+ envVars,
272
+ hint: hint || 'run `claude login` or set ANTHROPIC_API_KEY',
273
+ detail: `Not configured — ${hint || 'run \`claude login\` or set ANTHROPIC_API_KEY'}`,
274
+ // Unconfigured: default to the era-gated credit-pool class (this is the
275
+ // claude-sdk default auth path once configured via `claude login`).
276
+ billingClass: era ? BILLING_CLASSES.PROGRAMMATIC_CREDIT : BILLING_CLASSES.SUBSCRIPTION,
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Minimal model list for the per-provider registry (#2956). The live
282
+ * Agent SDK push (`supportedModels()`) replaces this at runtime; the
283
+ * fallback ships only short aliases so the dropdown is never empty
284
+ * before the first SDK response arrives.
285
+ */
286
+ static getFallbackModels() {
287
+ return CLAUDE_FALLBACK_MODELS
288
+ }
289
+
290
+ static getAllowedModels() {
291
+ return [...ALLOWED_MODEL_IDS]
292
+ }
293
+
294
+ /**
295
+ * Claude-style metadata: strip the `claude-` prefix for the short id,
296
+ * reuse the shared context-window heuristic. Used by the per-provider
297
+ * registry for both lookup and validation (#2956). Delegates to the shared
298
+ * claudeModelMetadata() so all Claude providers stay in lockstep (#6201 OCP).
299
+ *
300
+ * @param {string} modelId - Full model id (e.g. 'claude-sonnet-4-6').
301
+ * @returns {{id:string,label:string,fullId:string,contextWindow:number,description?:string}|null}
302
+ */
303
+ static getModelMetadata(modelId) {
304
+ return claudeModelMetadata(modelId)
305
+ }
306
+
307
+ /** Token budgets for thinking levels. null = adaptive (SDK default). */
308
+ static THINKING_BUDGETS = { default: null, high: 32000, max: 128000 }
309
+
310
+ /** Error patterns mapped to user-friendly messages. */
311
+ static _ERROR_PATTERNS = [
312
+ { test: /credit|billing|quota|usage.limit/i,
313
+ msg: 'Insufficient API credits or billing limit reached. Check your API provider dashboard.' },
314
+ { test: /rate.limit|too many requests|429/i,
315
+ msg: 'API rate limit exceeded. Please wait a moment and try again.' },
316
+ { test: /authentication|invalid.api.key|401|unauthorized/i,
317
+ msg: 'API authentication failed. Check your API key configuration.' },
318
+ { test: /overloaded|503|529|temporarily unavailable/i,
319
+ msg: 'The API is temporarily overloaded. Please try again in a few minutes.' },
320
+ { test: /SIGABRT|SIGKILL|SIGSEGV|terminated by signal/i,
321
+ msg: 'Claude Code process crashed. This is often caused by API errors (insufficient credits, invalid key, or rate limits). Check your API provider dashboard.' },
322
+ ]
323
+
324
+ static _enrichErrorMessage(raw) {
325
+ if (!raw) return 'Unknown error'
326
+ for (const { test, msg } of SdkSession._ERROR_PATTERNS) {
327
+ if (test.test(raw)) return msg
328
+ }
329
+ return raw
330
+ }
331
+
332
+ get thinkingLevel() { return this._thinkingLevel }
333
+
334
+ constructor(opts = {}) {
335
+ super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-sdk' }))
336
+ // SdkSession-local opts (not BaseSession opts — see buildBaseSessionOpts).
337
+ const { resumeSessionId, transforms, maxToolInput, sandbox, stdinForwardingDisabled } = opts
338
+ this._maxToolInput = maxToolInput || DEFAULT_MAX_TOOL_INPUT_LENGTH
339
+ this._transformPipeline = new MessageTransformPipeline(transforms || [])
340
+ this._sandbox = sandbox || null
341
+
342
+ this._sdkSessionId = resumeSessionId || null
343
+ this._sessionId = null
344
+ // #4828: session-scoped logger, lazily bound on the SDK's first `init`
345
+ // message (where session_id becomes known). Pre-init log lines stay on
346
+ // the module-level `log` — same fallback pattern as ClaudeTuiSession.
347
+ // No reset on destroy/respawn (unlike CliSession): SdkSession lacks a
348
+ // _killAndRespawn path so session_id is stable for the instance
349
+ // lifetime; the binding stays valid until destroy() drops the instance.
350
+ this._log = null
351
+ this._query = null
352
+ this._thinkingLevel = null
353
+
354
+ // #5269 (Control Room Phase 2a): map a Task subagent's tool_use_id (the id
355
+ // chroxy keys activity/agent nodes by) → the SDK's separate `task_id`,
356
+ // captured from `task_started` system messages. cancelActivity() needs the
357
+ // task_id to call query.stopTask(); the wire/activity layer only knows the
358
+ // tool_use_id. Cleared per entry on the terminal `task_notification` and
359
+ // wholesale at the start of each new turn (after `_callQuery`) and in
360
+ // destroy().
361
+ this._taskIdByToolUseId = new Map()
362
+
363
+ // Permission handling — delegated to PermissionManager. The pause/resume
364
+ // hooks keep the inactivity timer suspended while a permission is pending:
365
+ // waiting on user input is NOT inactivity, and without this a session with
366
+ // a pending prompt silently goes unresponsive after 5 min (#2831). The
367
+ // pause uses a reference count so concurrent prompts keep the timer
368
+ // suspended until the last one resolves. (Shared wiring extracted in P2-9.)
369
+ this._permissions = new PermissionManager({ log })
370
+ wirePermissionManager(this, this._permissions, {
371
+ onRequest: () => this._pauseResultTimeoutForPermission(),
372
+ onResolved: () => this._resumeResultTimeoutForPermission(),
373
+ })
374
+
375
+ // Permission pause bookkeeping for _resultTimeout (#2831)
376
+ this._permissionPauseCount = 0
377
+ this._resultTimeoutPaused = false
378
+ this._resetResultTimeout = null
379
+
380
+ // stdin_dropped accounting (#3506) — every chunk dropped at the
381
+ // SidecarProcess pre-dial cap accumulates here so operators can
382
+ // see the running cost of dropped input. The default listener
383
+ // (see _attachSidecarProcessListeners) escalates to an error log
384
+ // on the first drop, every Nth drop, and when the cumulative byte
385
+ // total crosses STDIN_DROPPED_BYTES_ERROR_THRESHOLD. Subsequent
386
+ // drops fall back to warn so a hot-loop drop flood doesn't spam.
387
+ this._stdinDroppedBytesTotal = 0
388
+ this._stdinDroppedCount = 0
389
+ this._stdinDroppedThresholdLogged = false
390
+
391
+ // #3540: SESSION-STICKY stdin_disabled flag (latched by the
392
+ // _attachSidecarProcessListeners 'stdin_disabled' handler, see #3501).
393
+ // Initialised here so SessionManager.serializeState can read the field
394
+ // unconditionally and so a hydrated value from restoreState survives
395
+ // until the next process tick. The metadata field is the canonical
396
+ // signal for restored sessions: clients connecting after restart see
397
+ // the disabled state in session_list / listSessions, no replayed
398
+ // `error` event needed (the original event already fired and was
399
+ // proxied; cold restart treats the persisted flag as authoritative).
400
+ this._stdinForwardingDisabled = !!stdinForwardingDisabled
401
+
402
+ // #3575: rate-limit the refused-sendMessage warn log. A stuck client that
403
+ // retries on every error event would otherwise flood operator logs with
404
+ // the same line on every attempt. Tracks the last Date.now() that the
405
+ // refusal warn fired; the warn is gated on
406
+ // `now - _lastRefusedWarnTs >= REFUSED_SENDMESSAGE_WARN_INTERVAL_MS`.
407
+ // The per-call `error` event still fires on every refused sendMessage so
408
+ // client UI feedback is unaffected.
409
+ this._lastRefusedWarnTs = 0
410
+
411
+ // #4881: provider parity with CliSession's #4602 _intentionalStop flag.
412
+ // Set by `interrupt()` immediately before aborting the active SDK query
413
+ // generator, then consumed inside `_callQuery`'s try/catch/finally so a
414
+ // user-initiated Stop:
415
+ // - suppresses the normal "Query error: AbortError" error emit, and
416
+ // - emits a single transient `stopped` event (no `code` — SdkSession is
417
+ // in-process, no child-process exit status to carry).
418
+ // Cleared on every consume path (close, error, destroy) so the flag never
419
+ // leaks past one turn — matches the single-use semantic CliSession pins
420
+ // in `_handleChildClose` (capture-and-clear up front).
421
+ // The flag itself is declared+initialized on BaseSession (#5375).
422
+ }
423
+
424
+ get sessionId() {
425
+ return this._sessionId
426
+ }
427
+
428
+ /** Public accessor for the SDK session ID used to resume conversations. */
429
+ get resumeSessionId() {
430
+ return this._sdkSessionId
431
+ }
432
+
433
+ /**
434
+ * Public accessor for the cumulative stdin_dropped totals (#3544).
435
+ *
436
+ * Returns a snapshot of the session-lifetime counters maintained by
437
+ * `_attachSidecarProcessListeners`. Operators can poll this from a test
438
+ * client or session-info handler; the same numbers are published as a
439
+ * `stdin_dropped_totals` session_event whenever a fresh drop arrives.
440
+ *
441
+ * @returns {{ bytes: number, count: number }}
442
+ */
443
+ get stdinDroppedTotals() {
444
+ return {
445
+ bytes: this._stdinDroppedBytesTotal,
446
+ count: this._stdinDroppedCount,
447
+ }
448
+ }
449
+
450
+
451
+ /**
452
+ * Start the SDK session. Creates the long-lived streaming input generator
453
+ * and begins the query loop.
454
+ */
455
+ start() {
456
+ this._processReady = true
457
+ log.info('Ready for messages')
458
+ this.emit('ready', { sessionId: null, model: this.model, tools: [] })
459
+ }
460
+
461
+ /**
462
+ * Send a message to Claude via the Agent SDK.
463
+ * Each call creates a new query() with resume to maintain conversation.
464
+ */
465
+ async sendMessage(prompt, attachments, sendOptions = {}) {
466
+ // #3539: once `_stdinForwardingDisabled` latches (see #3502/#3402), any
467
+ // further sendMessage calls would be silently dropped on the SidecarProcess
468
+ // PassThrough — the user sees a hung turn instead of an error. Refuse the
469
+ // write up front, surface the same machine-readable `code: 'stdin_disabled'`
470
+ // contract that #3502 established, and drain any queued follow-ups so the
471
+ // post-finally dequeue path (#3541) does not re-trigger writes after the
472
+ // flag flips. Decision: one-shot reject (per-call). The session is
473
+ // unrecoverable until restart, so queueing for "flush on resume" would only
474
+ // hide the problem; clients must handle the error and prompt for restart.
475
+ if (this._stdinForwardingDisabled) {
476
+ // #3575: rate-limit the refused-sendMessage warn so a stuck client
477
+ // retrying in a hot loop does not flood operator logs. The per-call
478
+ // `error` event below still fires on every attempt — only the log line
479
+ // is gated. The "Discarding queued follow-ups" warn is also gated by
480
+ // this same window because it only ever fires alongside the refusal
481
+ // warn (one drain per latch transition).
482
+ const now = Date.now()
483
+ const warnSuppressed = (now - this._lastRefusedWarnTs) < REFUSED_SENDMESSAGE_WARN_INTERVAL_MS
484
+ if (!warnSuppressed) {
485
+ // #4828: session-scoped when init has fired (sendMessage typically
486
+ // arrives after init; first-message pre-init path falls back to `log`).
487
+ ;(this._log || log).warn(
488
+ 'Refusing sendMessage — stdin forwarding is disabled for this session; ' +
489
+ 'restart the session to recover'
490
+ )
491
+ this._lastRefusedWarnTs = now
492
+ }
493
+ // Drop any messages that piled up in the queue while the flag was
494
+ // flipping. Without this, the post-turn dequeue would call
495
+ // sendMessage(...) once per queued item and emit one error per message —
496
+ // noisy, and pointless because none of them can be sent. #5936: the queue
497
+ // is now the shared `_outgoingQueue`; clear it silently (no per-item
498
+ // message_dequeued — these are discarded, not flushed) and surface the
499
+ // single stdin_disabled error below.
500
+ if (this._outgoingQueue.length) {
501
+ if (!warnSuppressed) {
502
+ // #4828: session-scoped when init has fired.
503
+ ;(this._log || log).warn(
504
+ `Discarding ${this._outgoingQueue.length} queued follow-up message(s) — ` +
505
+ 'stdin forwarding is disabled'
506
+ )
507
+ }
508
+ this.clearOutgoingQueue({ emit: false })
509
+ }
510
+ this.emit('error', {
511
+ code: 'stdin_disabled',
512
+ message: 'Cannot send message — stdin forwarding is disabled; restart this session',
513
+ recoverable: false,
514
+ })
515
+ return
516
+ }
517
+
518
+ if (this._isBusy) {
519
+ // #5936 (epic #5935): a send-while-busy follow-up goes into the shared
520
+ // outgoing queue (BaseSession) — flushed FIFO on the next `result`. The
521
+ // overflow cap + the `message_queued` mirror event live in
522
+ // enqueueOutgoingMessage; nothing to do here but enqueue and return.
523
+ this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
524
+ return
525
+ }
526
+
527
+ // Apply message transforms if configured
528
+ let transformedPrompt = prompt
529
+ if (this._transformPipeline.hasTransforms && typeof prompt === 'string') {
530
+ transformedPrompt = this._transformPipeline.apply(prompt, {
531
+ cwd: this.cwd,
532
+ model: this.model,
533
+ isVoiceInput: !!sendOptions.isVoice,
534
+ platform: process.platform,
535
+ })
536
+ }
537
+
538
+ this._isBusy = true
539
+ this._messageCounter++
540
+ // `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
541
+ // the boot-unique prefix is needed (#3700). Format change does not
542
+ // affect the wire schema; clients treat messageId as opaque string.
543
+ const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
544
+ this._currentMessageId = messageId
545
+ // Shared ref so _handleResultTimeout can observe the latest value
546
+ // when it fires (the timer was armed when hasStreamStarted was still
547
+ // false, but the turn may have streamed before the timeout landed).
548
+ const streamState = { hasStreamStarted: false }
549
+ let didStreamText = false
550
+
551
+ const sdkPermMode = this._sdkPermissionMode()
552
+ // Skills MVP (#2957) — append shared skills via SDK systemPrompt.append.
553
+ // Per-skill injection mode (#3200): the append bucket flows through
554
+ // systemPrompt.append; the prepend bucket is concatenated onto the
555
+ // first user message, once per session.
556
+ const skillsText = this._buildSystemPrompt()
557
+ const systemPrompt = { type: 'preset', preset: 'claude_code' }
558
+ if (skillsText) {
559
+ systemPrompt.append = skillsText
560
+ }
561
+ // Don't flip `_skillsPrepended` until _callQuery() has accepted the
562
+ // prompt (#3225). If the call throws synchronously — bad SDK args,
563
+ // missing claude binary in DockerSdkSession's spawnClaudeCodeProcess,
564
+ // etc. — the prepend bucket needs to ride on the next attempt.
565
+ let firstMessagePrefix = ''
566
+ let willPrependSkills = false
567
+ if (!this._skillsPrepended) {
568
+ const prependText = typeof this._buildPrependPrompt === 'function'
569
+ ? this._buildPrependPrompt()
570
+ : ''
571
+ if (prependText) {
572
+ firstMessagePrefix = `${prependText}\n\n---\n\n`
573
+ }
574
+ willPrependSkills = true
575
+ }
576
+ const options = {
577
+ cwd: this.cwd,
578
+ permissionMode: sdkPermMode,
579
+ includePartialMessages: true,
580
+ settingSources: ['user', 'project', 'local'],
581
+ systemPrompt,
582
+ tools: { type: 'preset', preset: 'claude_code' },
583
+ }
584
+
585
+ // SDK requires this flag when using bypassPermissions
586
+ if (sdkPermMode === 'bypassPermissions') {
587
+ options.allowDangerouslySkipPermissions = true
588
+ }
589
+
590
+ if (this.model) {
591
+ options.model = this.model
592
+ }
593
+
594
+ // Apply thinking level if set
595
+ if (this._thinkingLevel) {
596
+ const budget = SdkSession.THINKING_BUDGETS[this._thinkingLevel]
597
+ if (budget != null) options.maxThinkingTokens = budget
598
+ }
599
+
600
+ // #4306 — magic thinking-keyword escalation. The native Claude Code CLI's
601
+ // interactive REPL scans the user's prompt for keywords (`think`,
602
+ // `think hard`, `think harder`, `megathink`, `ultrathink`) and escalates
603
+ // the thinking budget for that turn. The Agent SDK's `query()` path does
604
+ // NOT do this — the scanner lives in the REPL only. Re-implement it here
605
+ // so the keyword behaviour is consistent between Chroxy and the native CLI.
606
+ //
607
+ // Important: the keyword detection runs against the ORIGINAL prompt
608
+ // (`prompt`), not the transformed one. Voice / typo / etc. transforms
609
+ // (#3203, MessageTransformPipeline) may legitimately rewrite the user's
610
+ // input, but the keyword is a user-intent signal that must come from
611
+ // their literal typed text.
612
+ //
613
+ // The detected budget takes precedence over the dropdown-driven level
614
+ // ONLY when the keyword's budget is larger — otherwise a `think` keyword
615
+ // could *lower* a session that the user already set to `max`. Matches
616
+ // the native CLI's "more thinking, never less" semantic.
617
+ const detectedKeyword = typeof prompt === 'string' ? detectThinkingKeyword(prompt) : null
618
+ if (detectedKeyword) {
619
+ const existing = options.maxThinkingTokens ?? 0
620
+ if (detectedKeyword.budget > existing) {
621
+ options.maxThinkingTokens = detectedKeyword.budget
622
+ // #4828: session-scoped when init has fired.
623
+ ;(this._log || log).info(`Thinking keyword "${detectedKeyword.keyword}" detected — escalating maxThinkingTokens to ${detectedKeyword.budget} for this turn`)
624
+ } else {
625
+ ;(this._log || log).debug(`Thinking keyword "${detectedKeyword.keyword}" detected but session already at higher budget (${existing}) — leaving unchanged`)
626
+ }
627
+ }
628
+
629
+ // Sandbox settings (lightweight isolation without Docker)
630
+ if (this._sandbox) {
631
+ options.sandbox = this._sandbox
632
+ }
633
+
634
+ // In-process permission handling (only when not bypassing).
635
+ // We forward the SDK-provided `suggestions` to the permission manager
636
+ // so the 'allow always' flow can echo them back via updatedPermissions.
637
+ // Without this, respondToPermission('allowAlways') had nothing to
638
+ // attach to the PermissionResult — and worse, the 2026-04-11 audit
639
+ // (Skeptic) found the old code passed behavior:'allowAlways' which
640
+ // isn't a valid PermissionResult.behavior (SDK only accepts
641
+ // 'allow'|'deny'). The correct shape per the SDK's "always allow"
642
+ // documentation is { behavior: 'allow', updatedPermissions:
643
+ // <suggestions from callback options> }.
644
+ if (this.permissionMode !== 'auto') {
645
+ options.canUseTool = (toolName, input, { signal, suggestions }) =>
646
+ this._handlePermission(toolName, input, signal, suggestions)
647
+ }
648
+
649
+ // Resume existing session if we have one
650
+ if (this._sdkSessionId) {
651
+ options.resume = this._sdkSessionId
652
+ }
653
+
654
+ // Safety timeouts: SOFT warning + HARD cap + STREAM-STALL recovery,
655
+ // all armed on every SDK event. Soft fires `inactivity_warning`
656
+ // (session stays alive); hard fires the existing kill path (force-
657
+ // clear, auto-deny pending perms, emit error); stall (#4467) fires
658
+ // the active-recovery path — clears busy state and emits
659
+ // `error{code:'stream_stall'}` so the dashboard's StreamStallChip
660
+ // can offer a retry without the user having to click Stop. All
661
+ // three paused while a permission prompt is outstanding (#2831) —
662
+ // awaiting user input is not inactivity / not a stall. Windows
663
+ // configurable per server (#3749 / #3899 / #4467) — see BaseSession.
664
+ const SOFT_TIMEOUT_MS = this._resultTimeoutMs
665
+ const HARD_TIMEOUT_MS = this._hardTimeoutMs
666
+ const STALL_TIMEOUT_MS = this._streamStallTimeoutMs
667
+ const resetResultTimeout = () => {
668
+ if (this._resultTimeout) clearTimeout(this._resultTimeout)
669
+ if (this._hardTimeout) clearTimeout(this._hardTimeout)
670
+ if (this._streamStallTimeout) clearTimeout(this._streamStallTimeout)
671
+ this._resultTimeout = null
672
+ this._hardTimeout = null
673
+ this._streamStallTimeout = null
674
+ if (this._resultTimeoutPaused) return
675
+ this._resultTimeout = setTimeout(() => {
676
+ this._resultTimeout = null
677
+ this._handleInactivityWarning(messageId)
678
+ }, SOFT_TIMEOUT_MS)
679
+ this._hardTimeout = setTimeout(() => {
680
+ this._hardTimeout = null
681
+ this._handleHardTimeout(messageId, streamState.hasStreamStarted)
682
+ }, HARD_TIMEOUT_MS)
683
+ // #4467: only arm the stall timer when the operator has not
684
+ // disabled the active-recovery path (value > 0). Soft + hard
685
+ // still apply regardless. Mirrors CliSession._armResultTimeout.
686
+ if (STALL_TIMEOUT_MS > 0) {
687
+ this._streamStallTimeout = setTimeout(() => {
688
+ this._streamStallTimeout = null
689
+ this._handleStreamStall(messageId, streamState.hasStreamStarted)
690
+ }, STALL_TIMEOUT_MS)
691
+ }
692
+ }
693
+ this._resetResultTimeout = resetResultTimeout
694
+ resetResultTimeout()
695
+
696
+ try {
697
+ // Allow subclasses to augment query options (e.g. DockerSdkSession
698
+ // injects spawnClaudeCodeProcess here)
699
+ this._augmentQueryOptions(options)
700
+
701
+ // If attachments present, build multimodal content blocks
702
+ const promptWithSkills = firstMessagePrefix
703
+ ? `${firstMessagePrefix}${transformedPrompt}`
704
+ : transformedPrompt
705
+ const queryArgs = { prompt: promptWithSkills, options }
706
+ if (attachments?.length) {
707
+ queryArgs.prompt = buildContentBlocks(promptWithSkills, attachments)
708
+ }
709
+ this._query = this._callQuery(queryArgs)
710
+ // #5269: a fresh turn — drop any task_id mappings left over from a prior
711
+ // turn (every subagent should clear via task_notification, but a turn
712
+ // aborted before its notifications would otherwise strand entries).
713
+ this._taskIdByToolUseId.clear()
714
+
715
+ // _callQuery returned an iterable without throwing — the prepend
716
+ // bucket is committed to this turn's prompt, so flip the flag (#3225).
717
+ // If _callQuery threw synchronously, control falls into the catch
718
+ // below with the flag still false, ensuring the next retry
719
+ // re-includes the prepend skills.
720
+ if (willPrependSkills) {
721
+ this._skillsPrepended = true
722
+ }
723
+
724
+ for await (const msg of this._query) {
725
+ if (this._destroying) break
726
+ resetResultTimeout() // Any SDK event = activity, reset inactivity timer
727
+
728
+ switch (msg.type) {
729
+ case 'system': {
730
+ if (msg.subtype === 'init') {
731
+ this._sdkSessionId = msg.session_id
732
+ this._sessionId = msg.session_id
733
+ // #4828: bind the session-scoped logger now that session_id
734
+ // is known. Subsequent log lines route through the WsServer
735
+ // log fan-out (#4787) to dashboards bound to this session.
736
+ this._log = loggerForSession('sdk', msg.session_id)
737
+ // #3687: persist the actual model the SDK booted with so
738
+ // sendSessionInfo (replay on reconnect / tab switch) reports
739
+ // the truth instead of `null` when the user didn't specify a
740
+ // model.
741
+ if (typeof msg.model === 'string' && msg.model) {
742
+ this.bootedModel = msg.model
743
+ }
744
+ ;(this._log || log).info(`Session initialized: ${msg.session_id} (model: ${msg.model})`)
745
+ this.emit('ready', {
746
+ sessionId: msg.session_id,
747
+ model: msg.model,
748
+ tools: msg.tools || [],
749
+ })
750
+ // Emit MCP server status if present (including empty list to clear stale state)
751
+ if (Array.isArray(msg.mcp_servers)) {
752
+ if (msg.mcp_servers.length > 0) {
753
+ // #4828: session-scoped (post-init).
754
+ ;(this._log || log).info(`MCP servers: ${msg.mcp_servers.map(s => `${s.name}(${s.status})`).join(', ')}`)
755
+ }
756
+ this.emit('mcp_servers', { servers: msg.mcp_servers })
757
+ }
758
+ // Fetch dynamic model list from SDK (non-blocking)
759
+ this._fetchSupportedModels()
760
+ } else if (msg.subtype === 'task_started') {
761
+ // #5269: a Task subagent started. The SDK message carries BOTH
762
+ // the subagent's `task_id` (needed by query.stopTask) and the
763
+ // originating `tool_use_id` (the id chroxy keys agent nodes by).
764
+ // Capture the mapping so cancelActivity() can translate an
765
+ // activity id back to a stoppable task. No client-facing emit —
766
+ // the agent node already exists via agent_spawned.
767
+ this._captureTaskId(msg.tool_use_id, msg.task_id)
768
+ break
769
+ } else if (msg.subtype === 'task_notification') {
770
+ // #5269: a Task subagent reached a terminal state (completed /
771
+ // failed / stopped — the last one is what query.stopTask emits).
772
+ // Finalize the agent node promptly and drop the task mapping so a
773
+ // cancel feels responsive instead of waiting for the turn-end
774
+ // sweep. Idempotent (no-op if already finalized).
775
+ this._finalizeAgentByToolUseId(msg.tool_use_id)
776
+ break
777
+ } else {
778
+ // Forward non-init system events (e.g. /usage, /cost, other
779
+ // slash command responses) as system messages to the client
780
+ const text = msg.message || msg.text || msg.subtype || 'System event'
781
+ // #4828: session-scoped (non-init system event arrives after init).
782
+ ;(this._log || log).info(`System event (${msg.subtype || 'unknown'}): ${typeof text === 'string' ? text.slice(0, 120) : text}`)
783
+ this.emit('message', {
784
+ type: 'system',
785
+ content: text,
786
+ timestamp: Date.now(),
787
+ })
788
+ }
789
+ break
790
+ }
791
+
792
+ case 'stream_event': {
793
+ // Handle partial message events (content_block_start/delta/stop)
794
+ const event = msg.event
795
+ if (!event) break
796
+
797
+ switch (event.type) {
798
+ case 'content_block_start': {
799
+ const blockType = event.content_block?.type
800
+ if (blockType === 'text') {
801
+ if (!streamState.hasStreamStarted) {
802
+ streamState.hasStreamStarted = true
803
+ this.emit('stream_start', { messageId })
804
+ }
805
+ } else if (blockType === 'tool_use') {
806
+ // Delegate to the shared parser so CliSession + SdkSession
807
+ // emit identical tool_start payloads (see
808
+ // claude-stream-parser.js for the toolId-derivation rules).
809
+ const toolStartData = buildToolStartData(messageId, event.content_block)
810
+ this.emit('tool_start', toolStartData)
811
+ // #4628: defense-in-depth — track so _emitResult sweep
812
+ // catches any orphan if the API ever drops a tool_result.
813
+ this._trackToolStart(toolStartData.toolUseId, event.content_block.name)
814
+ }
815
+ break
816
+ }
817
+
818
+ case 'content_block_delta': {
819
+ const delta = event.delta
820
+ if (!delta) break
821
+ if (delta.type === 'text_delta') {
822
+ if (!streamState.hasStreamStarted) {
823
+ streamState.hasStreamStarted = true
824
+ this.emit('stream_start', { messageId })
825
+ }
826
+ didStreamText = true
827
+ // #5515 (epic #5514): stamp the monotonic emit time so
828
+ // ws-forwarding can measure emit→broadcast (the server-side
829
+ // coalescing cost). Monotonic (hrtime) — not wall-clock —
830
+ // because both ends are this same process; it's a true
831
+ // elapsed duration, unlike the cross-machine serverTs field.
832
+ this.emit('stream_delta', { messageId, delta: delta.text, _emitMonoMs: Number(process.hrtime.bigint() / 1_000_000n) })
833
+ }
834
+ break
835
+ }
836
+ }
837
+ break
838
+ }
839
+
840
+ case 'assistant': {
841
+ // Full assistant message — process content blocks for tool detection
842
+ const content = msg.message?.content
843
+ if (!Array.isArray(content)) break
844
+
845
+ for (const block of content) {
846
+ if (block.type === 'text' && block.text && !didStreamText && !streamState.hasStreamStarted) {
847
+ // Fallback for non-streamed text
848
+ this.emit('message', {
849
+ type: 'response',
850
+ content: block.text,
851
+ timestamp: Date.now(),
852
+ })
853
+ }
854
+
855
+ if (block.type === 'tool_use') {
856
+ this._handleToolUseBlock(messageId, block)
857
+ }
858
+ }
859
+ break
860
+ }
861
+
862
+ case 'user': {
863
+ // Tool result content blocks appear in user-role messages during the tool loop
864
+ emitToolResults(msg.message?.content, this)
865
+ // #4307: scan tool_result blocks for the canonical
866
+ // "Command running in background with ID: <id>" pattern so
867
+ // we can record the shell as pending background work. Done
868
+ // alongside emitToolResults rather than inside it so the
869
+ // tracker stays out of the existing image-extraction /
870
+ // truncation surface (tool-result.js is also used by
871
+ // CliSession + GeminiSession, which don't share this
872
+ // BaseSession path).
873
+ this._recordBackgroundShellsFromToolResults(msg.message?.content)
874
+ break
875
+ }
876
+
877
+ case 'result': {
878
+ if (streamState.hasStreamStarted) {
879
+ this.emit('stream_end', { messageId })
880
+ }
881
+
882
+ if (msg.session_id) {
883
+ this._sdkSessionId = msg.session_id
884
+ this._sessionId = msg.session_id
885
+ }
886
+
887
+ // Correct any static context-window guess using the SDK's
888
+ // authoritative per-model values. Only cache + broadcast when
889
+ // a value actually changed to avoid thrashy writes / UI churn.
890
+ let contextWindowChanged = false
891
+ if (msg.modelUsage && typeof msg.modelUsage === 'object') {
892
+ const missingIds = []
893
+ for (const [modelId, usage] of Object.entries(msg.modelUsage)) {
894
+ if (usage && typeof usage.contextWindow === 'number') {
895
+ if (updateContextWindow(modelId, usage.contextWindow)) {
896
+ contextWindowChanged = true
897
+ }
898
+ } else {
899
+ missingIds.push(modelId)
900
+ }
901
+ }
902
+ // Drift signal: at least one modelUsage entry was missing a
903
+ // numeric contextWindow. Catches both total drift (field renamed
904
+ // or removed upstream) and partial drift (schema updated for one
905
+ // model family before another). Log a redacted sample so a
906
+ // future regression is diagnosable without flooding info-level
907
+ // output.
908
+ if (missingIds.length > 0) {
909
+ const sampleId = missingIds[0]
910
+ const sampleKeys = Object.keys(msg.modelUsage[sampleId] || {})
911
+ // #4828: session-scoped (result handler runs strictly post-init).
912
+ ;(this._log || log).debug(
913
+ `modelUsage partial drift: contextWindow missing for modelIds=${JSON.stringify(missingIds)} sampleKeys=${JSON.stringify(sampleKeys)}`
914
+ )
915
+ }
916
+ }
917
+ if (contextWindowChanged) {
918
+ saveModelsCache()
919
+ // Notify connected clients so the picker / budget UI picks up
920
+ // the corrected window without waiting for the next refresh.
921
+ this.emit('models_updated', { models: getModels() })
922
+ }
923
+
924
+ // #4628: sweep any orphan tool_starts before emitting result
925
+ // so the dashboard's activeTools clears as part of the same
926
+ // turn-end burst. _clearMessageState (called next) would also
927
+ // clear the in-flight map but without broadcasting synthetic
928
+ // tool_results to the dashboard.
929
+ this._emitResult({
930
+ sessionId: msg.session_id || this._sdkSessionId,
931
+ cost: msg.total_cost_usd,
932
+ duration: msg.duration_ms,
933
+ usage: msg.usage,
934
+ }, 'turn_ended_with_orphan_tool_start')
935
+
936
+ this._clearMessageState()
937
+ break
938
+ }
939
+ }
940
+ }
941
+ } catch (err) {
942
+ if (streamState.hasStreamStarted) {
943
+ this.emit('stream_end', { messageId })
944
+ }
945
+ // #4881: capture-and-clear before any branch so the flag never leaks
946
+ // past this turn even when _destroying short-circuits the emits below.
947
+ // Mirrors CliSession._handleChildClose (#4602).
948
+ const wasIntentionalStop = this._consumeIntentionalStop()
949
+ if (!this._destroying) {
950
+ if (wasIntentionalStop) {
951
+ // #4881: user clicked Stop — interrupt() set the flag, the SDK
952
+ // generator threw an AbortError as a result. Skip the loud "Query
953
+ // error" surface and emit the quiet `stopped` event for parity
954
+ // with CliSession. No `code` because SDK runs in-process — there
955
+ // is no child-process exit status to carry.
956
+ ;(this._log || log).info('Query aborted after user stop')
957
+ this.emit('stopped', {})
958
+ } else {
959
+ // #4828: session-scoped when init has fired; falls back to module
960
+ // `log` for pre-init query failures (e.g. spawn refused).
961
+ ;(this._log || log).error(`Query error: ${err.message}`)
962
+ this.emit('error', { message: SdkSession._enrichErrorMessage(err.message) })
963
+ }
964
+ }
965
+ this._clearMessageState()
966
+ } finally {
967
+ this._query = null
968
+ // #4881: safety-net clear of _intentionalStop. The catch block clears
969
+ // it on the throw path (AbortError after interrupt()), but if
970
+ // query.interrupt() races a `result` message arriving first, the
971
+ // for-await loop exits normally, skipping the catch. Without this
972
+ // clear, the flag would stay armed until the next turn's catch and
973
+ // mis-trigger a spurious `stopped` emit there. Idempotent — the
974
+ // catch path already cleared it on the throw path.
975
+ this._clearIntentionalStop()
976
+ // Dequeue any follow-up messages that arrived while busy (#5936: the
977
+ // shared `_outgoingQueue`; flush one item via dequeueNextOutgoing, whose
978
+ // re-dispatched sendMessage re-sets _isBusy so the next `result` drains
979
+ // the following item — FIFO, one turn at a time).
980
+ if (this._outgoingQueue.length && !this._destroying) {
981
+ // #3562: if the SidecarProcess latched stdin_disabled mid-turn (e.g.
982
+ // the PassThrough closed while _callQuery was still streaming), the
983
+ // entry-gate at the top of sendMessage has already been bypassed
984
+ // for this turn. Without this short-circuit, we would shift one
985
+ // follow-up, schedule a process.nextTick recursion, and only then
986
+ // hit the entry gate — wasting a hop and emitting a per-message
987
+ // error. Drain the queue at the dequeue site for symmetry with
988
+ // the entry-gate drain (#3539/PR #3560), log a single warn, and
989
+ // skip the recursion entirely.
990
+ if (this._stdinForwardingDisabled) {
991
+ // #4828: session-scoped (finally block runs strictly post-init).
992
+ ;(this._log || log).warn(
993
+ `Discarding ${this._outgoingQueue.length} queued follow-up message(s) after turn finish — ` +
994
+ 'stdin forwarding is disabled'
995
+ )
996
+ // Silent clear — these are discarded (stdin gone), not flushed, so no
997
+ // message_dequeued (which signals "sent") should fire for them.
998
+ this.clearOutgoingQueue({ emit: false })
999
+ return
1000
+ }
1001
+ this.dequeueNextOutgoing()
1002
+ }
1003
+ }
1004
+ }
1005
+
1006
+ /**
1007
+ * Invoke the SDK query function. Extracted for testability.
1008
+ * @param {object} queryArgs - { prompt, options }
1009
+ * @returns {AsyncIterable} SDK message stream
1010
+ */
1011
+ _callQuery(queryArgs) {
1012
+ return query(queryArgs)
1013
+ }
1014
+
1015
+ /**
1016
+ * Hook for subclasses to modify query options before they're passed to query().
1017
+ * Default implementation is a no-op. Override in subclasses that need to inject
1018
+ * additional options (e.g. spawnClaudeCodeProcess for container isolation).
1019
+ * @param {object} options - The query options object (mutated in place)
1020
+ */
1021
+ _augmentQueryOptions(_options) {
1022
+ // No-op — override in subclasses
1023
+ }
1024
+
1025
+ /**
1026
+ * Attach default log listeners for SidecarProcess stdin failure
1027
+ * signals (#3402, #3474, #3506).
1028
+ *
1029
+ * SidecarProcess (used by container/k8s spawnClaudeCodeProcess paths)
1030
+ * emits two stdin failure events the SDK itself does not surface:
1031
+ *
1032
+ * - `stdin_disabled` — fired when forwarding becomes unrecoverable
1033
+ * (post-reconnect or live WS close mid-write). One-shot.
1034
+ * Logged at warn level.
1035
+ * - `stdin_dropped` — fired for every chunk that exceeds the 1 MiB
1036
+ * pre-dial cap. Payload: `{ bytes, reason: 'pre-dial-cap' }`.
1037
+ * #3506: every drop logs with a cumulative running total
1038
+ * (`_stdinDroppedBytesTotal` + `_stdinDroppedCount`); the level
1039
+ * escalates to error on the first drop, every Nth drop
1040
+ * (`STDIN_DROPPED_ESCALATION_EVERY_N`), and when the cumulative
1041
+ * byte total crosses `STDIN_DROPPED_BYTES_ERROR_THRESHOLD`. All
1042
+ * other drops log at warn.
1043
+ *
1044
+ * Both signal silent data loss from the consumer's perspective: the
1045
+ * underlying PassThrough still accepts writes, so without an explicit
1046
+ * listener the user sees a hung turn instead of an error. This helper
1047
+ * provides the "log at minimum" guarantee — subclasses or future
1048
+ * K8s-aware paths may override to escalate further (e.g. emit a
1049
+ * session error event, abort the turn).
1050
+ *
1051
+ * Idempotent on two axes:
1052
+ * 1. Safe on non-SidecarProcess procs — Node ChildProcess (Docker path)
1053
+ * never emits these events, so the listeners simply never fire.
1054
+ * 2. Safe on repeat calls — the proc is stamped with a Symbol marker
1055
+ * after the first wiring; subsequent calls short-circuit so a
1056
+ * resume/reconnect caller cannot accumulate duplicate listeners
1057
+ * (and therefore duplicate logs) on the same proc.
1058
+ *
1059
+ * @param {EventEmitter|null|undefined} proc — the spawned process from
1060
+ * `spawnClaudeCodeProcess`. May be a Node ChildProcess (Docker path)
1061
+ * or a SidecarProcess (K8s path); only the latter emits these events.
1062
+ */
1063
+ _attachSidecarProcessListeners(proc) {
1064
+ if (!proc || typeof proc.on !== 'function') return
1065
+ // Re-wiring guard (#3504 review): stamp the proc on first attach so
1066
+ // duplicate calls don't pile up listeners. Symbol-keyed so it can't
1067
+ // collide with consumer code or arbitrary EventEmitters used as stubs.
1068
+ if (proc[SIDECAR_LISTENERS_ATTACHED]) return
1069
+ proc[SIDECAR_LISTENERS_ATTACHED] = true
1070
+
1071
+ proc.on('stdin_dropped', (info) => {
1072
+ // #3506: track a cumulative byte counter and escalate to error
1073
+ // level on the first drop, every Nth drop, and when the running
1074
+ // total crosses STDIN_DROPPED_BYTES_ERROR_THRESHOLD. Other drops
1075
+ // log at warn so the signal stays loud without flooding logs.
1076
+ const rawBytes = info?.bytes
1077
+ const knownBytes = typeof rawBytes === 'number' && Number.isFinite(rawBytes)
1078
+ const bytesLabel = knownBytes ? `${rawBytes} bytes` : 'unknown bytes'
1079
+ const reason = info?.reason ?? 'unknown'
1080
+
1081
+ this._stdinDroppedCount += 1
1082
+ if (knownBytes && rawBytes > 0) {
1083
+ this._stdinDroppedBytesTotal += rawBytes
1084
+ }
1085
+
1086
+ const cumulative = this._stdinDroppedBytesTotal
1087
+ const dropCount = this._stdinDroppedCount
1088
+
1089
+ const isFirstDrop = dropCount === 1
1090
+ const crossedByteThreshold =
1091
+ !this._stdinDroppedThresholdLogged &&
1092
+ cumulative >= STDIN_DROPPED_BYTES_ERROR_THRESHOLD
1093
+ const hitCountCadence =
1094
+ dropCount > 1 && dropCount % STDIN_DROPPED_ESCALATION_EVERY_N === 0
1095
+
1096
+ const escalate = isFirstDrop || crossedByteThreshold || hitCountCadence
1097
+ if (crossedByteThreshold) {
1098
+ this._stdinDroppedThresholdLogged = true
1099
+ }
1100
+
1101
+ // #3543: keep the raw byte count for scriptable log consumers and
1102
+ // append a humanised KiB/MiB/GiB suffix so threshold-cross lines are
1103
+ // easier to scan at a glance. Format: `cumulative=N bytes (X.X MiB)`.
1104
+ const cumulativeHuman = formatBytes(cumulative)
1105
+ const message =
1106
+ `Sidecar stdin chunk dropped (${bytesLabel}, reason=${reason}, ` +
1107
+ `cumulative=${cumulative} bytes (${cumulativeHuman}) over ${dropCount} drops) — ` +
1108
+ 'turn input was truncated; consumer may need to retry'
1109
+
1110
+ // #4828: session-scoped when init has fired; falls back to module
1111
+ // `log` for stdin drops that occur pre-init (rare — SidecarProcess
1112
+ // listener attach happens after spawn, before init normally arrives).
1113
+ if (escalate) {
1114
+ ;(this._log || log).error(message)
1115
+ } else {
1116
+ ;(this._log || log).warn(message)
1117
+ }
1118
+
1119
+ // #3544: surface the cumulative totals as a session-level event so
1120
+ // SessionManager can proxy it onto the unified `session_event`
1121
+ // envelope. Dashboards and the mobile app see "X bytes lost over N
1122
+ // drops" instead of a hung turn. Emitted on every drop (not only
1123
+ // escalations) so the dashboard counter stays live; the `escalated`
1124
+ // flag lets the UI distinguish a "first drop / threshold-cross /
1125
+ // every-Nth" loud signal from routine warn-level updates.
1126
+ this.emit('stdin_dropped_totals', {
1127
+ bytes: cumulative,
1128
+ count: dropCount,
1129
+ reason,
1130
+ escalated: escalate,
1131
+ })
1132
+ })
1133
+
1134
+ proc.on('stdin_disabled', () => {
1135
+ // #3468 + #3501: SESSION-STICKY semantics. Once any spawn under this
1136
+ // session emits 'stdin_disabled' we latch `_stdinForwardingDisabled`
1137
+ // and log a single warn for the lifetime of the session. Subsequent
1138
+ // spawns (next turn, post-reconnect retry) that fire their own
1139
+ // 'stdin_disabled' are intentionally silenced.
1140
+ //
1141
+ // Trade-off (decided in #3501): per-spawn warns would surface every
1142
+ // reconnect-induced loss but spam the operator log on a session that
1143
+ // is already known to be in the disabled state — the actionable signal
1144
+ // (reconnect/restart) was already delivered. The session-sticky path
1145
+ // keeps the warn high-signal: one warn = "this session lost stdin
1146
+ // forwarding"; the latched flag is the persistent diagnostic for
1147
+ // anything more granular (e.g. metrics, dashboards). If a future
1148
+ // K8s-aware subclass wants per-spawn visibility it can override this
1149
+ // method or read `_stdinForwardingDisabled` directly.
1150
+ if (this._stdinForwardingDisabled) return
1151
+ this._stdinForwardingDisabled = true
1152
+ // #3536 review: SidecarProcess explicitly does NOT re-wire stdin on
1153
+ // WS reconnect (see k8s.js `stdin_disabled signal` block) — once this
1154
+ // signal fires forwarding is permanently lost for the lifetime of the
1155
+ // session. Recommend a session restart only; mentioning reconnect
1156
+ // contradicts `recoverable: false` and misleads users into a path
1157
+ // that cannot work.
1158
+ const message = 'Sidecar stdin forwarding is disabled — further writes will be ' +
1159
+ 'silently dropped; restart this session to recover'
1160
+ // #4828: session-scoped when known; falls back to module `log` for
1161
+ // the rare pre-init case (same rationale as the stdin_dropped path).
1162
+ ;(this._log || log).warn(message)
1163
+ // #3502: surface the disabled flag to paired clients via the session
1164
+ // `error` channel. SessionManager._wireSessionEvents proxies `error`
1165
+ // into the unified `session_event` envelope, so dashboards and the
1166
+ // mobile app receive a structured frame and can render a "stdin lost
1167
+ // — restart this session" banner instead of seeing a hung turn.
1168
+ // Single emit per session: gated by the same _stdinForwardingDisabled
1169
+ // short-circuit above so a flapping sidecar can't spam errors.
1170
+ this.emit('error', {
1171
+ code: 'stdin_disabled',
1172
+ message,
1173
+ recoverable: false,
1174
+ })
1175
+ })
1176
+ }
1177
+
1178
+ /**
1179
+ * Handle tool_use blocks from assistant messages.
1180
+ * Detects Task tool for agent monitoring.
1181
+ *
1182
+ * Note: AskUserQuestion is NOT handled here — it flows through the
1183
+ * canUseTool callback in _handleAskUserQuestion(), which emits
1184
+ * user_question and waits for respondToQuestion().
1185
+ */
1186
+ _handleToolUseBlock(messageId, block) {
1187
+ // Guard against oversized tool inputs
1188
+ const inputStr = JSON.stringify(block.input || {})
1189
+ if (Buffer.byteLength(inputStr, 'utf8') > this._maxToolInput) {
1190
+ // #4828: session-scoped (tool_use only arrives after init).
1191
+ ;(this._log || log).warn(`Tool input for ${block.name} exceeded ${this._maxToolInput} bytes, skipping`)
1192
+ this.emit('error', {
1193
+ message: `Tool input too large (>${Math.round(this._maxToolInput / 1024)}KB) for ${block.name} — tool use was skipped`,
1194
+ })
1195
+ return
1196
+ }
1197
+
1198
+ // #4307: stash the command text against the tool_use_id so the
1199
+ // matching tool_result (carrying the shellId Claude prints) can
1200
+ // recover it. Strict-boolean run_in_background check; non-Bash
1201
+ // tools and missing inputs are no-ops. The map is the ephemeral
1202
+ // turn-local one — entries that never see a tool_result clear at
1203
+ // turn-end.
1204
+ if (isRunInBackgroundInput(block.name, block.input)) {
1205
+ const cmd = typeof block.input?.command === 'string' ? block.input.command : ''
1206
+ this._pendingBackgroundCommands.set(block.id, cmd)
1207
+ }
1208
+ // #4307: when the agent calls BashOutput on a previously-tracked
1209
+ // shell, drop the pending entry. Whether output was complete or
1210
+ // not, the agent has acknowledged the shell — our local model of
1211
+ // "session is waiting on background work" is stale either way.
1212
+ const bashOutputId = parseBashOutputShellId(block.name, block.input)
1213
+ if (bashOutputId) {
1214
+ this.clearBackgroundShell(bashOutputId)
1215
+ }
1216
+
1217
+ // Delegate Task / EnterPlanMode / ExitPlanMode interpretation to the
1218
+ // shared parser so SdkSession and CliSession cannot drift on tool
1219
+ // semantics. AskUserQuestion is intentionally skipped here — it flows
1220
+ // through the canUseTool callback in _handleAskUserQuestion() and
1221
+ // never reaches this code path.
1222
+ const semantics = extractToolInputSemantics(block.name, block.input)
1223
+ if (!semantics) return
1224
+ if (semantics.kind === 'task') {
1225
+ // #4778: when block.id is missing, mirror the synthesized fallback
1226
+ // used by buildToolStartData (`${messageId}-tool`) so the
1227
+ // agent_spawned toolUseId + _activeAgents key match the wire-emitted
1228
+ // tool_start id. Without this, _activeAgents.set(undefined, ...)
1229
+ // collides on undefined for any fallback-path Task spawn.
1230
+ const toolUseId = block.id || `${messageId}-tool`
1231
+ const agentInfo = {
1232
+ toolUseId,
1233
+ description: semantics.payload.description,
1234
+ startedAt: Date.now(),
1235
+ }
1236
+ this._activeAgents.set(toolUseId, agentInfo)
1237
+ this.emit('agent_spawned', agentInfo)
1238
+ }
1239
+ // EnterPlanMode / ExitPlanMode are not currently surfaced by SdkSession
1240
+ // (plan-mode flow is CliSession-only today). Extracting via the shared
1241
+ // parser leaves the door open without changing observable behavior.
1242
+ }
1243
+
1244
+ /**
1245
+ * #4307: scan a user-role message's tool_result content blocks for
1246
+ * the canonical `Command running in background with ID: <id>` text
1247
+ * and register each pending background shell against the matching
1248
+ * command stashed earlier by `_handleToolUseBlock`.
1249
+ *
1250
+ * Defensive against non-array content (the SDK sometimes ships a
1251
+ * single string for content) and content blocks without `tool_use_id`
1252
+ * (no-op) — the standard tool-loop flow always populates both.
1253
+ *
1254
+ * @param {unknown} content
1255
+ * @private
1256
+ */
1257
+ _recordBackgroundShellsFromToolResults(content) {
1258
+ if (!Array.isArray(content)) return
1259
+ for (const block of content) {
1260
+ if (block?.type !== 'tool_result' || !block.tool_use_id) continue
1261
+ // Flatten the result text the same way `emitToolResults` does so
1262
+ // a shellId in a multi-block content array still matches.
1263
+ let text = ''
1264
+ if (typeof block.content === 'string') {
1265
+ text = block.content
1266
+ } else if (Array.isArray(block.content)) {
1267
+ text = block.content
1268
+ .filter((b) => b?.type === 'text')
1269
+ .map((b) => b.text)
1270
+ .join('\n')
1271
+ }
1272
+ const shellId = parseBackgroundShellId(text)
1273
+ if (!shellId) continue
1274
+ const command = this._pendingBackgroundCommands.get(block.tool_use_id) || ''
1275
+ this._pendingBackgroundCommands.delete(block.tool_use_id)
1276
+ // #5177: capture the output file path from the same tool_result so the
1277
+ // completion sweep can reap the shell on quiescence without a poll.
1278
+ const outputPath = parseBackgroundShellOutputPath(text)
1279
+ this.trackBackgroundShell({ shellId, command, outputPath })
1280
+ }
1281
+ }
1282
+
1283
+ /**
1284
+ * In-process permission handler for canUseTool callback.
1285
+ * Delegates to the PermissionManager.
1286
+ */
1287
+ _handlePermission(toolName, input, signal, suggestions) {
1288
+ return this._permissions.handlePermission(toolName, input, signal, this.permissionMode, suggestions)
1289
+ }
1290
+
1291
+ /**
1292
+ * Resolve a pending permission request (called by WsServer when
1293
+ * the app sends permission_response).
1294
+ */
1295
+ respondToPermission(requestId, decision, editedInput) {
1296
+ return this._permissions.respondToPermission(requestId, decision, editedInput)
1297
+ }
1298
+
1299
+ /**
1300
+ * Send a response to an AskUserQuestion prompt.
1301
+ * In SDK mode, the canUseTool callback is holding a Promise open.
1302
+ * This method resolves it with the user's answer as structured updatedInput.
1303
+ */
1304
+ respondToQuestion(text, answersMap) {
1305
+ this._permissions.respondToQuestion(text, answersMap)
1306
+ }
1307
+
1308
+ /**
1309
+ * Change the model. In SDK mode this doesn't require process restart.
1310
+ * #5374: BaseSession.setModel owns the guard + resolve and fires this hook.
1311
+ */
1312
+ _onModelChanged() {
1313
+ // #4828: session-scoped when init has fired.
1314
+ ;(this._log || log).info(`Model changed to ${this.model || 'default'}`)
1315
+ }
1316
+
1317
+ _onPermissionModeChanged(mode) {
1318
+ this._permissions.clearRules()
1319
+ // #3729: switching TO auto is a "panic button" — drain any pending
1320
+ // permission prompts so the user isn't left staring at modals after
1321
+ // declaring "approve everything". Without this, prompts that were
1322
+ // emitted under the previous mode hang until the user resolves them
1323
+ // or they hit the 5-min timeout, contradicting the bypass semantics.
1324
+ if (mode === 'auto') {
1325
+ this._permissions.autoAllowPending()
1326
+ }
1327
+ // #4828: session-scoped when init has fired.
1328
+ ;(this._log || log).info(`Permission mode changed to ${mode}`)
1329
+ }
1330
+
1331
+ /**
1332
+ * Set per-session permission rules. Delegates to PermissionManager.
1333
+ * @param {Array<{tool: string, decision: string}>} rules
1334
+ */
1335
+ setPermissionRules(rules) {
1336
+ if (typeof this._permissions.setRules === 'function') {
1337
+ this._permissions.setRules(rules)
1338
+ }
1339
+ }
1340
+
1341
+ /**
1342
+ * Get current per-session permission rules. Delegates to PermissionManager.
1343
+ * @returns {Array<{tool: string, decision: string}>}
1344
+ */
1345
+ getPermissionRules() {
1346
+ if (typeof this._permissions.getRules === 'function') {
1347
+ return this._permissions.getRules()
1348
+ }
1349
+ return []
1350
+ }
1351
+
1352
+ /**
1353
+ * Clear all per-session permission rules. Delegates to PermissionManager.
1354
+ */
1355
+ clearPermissionRules() {
1356
+ if (typeof this._permissions.clearRules === 'function') {
1357
+ this._permissions.clearRules()
1358
+ }
1359
+ }
1360
+
1361
+ /**
1362
+ * Set thinking level by adjusting max thinking tokens.
1363
+ * @param {string} level - 'default' | 'high' | 'max'
1364
+ */
1365
+ async setThinkingLevel(level) {
1366
+ const budget = SdkSession.THINKING_BUDGETS[level] ?? null
1367
+ this._thinkingLevel = level === 'default' ? null : level
1368
+
1369
+ if (this._query && typeof this._query.setMaxThinkingTokens === 'function') {
1370
+ try {
1371
+ await this._query.setMaxThinkingTokens(budget)
1372
+ // #4828: session-scoped (setThinkingLevel only takes effect with
1373
+ // an active query — strictly post-init).
1374
+ ;(this._log || log).info(`Thinking level set to ${level} (${budget ?? 'adaptive'} tokens)`)
1375
+ } catch (err) {
1376
+ ;(this._log || log).warn(`Failed to set thinking level: ${err.message}`)
1377
+ }
1378
+ }
1379
+
1380
+ // Note: thinking_level_changed is broadcast by the WS handler, not emitted here
1381
+ }
1382
+
1383
+ /**
1384
+ * Map internal permission mode to SDK PermissionMode.
1385
+ */
1386
+ _sdkPermissionMode() {
1387
+ switch (this.permissionMode) {
1388
+ case 'auto': return 'bypassPermissions'
1389
+ case 'plan': return 'plan'
1390
+ default: return 'default'
1391
+ }
1392
+ }
1393
+
1394
+ /**
1395
+ * Query the SDK for available models and emit models_updated.
1396
+ * Called after session init — non-blocking, failures are logged and ignored.
1397
+ */
1398
+ async _fetchSupportedModels() {
1399
+ if (!this._query || typeof this._query.supportedModels !== 'function') return
1400
+
1401
+ try {
1402
+ const sdkModels = await this._query.supportedModels()
1403
+ const converted = updateModels(sdkModels)
1404
+ if (converted && converted.length > 0) {
1405
+ // #4828: session-scoped (called from init handler so _log is set).
1406
+ ;(this._log || log).info(`Dynamic model list: ${converted.map(m => m.id).join(', ')}`)
1407
+ saveModelsCache()
1408
+ this.emit('models_updated', { models: converted })
1409
+ }
1410
+ } catch (err) {
1411
+ ;(this._log || log).warn(`Failed to fetch supported models: ${err.message}`)
1412
+ }
1413
+ }
1414
+
1415
+ /**
1416
+ * #5269: record a Task subagent's `task_id ↔ tool_use_id` mapping. Tolerant
1417
+ * of either id arriving missing (the SDK marks `tool_use_id` optional on
1418
+ * task messages) and of `task_started` racing ahead of `agent_spawned` — the
1419
+ * map is keyed by tool_use_id and read lazily at cancel time, so order does
1420
+ * not matter.
1421
+ * @param {unknown} toolUseId
1422
+ * @param {unknown} taskId
1423
+ * @private
1424
+ */
1425
+ _captureTaskId(toolUseId, taskId) {
1426
+ if (typeof toolUseId !== 'string' || !toolUseId) return
1427
+ if (typeof taskId !== 'string' || !taskId) return
1428
+ this._taskIdByToolUseId.set(toolUseId, taskId)
1429
+ }
1430
+
1431
+ /**
1432
+ * #5269: finalize a Task subagent identified by its `tool_use_id` — drop the
1433
+ * task-id mapping and, if the agent is still tracked, balance the
1434
+ * `agent_spawned` with a matching `agent_completed` + `_activeAgents` delete
1435
+ * so the activity node terminates immediately (the turn-end sweep would
1436
+ * otherwise be the only finalizer on the SDK path). Idempotent.
1437
+ * @param {unknown} toolUseId
1438
+ * @private
1439
+ */
1440
+ _finalizeAgentByToolUseId(toolUseId) {
1441
+ if (typeof toolUseId !== 'string' || !toolUseId) return
1442
+ this._taskIdByToolUseId.delete(toolUseId)
1443
+ if (this._activeAgents.has(toolUseId)) {
1444
+ this._activeAgents.delete(toolUseId)
1445
+ this.emit('agent_completed', { toolUseId })
1446
+ }
1447
+ }
1448
+
1449
+ /**
1450
+ * #5269 (Control Room Phase 2a): cancel a single in-flight subagent by its
1451
+ * activity id (which, for an `agent` node, IS the Task's `tool_use_id`).
1452
+ * Translates the id to the SDK `task_id` and calls `query.stopTask()`. The
1453
+ * SDK responds with a `task_notification` (status `stopped`), which
1454
+ * `_finalizeAgentByToolUseId` turns into the terminal activity delta; we also
1455
+ * finalize optimistically on success so the node clears without waiting.
1456
+ *
1457
+ * Only `agent` nodes are cancellable — shells/tools are not individually
1458
+ * stoppable (chroxy doesn't own them). Returns a structured result rather
1459
+ * than throwing so the WS handler can map it to a reply.
1460
+ *
1461
+ * @param {string} activityId
1462
+ * @returns {Promise<{ ok: boolean, reason?: string, error?: string }>}
1463
+ */
1464
+ async cancelActivity(activityId) {
1465
+ if (typeof activityId !== 'string' || !activityId) return { ok: false, reason: 'invalid-id' }
1466
+ const entry = this._activity.getEntry(activityId)
1467
+ if (!entry) return { ok: false, reason: 'not-found' }
1468
+ if (entry.kind !== 'agent') {
1469
+ // Shells and tool calls have no per-node cancel surface. Distinguish the
1470
+ // shell case so the UI can explain "use Interrupt turn" rather than
1471
+ // implying a transient error.
1472
+ return { ok: false, reason: entry.kind === 'shell' ? 'shell-not-cancellable' : 'not-cancellable' }
1473
+ }
1474
+ // A finished agent isn't retained in the registry (terminal nodes are
1475
+ // dropped on _end), so a stale cancel for one resolves as not-found above —
1476
+ // no separate already-finished branch is reachable here.
1477
+ const taskId = this._taskIdByToolUseId.get(activityId)
1478
+ if (!taskId) {
1479
+ // agent_spawned landed but task_started hasn't (or this SDK build doesn't
1480
+ // emit task lifecycle messages) — we have no id to stop.
1481
+ return { ok: false, reason: 'no-task-id' }
1482
+ }
1483
+ // Feature-detect stopTask (mirrors the supportedModels / setMaxThinkingTokens
1484
+ // guards) — older SDK builds may not expose it even though interrupt() works.
1485
+ if (!this._query || typeof this._query.stopTask !== 'function') {
1486
+ return { ok: false, reason: 'not-supported' }
1487
+ }
1488
+ ;(this._log || log).info(`Cancelling subagent ${activityId} (task ${taskId})`)
1489
+ try {
1490
+ await this._query.stopTask(taskId)
1491
+ } catch (err) {
1492
+ ;(this._log || log).warn(`stopTask failed for ${activityId}: ${err.message}`)
1493
+ return { ok: false, reason: 'stop-failed', error: err.message }
1494
+ }
1495
+ // Optimistic finalize — idempotent with the incoming task_notification.
1496
+ this._finalizeAgentByToolUseId(activityId)
1497
+ return { ok: true }
1498
+ }
1499
+
1500
+ /**
1501
+ * Interrupt the current query.
1502
+ */
1503
+ async interrupt() {
1504
+ // #5936: a deliberate Stop cancels the owner's queued follow-ups (cancel,
1505
+ // not flush) — clear BEFORE the abort so the turn-end `result` flush in the
1506
+ // `finally` sees an empty queue and nothing auto-fires after the halt.
1507
+ // Runs even when there is no active `_query` (queued sends with the turn
1508
+ // already settling) so an interrupt never strands a queued message.
1509
+ this.clearOutgoingQueue()
1510
+
1511
+ if (!this._query) return
1512
+
1513
+ // #4881: mark the imminent query teardown as user-initiated so the
1514
+ // _callQuery catch block suppresses the AbortError-flavored "Query error"
1515
+ // emit and instead surfaces a quiet `stopped` event. Cleared in the
1516
+ // catch/finally (single-use, mirrors CliSession#4602).
1517
+ this.markIntentionalStop()
1518
+
1519
+ // #4828: session-scoped (interrupt() only meaningful with an active query).
1520
+ ;(this._log || log).info('Interrupting query')
1521
+ try {
1522
+ await this._query.interrupt()
1523
+ } catch (err) {
1524
+ ;(this._log || log).warn(`Interrupt error: ${err.message}`)
1525
+ }
1526
+ }
1527
+
1528
+ /**
1529
+ * Handle the SOFT inactivity warning (#3899) — `_resultTimeoutMs` of
1530
+ * silence with no SDK event to reset it (default 30 min). Unlike
1531
+ * `_handleHardTimeout`, this does NOT clear busy state, does NOT
1532
+ * auto-deny pending permissions, and does NOT emit `error`. It just
1533
+ * emits a transient `inactivity_warning` event so the client can
1534
+ * render a check-in chip ("Status update?") and (if push is wired)
1535
+ * deliver an Expo notification.
1536
+ *
1537
+ * The hard-cap timer continues running in parallel — if the user
1538
+ * never engages, the kill path eventually fires anyway. The soft
1539
+ * timer is NOT re-armed here; each silent stretch fires exactly
1540
+ * one warning (any subsequent activity resets both timers, so the
1541
+ * next stretch fires a fresh warning).
1542
+ */
1543
+ _handleInactivityWarning(messageId) {
1544
+ if (!this._isBusy) return
1545
+ const idleMs = this._resultTimeoutMs
1546
+ const friendly = formatIdleDuration(idleMs)
1547
+ // #4828: session-scoped (inactivity warning fires from active turn).
1548
+ ;(this._log || log).info(`Inactivity warning (${friendly}) — session alive, prompting check-in`)
1549
+ this.emit('inactivity_warning', {
1550
+ messageId,
1551
+ idleMs,
1552
+ prefab: 'Status update?',
1553
+ })
1554
+ }
1555
+
1556
+ /**
1557
+ * Handle the HARD-cap timeout (#3899; pre-#3899 this was the only
1558
+ * handler, named `_handleResultTimeout` — kept as the absolute
1559
+ * backstop for genuinely stuck sessions when the user never check-
1560
+ * ins on the soft warning). Emits stream_end (if streaming), auto-
1561
+ * denies any pending permissions, emits `permission_expired` for
1562
+ * each so the client UI clears stale prompts, then clears state and
1563
+ * emits an error. Issue #2831 added the permission cleanup so late
1564
+ * user approvals don't resolve into an abandoned SDK turn.
1565
+ */
1566
+ _handleHardTimeout(messageId, hasStreamStarted) {
1567
+ if (!this._isBusy) return
1568
+ const friendly = formatIdleDuration(this._hardTimeoutMs)
1569
+ // #4828: session-scoped (hard-cap fires from active turn).
1570
+ ;(this._log || log).warn(`Hard-cap timeout (${friendly} inactivity) — force-clearing busy state`)
1571
+ if (hasStreamStarted) {
1572
+ this.emit('stream_end', { messageId })
1573
+ }
1574
+ // Fire permission_expired for every outstanding permission BEFORE
1575
+ // clearing state — the underlying Map is cleared by _clearMessageState
1576
+ // → PermissionManager.clearAll() below.
1577
+ if (this._pendingPermissions && this._pendingPermissions.size > 0) {
1578
+ for (const [requestId] of this._pendingPermissions) {
1579
+ this.emit('permission_expired', { requestId, message: 'Permission request expired (session timeout)' })
1580
+ }
1581
+ }
1582
+ // Attempt to abort the SDK query generator so no further events land
1583
+ // into a cleared message. Best-effort — the SDK's generator may not
1584
+ // support .return()/.throw() uniformly.
1585
+ this._abortActiveQuery()
1586
+ this._clearMessageState()
1587
+ this.emit('error', { message: `Response timed out after ${friendly} of inactivity` })
1588
+ }
1589
+
1590
+ /**
1591
+ * Handle the STREAM-STALL recovery timer (#4467). Fires when the SDK
1592
+ * has been silent for `_streamStallTimeoutMs` despite the session
1593
+ * being busy — typically a half-open HTTPS to the Anthropic API that
1594
+ * the OS hasn't surfaced as an error yet. Distinct from the SOFT
1595
+ * inactivity warning (which is passive — just a chip) and the HARD
1596
+ * cap (which is the absolute backstop at 2h): this is the ACTIVE
1597
+ * recovery path so the user can retry without clicking Stop.
1598
+ *
1599
+ * On fire: log with context (messageId, elapsed) for triage; abort
1600
+ * the in-flight query so further events don't land in a cleared
1601
+ * context; emit `stream_end` (if streaming) then `error` with
1602
+ * `code: 'stream_stall'` so the dashboard's StreamStallChip can
1603
+ * render a dedicated retry affordance distinct from generic errors;
1604
+ * clear message state so `_isBusy` flips false and the next
1605
+ * `sendMessage` is no longer rejected by the busy guard.
1606
+ */
1607
+ _handleStreamStall(messageId, hasStreamStarted) {
1608
+ if (!this._isBusy) return
1609
+ const friendly = formatIdleDuration(this._streamStallTimeoutMs)
1610
+ // #4828: session-scoped (stall fires from active turn).
1611
+ ;(this._log || log).warn(
1612
+ `Stream stalled (${friendly}, messageId=${messageId}) — clearing busy state for retry`,
1613
+ )
1614
+ if (hasStreamStarted) {
1615
+ this.emit('stream_end', { messageId })
1616
+ }
1617
+ // Attempt to abort the SDK query generator so no further events land
1618
+ // into a cleared message context. Best-effort — matches _handleHardTimeout.
1619
+ this._abortActiveQuery()
1620
+ // #4616: snapshot sessionId BEFORE _clearMessageState wipes it so the
1621
+ // synthetic `result` event below carries the correct identifier.
1622
+ const sessionId = this._sdkSessionId || this._sessionId
1623
+ this._clearMessageState()
1624
+ // #4616: emit a synthetic `result` so event-normalizer fans it to
1625
+ // `agent_idle`. Per #4308 handleAgentIdle clears `activeTools: []`
1626
+ // as a safety net, which is what stops the dashboard's footer pill
1627
+ // from ticking after the stall. CLI does the equivalent via
1628
+ // _emitInterruptedTurnResult (stream_end + result); the SDK was
1629
+ // previously missing the `result` half of the pair. cost:null skips
1630
+ // session-manager billing accumulation (mirrors CLI).
1631
+ this.emit('result', { cost: null, duration: this._streamStallTimeoutMs, usage: null, sessionId })
1632
+ this.emit('error', {
1633
+ code: 'stream_stall',
1634
+ message: `Stream stalled — no response for ${friendly}. Try sending again.`,
1635
+ })
1636
+ }
1637
+
1638
+ /**
1639
+ * Best-effort abort of the active SDK query generator. Used when the
1640
+ * session times out mid-turn so tool results don't stream into a
1641
+ * cleared message context (#2831).
1642
+ */
1643
+ _abortActiveQuery() {
1644
+ const q = this._query
1645
+ if (!q) return
1646
+ try {
1647
+ if (typeof q.interrupt === 'function') {
1648
+ const p = q.interrupt()
1649
+ if (p && typeof p.catch === 'function') {
1650
+ // #4828: session-scoped (abort runs strictly post-init).
1651
+ p.catch((err) => (this._log || log).warn(`Query interrupt (timeout) failed: ${err.message}`))
1652
+ }
1653
+ } else if (typeof q.return === 'function') {
1654
+ q.return()
1655
+ }
1656
+ } catch (err) {
1657
+ // #4828: session-scoped.
1658
+ ;(this._log || log).warn(`Query abort (timeout) failed: ${err.message}`)
1659
+ }
1660
+ }
1661
+
1662
+ /**
1663
+ * Pause the inactivity timer because a permission prompt is
1664
+ * outstanding. Ref-counted so concurrent prompts all have to resolve
1665
+ * before the timer re-arms. #2831.
1666
+ */
1667
+ _pauseResultTimeoutForPermission() {
1668
+ this._permissionPauseCount++
1669
+ if (this._permissionPauseCount === 1) {
1670
+ this._resultTimeoutPaused = true
1671
+ // #3899: clear BOTH the soft warning and hard cap. Awaiting user
1672
+ // input on a permission is not inactivity; both re-arm together
1673
+ // via `_resetResultTimeout()` when the last prompt resolves.
1674
+ if (this._resultTimeout) {
1675
+ clearTimeout(this._resultTimeout)
1676
+ this._resultTimeout = null
1677
+ }
1678
+ if (this._hardTimeout) {
1679
+ clearTimeout(this._hardTimeout)
1680
+ this._hardTimeout = null
1681
+ }
1682
+ // #4467: clear the stall timer too — waiting on the user is not a stall.
1683
+ if (this._streamStallTimeout) {
1684
+ clearTimeout(this._streamStallTimeout)
1685
+ this._streamStallTimeout = null
1686
+ }
1687
+ }
1688
+ }
1689
+
1690
+ /**
1691
+ * Resume the inactivity timer when a permission prompt is resolved.
1692
+ * Only re-arms once the last concurrent prompt clears. #2831.
1693
+ */
1694
+ _resumeResultTimeoutForPermission() {
1695
+ if (this._permissionPauseCount === 0) return
1696
+ this._permissionPauseCount--
1697
+ if (this._permissionPauseCount === 0) {
1698
+ this._resultTimeoutPaused = false
1699
+ if (this._isBusy && typeof this._resetResultTimeout === 'function') {
1700
+ this._resetResultTimeout()
1701
+ }
1702
+ }
1703
+ }
1704
+
1705
+ /**
1706
+ * Clear per-message state, marking us as ready for the next message.
1707
+ */
1708
+ _clearMessageState() {
1709
+ super._clearMessageState()
1710
+ this._permissions.clearAll()
1711
+ // Pause counter is tied to the previous message — reset so the next
1712
+ // message starts with a fresh counter.
1713
+ this._permissionPauseCount = 0
1714
+ this._resultTimeoutPaused = false
1715
+ this._resetResultTimeout = null
1716
+ }
1717
+
1718
+ /**
1719
+ * Clean up resources.
1720
+ */
1721
+ destroy() {
1722
+ this._destroying = true
1723
+ // #5936: tear down the shared outgoing queue silently — no message_dequeued
1724
+ // (which signals "sent") for a session that's going away.
1725
+ this.clearOutgoingQueue({ emit: false })
1726
+ // #4881: clear so a teardown after interrupt() never leaks the flag past
1727
+ // this session instance. Mirrors CliSession.destroy() (#4602).
1728
+ this._clearIntentionalStop()
1729
+ // #5269: drop subagent task-id mappings on teardown.
1730
+ this._taskIdByToolUseId.clear()
1731
+
1732
+ if (this._resultTimeout) {
1733
+ clearTimeout(this._resultTimeout)
1734
+ this._resultTimeout = null
1735
+ }
1736
+ if (this._hardTimeout) {
1737
+ clearTimeout(this._hardTimeout)
1738
+ this._hardTimeout = null
1739
+ }
1740
+ // #4467: clear stall timer on destroy so a stale fire can't run
1741
+ // against a torn-down session.
1742
+ if (this._streamStallTimeout) {
1743
+ clearTimeout(this._streamStallTimeout)
1744
+ this._streamStallTimeout = null
1745
+ }
1746
+
1747
+ // Interrupt active query
1748
+ if (this._query) {
1749
+ this._query.interrupt().catch((err) => {
1750
+ // #4828: session-scoped when init has fired.
1751
+ ;(this._log || log).warn(`Failed to interrupt active query: ${err.message} (non-critical, session destroying)`)
1752
+ })
1753
+ this._query = null
1754
+ }
1755
+
1756
+ // Emit completions for any tracked agents and clear busy state
1757
+ this._clearMessageState()
1758
+
1759
+ // #4307: drop any pending background-shell entries so the session-
1760
+ // list snapshot doesn't carry phantom entries for a destroyed
1761
+ // session and the map can't leak. Done after _clearMessageState so
1762
+ // the canonical "turn-end keeps pending shells" invariant from
1763
+ // _clearMessageState is preserved — the explicit destroy hook is
1764
+ // the only path that removes them.
1765
+ this._destroyPendingBackgroundShells()
1766
+
1767
+ // Clean up permission manager
1768
+ this._permissions.destroy()
1769
+
1770
+ this._processReady = false
1771
+ this.removeAllListeners()
1772
+ }
1773
+ }