@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,3257 @@
1
+ import { EventEmitter } from 'events'
2
+ import { randomBytes } from 'crypto'
3
+ import { statSync, mkdirSync, rmSync } from 'fs'
4
+ import { join, resolve, dirname } from 'path'
5
+ import { homedir } from 'os'
6
+ import { execFileSync } from 'child_process'
7
+ import { getProvider, getProviderAuthInfo, DEFAULT_PROVIDER } from './providers.js'
8
+ import { isClaudeProvider } from './models.js'
9
+ import { billingClassForProvider, BILLING_CLASSES } from './billing-class.js'
10
+ import { MonthlyProgrammaticBudgetManager } from './billing-budget.js'
11
+ import { runProviderPreflight, ProviderBinaryNotFoundError, ProviderCredentialMissingError } from './utils/preflight.js'
12
+ import { GIT } from './git.js'
13
+ import { sweepOrphanChroxyWorktrees } from './worktree-gc.js'
14
+ import { resolveJsonlPath, readConversationHistoryAsync } from './jsonl-reader.js'
15
+ import { readSessionContext } from './session-context.js'
16
+ import { parseDuration, isOperatorTimeoutInRange } from './duration.js'
17
+ import { SessionLockManager } from './session-lock.js'
18
+ import { CostBudgetManager } from './cost-budget-manager.js'
19
+ import { SessionStatePersistence } from './session-state-persistence.js'
20
+ import { SessionTimeoutManager, formatIdleDuration } from './session-timeout-manager.js'
21
+ import { SessionMessageHistory } from './session-message-history.js'
22
+ import { SkillsUsageRecorder } from './skills-usage.js'
23
+ import { resolveSessionPreset, foldPreamble } from './session-preset.js'
24
+ import { SessionPresetTrustStore } from './session-preset-trust.js'
25
+ import { createLogger } from './logger.js'
26
+ import { ExternalSessionRegistry } from './external-session-registry.js'
27
+ import { metrics } from './metrics.js'
28
+ import { auditShellDestroy } from './shell-audit.js'
29
+ import { recordShell, forgetShell, reapOrphanShells } from './user-shell-registry.js'
30
+ import { getErrorMessage } from './utils/error-message.js'
31
+ import {
32
+ forwardPerSessionSettingsToProviderOpts,
33
+ serializePerSessionSettings,
34
+ restorePerSessionSettings,
35
+ } from './per-session-settings.js'
36
+
37
+ const log = createLogger('session-manager')
38
+ const DEFAULT_STATE_FILE = join(homedir(), '.chroxy', 'session-state.json')
39
+ // #5982 — grace before auto-removing an exited user-shell session, so a live
40
+ // viewer sees the "[shell exited]" marker before the session vanishes.
41
+ const AUTO_REMOVE_ON_EXIT_DELAY_MS = 1500
42
+
43
+ /**
44
+ * Zero-initialized cumulative usage record (#4072). Lives on the session
45
+ * entry; increments on every priced `result` event. Field names are
46
+ * camelCase here even though the SDK delivers snake_case usage — the
47
+ * client-facing API (`session_usage` event, `listSessions()` snapshot)
48
+ * uses camelCase to match chroxy's protocol convention.
49
+ */
50
+ function makeZeroCumulativeUsage() {
51
+ return {
52
+ inputTokens: 0,
53
+ outputTokens: 0,
54
+ cacheReadTokens: 0,
55
+ cacheCreationTokens: 0,
56
+ costUsd: 0,
57
+ turnsBilled: 0,
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Base error class for session management operations.
63
+ */
64
+ export class SessionError extends Error {
65
+ constructor(message, code) {
66
+ super(message)
67
+ this.name = 'SessionError'
68
+ this.code = code
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Thrown when maximum session limit is reached.
74
+ */
75
+ export class SessionLimitError extends SessionError {
76
+ constructor(maxSessions) {
77
+ super(`Maximum sessions (${maxSessions}) reached`, 'SESSION_LIMIT_REACHED')
78
+ this.name = 'SessionLimitError'
79
+ this.maxSessions = maxSessions
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Thrown when session directory validation fails.
85
+ */
86
+ export class SessionDirectoryError extends SessionError {
87
+ constructor(message, path) {
88
+ super(message, 'INVALID_DIRECTORY')
89
+ this.name = 'SessionDirectoryError'
90
+ this.path = path
91
+ }
92
+ }
93
+
94
+ /**
95
+ * #5985 (epic #5982): thrown when a `user-shell` session is requested but the
96
+ * server has not opted in (`userShell.enabled !== true`). Secure-by-default —
97
+ * a user shell is arbitrary code execution on the dev machine, so it is off
98
+ * until an explicit local config edit enables it.
99
+ */
100
+ export class UserShellDisabledError extends SessionError {
101
+ constructor() {
102
+ super(
103
+ 'User-shell sessions are disabled on this server. To enable, set userShell.enabled:true in the server config file (requires local filesystem access). Default is disabled for security.',
104
+ 'USER_SHELL_DISABLED'
105
+ )
106
+ this.name = 'UserShellDisabledError'
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Thrown when worktree creation fails (e.g. non-git directory).
112
+ */
113
+ export class WorktreeError extends SessionError {
114
+ constructor(message) {
115
+ super(message, 'WORKTREE_ERROR')
116
+ this.name = 'WorktreeError'
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Thrown when an initial session model is not valid for the selected provider.
122
+ */
123
+ export class ProviderModelNotSupportedError extends SessionError {
124
+ constructor({ provider, model, supported }) {
125
+ const suffix = Array.isArray(supported) && supported.length > 0
126
+ ? ` Supported models: ${supported.join(', ')}.`
127
+ : ''
128
+ super(`Model '${model}' is not supported by provider '${provider}'.${suffix}`, 'MODEL_NOT_SUPPORTED_BY_PROVIDER')
129
+ this.name = 'ProviderModelNotSupportedError'
130
+ this.provider = provider
131
+ this.model = model
132
+ this.supported = supported || []
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Default base directory for session worktrees.
138
+ * @type {string}
139
+ */
140
+ const DEFAULT_WORKTREE_BASE = join(homedir(), '.chroxy', 'worktrees')
141
+
142
+ /**
143
+ * Manages the lifecycle of multiple CLI sessions.
144
+ *
145
+ * Events emitted:
146
+ * session_event { sessionId, event, data } — proxied from each session
147
+ * Events: ready, stream_start, stream_delta, stream_end, message, tool_start, result, error
148
+ * session_created { sessionId, name, cwd }
149
+ * session_destroyed { sessionId }
150
+ * session_updated { sessionId, name }
151
+ * session_warning { sessionId, name, reason, message, remainingMs } — session nearing idle timeout
152
+ * session_timeout { sessionId, name, idleMs } — session destroyed due to idle timeout
153
+ * session_restore_failed { sessionId, name, provider, cwd, model, permissionMode, errorCode, errorMessage, originalHistoryPreserved, historyLength }
154
+ * — emitted when a session in the persisted state file fails to restore (e.g. missing env var).
155
+ * History on disk is preserved so the user can retry after fixing the underlying issue.
156
+ * session_create_failed { sessionId, name, provider, cwd, model, errorCode, errorMessage } — #5731 T6:
157
+ * a FRESH session whose async provider start() rejected (e.g. claude-tui's PTY failed to spawn).
158
+ * The session is fully destroyed (no history to preserve); this carries the reason so the
159
+ * forwarder can surface a `session_error` toast before the `session_destroyed` lands.
160
+ * session_persist_failed { sessionId, name } — #5701: a synchronous flush of a
161
+ * session-list mutation (create/rename/destroy) failed to write to disk
162
+ * (disk full / locked file / read-only home), so the change may be lost on
163
+ * restart. Observable signal; a client-facing surface is a follow-up.
164
+ */
165
+
166
+ // Re-export formatIdleDuration from SessionTimeoutManager for backward compatibility
167
+ export { formatIdleDuration }
168
+
169
+ // Re-export preflight errors so call sites that catch createSession() failures
170
+ // can detect/branch on PROVIDER_BINARY_NOT_FOUND / PROVIDER_CREDENTIAL_MISSING
171
+ // without taking a separate dependency on utils/preflight.js.
172
+ export { ProviderBinaryNotFoundError, ProviderCredentialMissingError }
173
+
174
+ /**
175
+ * @typedef {Object} SessionManagerConfig
176
+ *
177
+ * Server identity
178
+ * @property {number} [port] - Server port (used in push notification metadata)
179
+ * @property {string} [apiToken] - API token for authentication
180
+ *
181
+ * Session defaults
182
+ * @property {number} [maxSessions=5] - Maximum concurrent sessions
183
+ * @property {string} [defaultCwd] - Default working directory (falls back to process.cwd())
184
+ * @property {string} [defaultModel] - Default Claude model identifier
185
+ * @property {string} [defaultPermissionMode='approve'] - Default permission mode
186
+ * @property {boolean} [defaultSkipPermissions=false] - Default for `skipPermissions` on
187
+ * createSession() — used to seed the
188
+ * auto-created Default session at boot
189
+ * when the server was launched with
190
+ * `chroxy start --dangerously-skip-permissions`
191
+ * (#4209). TUI-only at the spawn site;
192
+ * other providers ignore it harmlessly.
193
+ * @property {string} [providerType='claude-sdk'] - Provider type from providers.js registry
194
+ *
195
+ * Session behavior
196
+ * @property {string} [sessionTimeout] - Idle timeout duration string (e.g. '30m', '2h'), parsed by parseDuration()
197
+ * @property {number} [maxToolInput] - Max characters for tool input display
198
+ * @property {Array} [transforms=[]] - Message transform functions
199
+ * @property {object} [sandbox] - SDK sandbox settings for lightweight isolation
200
+ * @property {number} [costBudget] - Per-session cost budget in dollars (e.g. 5.00).
201
+ * Applied independently to each session; not a shared/global pool.
202
+ *
203
+ * State persistence
204
+ * @property {string} [stateFilePath] - Path to session state JSON file (default: ~/.chroxy/session-state.json)
205
+ * @property {number} [stateTtlMs] - Max age of persisted state before discard (default: 24 hours)
206
+ * @property {number} [persistDebounceMs=2000] - Debounce interval for state file writes
207
+ *
208
+ * Message history
209
+ * @property {number} [maxMessages=1000] - Max history messages per session (alias: maxHistory)
210
+ * @property {number} [maxHistory] - Legacy alias for maxMessages
211
+ */
212
+ export class SessionManager extends EventEmitter {
213
+ /**
214
+ * @param {SessionManagerConfig} config
215
+ */
216
+ constructor({
217
+ // Server identity
218
+ port,
219
+ apiToken,
220
+
221
+ // Session defaults
222
+ maxSessions = 5,
223
+ defaultCwd,
224
+ defaultModel,
225
+ defaultPermissionMode,
226
+ // #4209: opt-in default for skipPermissions on the auto-created Default
227
+ // session and for any createSession() call that omits the field. Plumbed
228
+ // through from `chroxy start --dangerously-skip-permissions` so the
229
+ // TUI session boots already in unmediated mode without requiring the
230
+ // dashboard checkbox round-trip.
231
+ defaultSkipPermissions = false,
232
+ // #5985 (epic #5982): gate for the embedded user-shell terminal. When false
233
+ // (default — secure-by-default), createSession rejects a `user-shell`
234
+ // provider with UserShellDisabledError. Wired from `isUserShellEnabled(config)`
235
+ // in server-cli. Enforced HERE (not in the WS handler) so it covers every
236
+ // spawn path — WS create, restoreState, and any internal caller — per the
237
+ // #5985 swarm-audit C3 finding.
238
+ userShellEnabled = false,
239
+ // #6378: provider names that opt OUT of static model-allowlist validation
240
+ // at create time (config.providers.allowAnyModel) — an unlisted-but-API-
241
+ // valid model id passes through verbatim instead of throwing
242
+ // ProviderModelNotSupportedError, so a new model needs no release. A Set of
243
+ // strings; wired from `getAllowAnyModelProviders(config)` in server-cli.
244
+ // Default empty → OFF (strict validation, the secure default).
245
+ allowAnyModelProviders = new Set(),
246
+ // #6276 test seam: inject {isAlive, commOf, kill} for the boot-time
247
+ // orphan-shell reaper so the reap+audit path is exercisable without
248
+ // signalling a real process. Undefined in production → the reaper uses its
249
+ // own defaults (process.kill / ps).
250
+ userShellReapSeams = undefined,
251
+ // Shadowed in production (server-cli.js always passes providerType
252
+ // explicitly), but kept on the single source of truth so the fallback
253
+ // can't silently diverge from the server's default (#5819).
254
+ providerType = DEFAULT_PROVIDER,
255
+
256
+ // Session behavior
257
+ sessionTimeout,
258
+ maxToolInput,
259
+ transforms,
260
+ sandbox,
261
+ costBudget,
262
+ // #4075: per-session "you've spent $X" soft warning. Distinct from
263
+ // `costBudget` (which hard-blocks at the cap). Fires once per session
264
+ // per crossing; subscription-billed providers never trigger it
265
+ // because their cumulativeUsage.costUsd stays at 0.
266
+ // Default: 5.00 (USD). Set to 0 to DISABLE. Omitting the field, or
267
+ // passing null/undefined/NaN/Infinity/negative, falls back to the
268
+ // 5.00 default (see _normalizeCostThreshold).
269
+ costThresholdUsd,
270
+ // #5665: the `billing` config block (creditTier / monthlyCreditBudgetUsd /
271
+ // budgetWarningPercent) driving the monthly programmatic-credit meter.
272
+ billing,
273
+ maxSkillBytes,
274
+ maxTotalSkillBytes,
275
+ providerSkillAllowlist,
276
+ trustMismatchMode,
277
+ resultTimeoutMs,
278
+ // #3899: HARD-cap inactivity timeout (ms). Forwarded to providers via
279
+ // providerOpts. null = use BaseSession's DEFAULT_HARD_TIMEOUT_MS (2h).
280
+ hardTimeoutMs,
281
+ // #4467: stream-stall recovery timeout (ms). Forwarded via providerOpts.
282
+ // null = use BaseSession's DEFAULT_STREAM_STALL_TIMEOUT_MS (5min).
283
+ streamStallTimeoutMs,
284
+ // #5288: background-shell HARD-quiesce window (ms). Forwarded via
285
+ // providerOpts. null = use BaseSession's BACKGROUND_SHELL_HARD_QUIESCE_MS
286
+ // (4h); 0 disables hard-reaping (advisory-only, #5247 behaviour).
287
+ backgroundShellHardQuiesceMs,
288
+ // #4601: per-provider override map for streamStallTimeoutMs. Keys are
289
+ // provider ids (e.g. 'codex', 'gemini'); values are stall windows in
290
+ // ms (or 0 to disable for that provider). When a session is created
291
+ // for a provider listed here, that entry wins over the global
292
+ // `streamStallTimeoutMs`; otherwise the global value (or BaseSession
293
+ // default) applies. Each entry is validated with the same allowZero
294
+ // + MAX_SANE_DURATION_MS ceiling as `streamStallTimeoutMs` — bogus
295
+ // entries are dropped (with a warn) and the call falls through to
296
+ // the global value, so a single mis-typed entry can't silently
297
+ // produce a >24h timer.
298
+ providerStreamStallTimeoutMs,
299
+ // #4482: per-MCP-call timeout (ms). Forwarded via providerOpts to
300
+ // byok-session, which threads it into MCPFleet.callTool. null = use
301
+ // byok-mcp-client's DEFAULT_TOOL_CALL_TIMEOUT_MS (30s).
302
+ mcpToolCallTimeoutMs,
303
+ // #4456: wall-clock cap on MCPFleet.start() (ms). Forwarded via
304
+ // providerOpts to byok-session, which threads it into the MCPFleet
305
+ // constructor. null = use byok-mcp-fleet's DEFAULT_FLEET_START_CAP_MS
306
+ // (1500ms). Bounds the worst-case session-start latency on a broken
307
+ // MCP config — see byok-mcp-fleet.MCPFleet.start() for the trade-off.
308
+ mcpStartCapMs,
309
+
310
+ // State persistence
311
+ stateFilePath,
312
+ stateTtlMs,
313
+ persistDebounceMs = 2000,
314
+
315
+ // #5554: per-skill usage recorder. Records which skills activate in each
316
+ // session, powering the Control Room Skills tab's "previously used" surface.
317
+ // Tests pass their own (temp-pathed) recorder; production wires a default
318
+ // whose file sits next to the session-state file (so a temp stateFilePath
319
+ // keeps the usage log out of the real ~/.chroxy too).
320
+ skillsUsageRecorder,
321
+
322
+ // #5553: trust ledger for repo-local session presets
323
+ // (.chroxy/session.json). Tests pass their own temp-pathed store; production
324
+ // wires a default whose file sits next to the session-state file so a temp
325
+ // stateFilePath also redirects the ledger out of the real ~/.chroxy.
326
+ presetTrustStore,
327
+ // #5553: config path for the daemon-side preset override map. Tests point
328
+ // this at a temp config.json; production uses the default ~/.chroxy/config.json.
329
+ presetConfigPath,
330
+
331
+ // Message history
332
+ maxMessages,
333
+ maxHistory,
334
+
335
+ // #5859 (audit P1-7): opt-in boot-time sweep of orphaned chroxy session
336
+ // worktrees (dirs under the worktree base whose session id is no longer
337
+ // live). Off by default — server-cli enables it from config.worktreeGc.autoReap,
338
+ // mirroring the agent-worktree reaper's opt-in. Always clean-tree-guarded.
339
+ sweepOrphanWorktrees = false,
340
+
341
+ // Test-only: skip preflight checks (binary + credential). Production must
342
+ // leave this false so missing providers surface cleanly at createSession.
343
+ skipPreflight = false,
344
+ } = {}) {
345
+ super()
346
+
347
+ // Server identity
348
+ this._port = port || null
349
+ this._apiToken = apiToken || null
350
+ this._skipPreflight = skipPreflight
351
+
352
+ // Session defaults
353
+ this.maxSessions = maxSessions
354
+ this._defaultCwd = defaultCwd || process.cwd()
355
+ this._defaultModel = defaultModel || null
356
+ this._defaultPermissionMode = defaultPermissionMode || 'approve'
357
+ // #4209: coerced to a strict boolean so a non-boolean from config can't
358
+ // partially enable the flag. Forwarded to providerOpts.skipPermissions
359
+ // for every createSession() call that omits the field.
360
+ this._defaultSkipPermissions = !!defaultSkipPermissions
361
+ // #5985: strict `=== true` (not `!!`) so the fail-closed / no-coercion
362
+ // contract holds at the SessionManager layer too — a direct caller passing
363
+ // a truthy non-boolean (`'true'`, `1`) must NOT open the shell gate. Matches
364
+ // isUserShellEnabled()'s strictness; production passes that helper's boolean.
365
+ this._userShellEnabled = userShellEnabled === true
366
+ // #6378: normalize to a Set so `.has()` is always safe even if a caller
367
+ // passes undefined/null/array. Default = empty Set (strict validation).
368
+ this._allowAnyModelProviders = allowAnyModelProviders instanceof Set
369
+ ? allowAnyModelProviders
370
+ : new Set(Array.isArray(allowAnyModelProviders) ? allowAnyModelProviders : [])
371
+ this._userShellReapSeams = userShellReapSeams
372
+ this._sweepOrphanWorktrees = !!sweepOrphanWorktrees
373
+ this._providerType = providerType
374
+
375
+ // Session behavior
376
+ this._maxToolInput = maxToolInput || null
377
+ this._transforms = transforms || []
378
+ this._sandbox = sandbox || null
379
+ // #3749: per-server inactivity timeout (ms) forwarded to providers
380
+ // via providerOpts. null = use BaseSession's DEFAULT_RESULT_TIMEOUT_MS.
381
+ //
382
+ // #4509: the ceiling check inside `isOperatorTimeoutInRange` mirrors the
383
+ // wire-side guard #4503 added to `ws-history.js sendPostAuthInfo`. An
384
+ // operator typo (`CHROXY_RESULT_TIMEOUT_MS=99999999999`, extra digit)
385
+ // would otherwise pass `Number.isFinite > 0` here and silently produce a
386
+ // >24h internal inactivity timer; the helper instead falls back to null
387
+ // (→ BaseSession default) and warns once.
388
+ this._resultTimeoutMs =
389
+ isOperatorTimeoutInRange(resultTimeoutMs, { name: 'resultTimeoutMs', log })
390
+ ? resultTimeoutMs
391
+ : null
392
+ // #3899: same shape as resultTimeoutMs — null means "let BaseSession
393
+ // use DEFAULT_HARD_TIMEOUT_MS (2h)"; a positive finite value (≤ ceiling)
394
+ // flows through providerOpts to each session subclass.
395
+ this._hardTimeoutMs =
396
+ isOperatorTimeoutInRange(hardTimeoutMs, { name: 'hardTimeoutMs', log })
397
+ ? hardTimeoutMs
398
+ : null
399
+ // #4467: 0 explicitly disables stream-stall recovery; null = use default;
400
+ // positive finite value sets the recovery window. `allowZero: true` keeps
401
+ // the explicit-disable behaviour intact while #4509's ceiling gate clamps
402
+ // pathological over-24h values back to the default.
403
+ this._streamStallTimeoutMs =
404
+ isOperatorTimeoutInRange(streamStallTimeoutMs, { allowZero: true, name: 'streamStallTimeoutMs', log })
405
+ ? streamStallTimeoutMs
406
+ : null
407
+ // #5288: background-shell hard-quiesce window. `allowZero: true` keeps 0 as
408
+ // "disable hard-reaping"; null falls through to BaseSession's 4h default.
409
+ // Same ceiling guard as the timeouts (over-24h falls back + warns).
410
+ this._backgroundShellHardQuiesceMs =
411
+ isOperatorTimeoutInRange(backgroundShellHardQuiesceMs, { allowZero: true, name: 'backgroundShellHardQuiesceMs', log })
412
+ ? backgroundShellHardQuiesceMs
413
+ : null
414
+ // #4601: sanitise the per-provider override map at construction time —
415
+ // each entry runs through the same `isOperatorTimeoutInRange` guard as
416
+ // the global value (`allowZero: true` + 24h ceiling). Bad entries are
417
+ // dropped and the warn log identifies which provider's entry was
418
+ // ignored so an operator can correlate it back to their config.json
419
+ // key path. Storing the SANITISED map means createSession() doesn't
420
+ // have to re-validate on every session boot.
421
+ this._providerStreamStallTimeoutMs = this._sanitizeProviderTimeoutMap(
422
+ providerStreamStallTimeoutMs,
423
+ { name: 'providerStreamStallTimeoutMs', allowZero: true },
424
+ )
425
+ // #4482: per-MCP-call timeout. Unlike streamStallTimeoutMs, 0 is not a
426
+ // valid disable here — a 0-ms callTool timeout fires immediately. Only
427
+ // positive finite values are accepted; null falls through to byok-mcp-
428
+ // client's 30s default.
429
+ // #4517: ceiling check via `isOperatorTimeoutInRange` (same as the three
430
+ // sibling timeouts in #4509) — a typoed CHROXY_MCP_TOOL_CALL_TIMEOUT_MS
431
+ // (extra digit / accidental exponent) falls back to null and warns.
432
+ this._mcpToolCallTimeoutMs =
433
+ isOperatorTimeoutInRange(mcpToolCallTimeoutMs, { name: 'mcpToolCallTimeoutMs', log })
434
+ ? mcpToolCallTimeoutMs
435
+ : null
436
+ // #4456: same defensive shape as mcpToolCallTimeoutMs — only positive
437
+ // finite values are forwarded; bogus values fall back to the fleet's
438
+ // default cap. 0 is rejected (a 0 ms cap would fire before any
439
+ // handshake could complete).
440
+ this._mcpStartCapMs =
441
+ Number.isFinite(mcpStartCapMs) && mcpStartCapMs > 0
442
+ ? mcpStartCapMs
443
+ : null
444
+ this._costBudget = new CostBudgetManager({ budget: costBudget })
445
+ // #4075: per-session crossing threshold. Stored as a runtime-mutable
446
+ // field so the settings panel can update it without restarting the
447
+ // server. Operators set this via setCostThresholdUsd() to pin the
448
+ // soft warning point (default $5).
449
+ this._costThresholdUsd = this._normalizeCostThreshold(costThresholdUsd, 5.00)
450
+ // Skills size budgets (#3202). null = use loader defaults (32KB / 256KB).
451
+ // Setting either to 0 in config disables that cap.
452
+ this._maxSkillBytes = Number.isFinite(maxSkillBytes) ? maxSkillBytes : null
453
+ this._maxTotalSkillBytes = Number.isFinite(maxTotalSkillBytes) ? maxTotalSkillBytes : null
454
+ // Per-provider skill allowlist (#3207). Stored verbatim and forwarded
455
+ // to BaseSession via providerOpts; the loader applies the gate after
456
+ // the per-skill / per-budget filters so an out-of-allowlist skill is
457
+ // dropped before its body reaches the prompt. `null` (or any
458
+ // non-object) means "no allowlist configured" — keeps the legacy
459
+ // permissive behaviour.
460
+ this._providerSkillAllowlist = (
461
+ providerSkillAllowlist && typeof providerSkillAllowlist === 'object' && !Array.isArray(providerSkillAllowlist)
462
+ )
463
+ ? providerSkillAllowlist
464
+ : null
465
+ // Skill content-hash trust mode (#3204). One of 'warn' / 'block' /
466
+ // null. Null = trust check disabled (the loader skips hashing
467
+ // entirely; behaviour identical to the pre-#3204 server). Operators
468
+ // opt in via the `trustMismatchMode` config key. Tests that don't
469
+ // pass this option keep the legacy no-op behaviour, so the default
470
+ // trust file at ~/.chroxy/skills-trust.json is never touched
471
+ // unless explicitly enabled.
472
+ this._trustMismatchMode = (trustMismatchMode === 'warn' || trustMismatchMode === 'block')
473
+ ? trustMismatchMode
474
+ : null
475
+
476
+ // State persistence (delegated to SessionStatePersistence)
477
+ this._persistence = new SessionStatePersistence({
478
+ stateFilePath: stateFilePath || DEFAULT_STATE_FILE,
479
+ stateTtlMs,
480
+ persistDebounceMs,
481
+ })
482
+ // Backward-compatible accessors for tests that reference internal state
483
+ this._stateFilePath = this._persistence._stateFilePath
484
+ // #6276: orphan-shell reaper sidecar, colocated with the state file so a
485
+ // test's temp stateFilePath keeps it out of the real ~/.chroxy.
486
+ this._userShellSidecarPath = join(dirname(this._stateFilePath), 'user-shells.json')
487
+ this._stateTtlMs = this._persistence._stateTtlMs
488
+ this._persistDebounceMs = this._persistence._persistDebounceMs
489
+
490
+ // #5554: usage recorder. Use the caller-supplied one (tests pin a temp
491
+ // path), else default to a file alongside the session-state file so a temp
492
+ // stateFilePath also redirects the usage log away from the real home — the
493
+ // sandbox guard (#4633) then never fires from a SessionManager constructed
494
+ // with a temp stateFilePath.
495
+ this.skillsUsageRecorder = skillsUsageRecorder
496
+ || new SkillsUsageRecorder({ filePath: join(dirname(this._stateFilePath), 'skills-usage.json') })
497
+ // #5665: monthly programmatic-credit budget meter. Its running-total state
498
+ // file sits next to the session-state file (same temp-redirect reasoning as
499
+ // skillsUsageRecorder), so a test's temp stateFilePath keeps it out of the
500
+ // real ~/.chroxy and the sandbox guard never fires.
501
+ this._creditBudget = new MonthlyProgrammaticBudgetManager({
502
+ billingConfig: billing || {},
503
+ statePath: join(dirname(this._stateFilePath), 'monthly-budget-state.json'),
504
+ })
505
+ // #5553: per-repo session-preset trust ledger. Same temp-redirect logic as
506
+ // skillsUsageRecorder — the default file sits next to the session-state
507
+ // file so a test's temp stateFilePath keeps the ledger out of the real home.
508
+ this.presetTrustStore = presetTrustStore
509
+ || new SessionPresetTrustStore({ filePath: join(dirname(this._stateFilePath), 'session-preset-trust.json') })
510
+ // Config path the preset resolver reads the daemon override map from.
511
+ // Defaults to undefined → resolveSessionPreset uses its own DEFAULT_CONFIG_PATH.
512
+ this.presetConfigPath = typeof presetConfigPath === 'string' ? presetConfigPath : null
513
+ Object.defineProperty(this, '_persistTimer', {
514
+ get: () => this._persistence._persistTimer,
515
+ set: (v) => { this._persistence._persistTimer = v },
516
+ enumerable: false,
517
+ configurable: true,
518
+ })
519
+
520
+ // Message history (delegated to SessionMessageHistory)
521
+ this._history = new SessionMessageHistory({ maxMessages: maxMessages ?? maxHistory, maxToolInput })
522
+ // Backward-compatible accessors for tests that reference internal state
523
+ this._maxHistory = this._history.maxHistory
524
+ this._messageHistory = this._history._messageHistory
525
+ this._pendingStreams = this._history.pendingStreams
526
+ this._historyTruncated = this._history._historyTruncated
527
+
528
+ // Wire auto_label events from history to session_updated emissions
529
+ this._history.on('auto_label', ({ sessionId, label }) => {
530
+ this.emit('session_updated', { sessionId, name: label })
531
+ })
532
+
533
+ // Internal state
534
+ this._sessions = new Map() // sessionId -> { session, name, cwd, createdAt, agentCommId? }
535
+ this._agentCommIds = new Map() // agentCommId -> sessionId (mailbox live-interrupt routing)
536
+ this._mailboxEvents = [] // bounded ring buffer of recent mailbox deliveries (Control Room observability)
537
+ this._externalSessions = new ExternalSessionRegistry() // #5969 — live external (/api/events) sessions for mission control
538
+ this._sessionLastActivityAt = new Map() // sessionId -> last meaningful user/agent activity timestamp
539
+ this._sessionCounter = 0 // monotonically incrementing; used for auto-naming
540
+ this._locks = new SessionLockManager()
541
+
542
+ // Failed-restore tracking (#2954 — Guardian FM-01): sessions whose on-disk
543
+ // state could not be re-hydrated (e.g. missing API key env var). We keep
544
+ // the original saved payload in-memory so serializeState() can rewrite it
545
+ // back to disk unchanged — the user's history must not be dropped just
546
+ // because the provider happened to be misconfigured at boot.
547
+ this._failedRestores = new Map() // sessionId -> { saved, error }
548
+
549
+ // Set to true by destroyAll() so any subsequent persist call is a no-op
550
+ // — prevents a duplicate shutdown pass writing 0 sessions over the good
551
+ // state already on disk (#3697).
552
+ this._destroying = false
553
+
554
+ // Session idle timeout (delegated to SessionTimeoutManager)
555
+ const parsedTimeout = sessionTimeout ? parseDuration(sessionTimeout) : null
556
+ if (sessionTimeout != null && parsedTimeout == null) {
557
+ log.warn(`Invalid sessionTimeout value "${sessionTimeout}". Session timeouts are disabled.`)
558
+ }
559
+ this._sessionTimeoutMs = parsedTimeout
560
+ this._timeoutManager = new SessionTimeoutManager({ sessionTimeoutMs: parsedTimeout })
561
+
562
+ // Wire timeout manager events to SessionManager events
563
+ this._timeoutManager.on('warning', ({ sessionId, remainingMs }) => {
564
+ const entry = this._sessions.get(sessionId)
565
+ if (!entry) return
566
+ const friendly = formatIdleDuration(remainingMs)
567
+ log.info(`Session ${sessionId} idle warning (${friendly} remaining)`)
568
+ this.emit('session_warning', {
569
+ sessionId,
570
+ name: entry.name,
571
+ reason: 'idle_timeout',
572
+ message: `Session "${entry.name}" will be closed in ${friendly} due to inactivity`,
573
+ remainingMs,
574
+ })
575
+ })
576
+
577
+ this._timeoutManager.on('timeout', ({ sessionId, idleMs }) => {
578
+ const entry = this._sessions.get(sessionId)
579
+ if (!entry) return
580
+ const friendly = formatIdleDuration(idleMs)
581
+ log.info(`Session ${sessionId} timed out after ${friendly} idle`)
582
+ this.emit('session_timeout', { sessionId, name: entry.name, idleMs })
583
+ this.destroySession(sessionId)
584
+ })
585
+
586
+ // Wire isRunning check so timeout manager can skip busy sessions
587
+ this._timeoutManager.setIsRunningFn((sessionId) => {
588
+ const entry = this._sessions.get(sessionId)
589
+ return entry ? entry.session.isRunning : false
590
+ })
591
+
592
+ // Validate provider exists at construction time for fail-fast behavior
593
+ getProvider(this._providerType)
594
+ }
595
+
596
+ /**
597
+ * Remove a session from all session-scoped maps and sets (#1204).
598
+ * Called by destroySession(), sync catch, and async .catch() paths.
599
+ * @param {string} sessionId
600
+ */
601
+ _cleanupSessionMaps(sessionId) {
602
+ const entry = this._sessions.get(sessionId)
603
+ if (entry && entry.agentCommId) {
604
+ this._agentCommIds.delete(entry.agentCommId)
605
+ }
606
+ this._sessions.delete(sessionId)
607
+ this._sessionLastActivityAt.delete(sessionId)
608
+ this._timeoutManager.removeSession(sessionId)
609
+ this._history.cleanupSession(sessionId)
610
+ this._costBudget.removeSession(sessionId)
611
+ }
612
+
613
+ /**
614
+ * Register a mailbox identity (AGENT_COMM_ID) for a live session so the
615
+ * mailbox live-interrupt route (POST /api/mailbox) can resolve agent -> session.
616
+ * One id maps to one session: re-registering an id, or registering a new id
617
+ * for a session, replaces the prior mapping. Returns true when the session
618
+ * exists and was registered.
619
+ * @param {string} sessionId
620
+ * @param {string} agentCommId
621
+ */
622
+ registerAgentCommId(sessionId, agentCommId) {
623
+ if (typeof sessionId !== 'string' || typeof agentCommId !== 'string') return false
624
+ if (!sessionId) return false
625
+ // Authoritative id contract (single source of truth for both the
626
+ // POST /api/mailbox/register route and createSession's auto-register),
627
+ // matching the route's cleanField bounds: trim, reject empty, cap length,
628
+ // reject control chars. The trim canonicalises the stored key so an
629
+ // untrimmed/whitespace-only id can't create a confusing/unresolvable
630
+ // mapping. Control chars are rejected for id hygiene and parity with the
631
+ // route — the id is only a routing key and never itself reaches the PTY
632
+ // wakeup string (a fixed template + unread count; see mailbox-route.js).
633
+ const id = agentCommId.trim()
634
+ if (!id || id.length > 200 || /[\u0000-\u001f\u007f]/.test(id)) return false
635
+ const entry = this._sessions.get(sessionId)
636
+ if (!entry) return false
637
+ // Drop a prior holder of this id (id -> some other session).
638
+ const priorSessionId = this._agentCommIds.get(id)
639
+ if (priorSessionId && priorSessionId !== sessionId) {
640
+ const priorEntry = this._sessions.get(priorSessionId)
641
+ if (priorEntry && priorEntry.agentCommId === id) priorEntry.agentCommId = null
642
+ }
643
+ // Drop a prior id this session held (session -> some other id).
644
+ if (entry.agentCommId && entry.agentCommId !== id) {
645
+ this._agentCommIds.delete(entry.agentCommId)
646
+ }
647
+ entry.agentCommId = id
648
+ this._agentCommIds.set(id, sessionId)
649
+ return true
650
+ }
651
+
652
+ /**
653
+ * Remove a mailbox identity mapping. Returns true when something was removed.
654
+ * @param {string} agentCommId
655
+ */
656
+ unregisterAgentCommId(agentCommId) {
657
+ if (typeof agentCommId !== 'string' || !agentCommId) return false
658
+ const sessionId = this._agentCommIds.get(agentCommId)
659
+ if (!sessionId) return false
660
+ this._agentCommIds.delete(agentCommId)
661
+ const entry = this._sessions.get(sessionId)
662
+ if (entry && entry.agentCommId === agentCommId) entry.agentCommId = null
663
+ return true
664
+ }
665
+
666
+ /**
667
+ * Resolve the live session object registered for a mailbox id, or null.
668
+ * @param {string} agentCommId
669
+ */
670
+ resolveSessionByAgentCommId(agentCommId) {
671
+ if (typeof agentCommId !== 'string' || !agentCommId) return null
672
+ const sessionId = this._agentCommIds.get(agentCommId)
673
+ if (!sessionId) return null
674
+ const entry = this._sessions.get(sessionId)
675
+ return entry ? entry.session : null
676
+ }
677
+
678
+ /** Max recent mailbox delivery events retained for the Control Room snapshot. */
679
+ static MAILBOX_EVENT_LIMIT = 50
680
+
681
+ /**
682
+ * Record one mailbox live-interrupt delivery attempt for the Control Room
683
+ * "Mailbox" tab. Bounded ring buffer (oldest dropped past the limit). Pure
684
+ * observability — never throws into the delivery path, so the caller
685
+ * (handleMailboxPing) can fire-and-forget. Invalid input is ignored.
686
+ * @param {{ to: string, from?: string, unreadCount?: number|null, outcome: string }} ev
687
+ */
688
+ recordMailboxEvent(ev) {
689
+ if (!ev || typeof ev.to !== 'string' || typeof ev.outcome !== 'string') return
690
+ const unreadCount =
691
+ typeof ev.unreadCount === 'number' && Number.isInteger(ev.unreadCount) && ev.unreadCount >= 0
692
+ ? ev.unreadCount
693
+ : null
694
+ this._mailboxEvents.push({
695
+ at: Date.now(),
696
+ to: ev.to,
697
+ from: typeof ev.from === 'string' && ev.from ? ev.from : 'unknown',
698
+ unreadCount,
699
+ outcome: ev.outcome,
700
+ })
701
+ const overflow = this._mailboxEvents.length - SessionManager.MAILBOX_EVENT_LIMIT
702
+ if (overflow > 0) this._mailboxEvents.splice(0, overflow)
703
+ }
704
+
705
+ /** Recent mailbox delivery events, newest first (a copy — safe to serialize). */
706
+ getMailboxEvents() {
707
+ return [...this._mailboxEvents].reverse()
708
+ }
709
+
710
+ /**
711
+ * Fold one ingested external-session event (#5969) into the registry that
712
+ * backs the Control Room mission-control read-only section. Pure
713
+ * observability — never throws into the ingest path, so the caller
714
+ * (handleEventIngest) can fire-and-forget. Events without a sessionId are
715
+ * ignored by the registry.
716
+ * @param {string} type ingest event type (session_start, user_prompt_submit, stop, subagent_start, subagent_stop, session_end, …)
717
+ * @param {string} source the emitter source from the event envelope
718
+ * @param {string} sessionId the external session id
719
+ * @param {{ project?: string|null, cwd?: string|null, ts?: number }} [meta]
720
+ */
721
+ recordExternalSessionEvent(type, source, sessionId, meta) {
722
+ try {
723
+ this._externalSessions.record(type, source, sessionId, meta || {})
724
+ } catch { /* observability only — never disturb the ingest path */ }
725
+ }
726
+
727
+ /** Live external (/api/events) sessions for mission control, newest-activity first. */
728
+ getExternalSessions() {
729
+ return this._externalSessions.getSessions()
730
+ }
731
+
732
+ /**
733
+ * Snapshot of the live agentCommId -> session registrations for the Control
734
+ * Room "Mailbox" tab: which mailbox ids are addressable, the session each
735
+ * resolves to, and whether that session is busy / claude-tui (the conditions
736
+ * the live-interrupt route injects under). Skips ids whose session has gone.
737
+ * @returns {Array<{agentCommId: string, sessionId: string, sessionName: string|null, isBusy: boolean, isTui: boolean}>}
738
+ */
739
+ listAgentCommRegistrations() {
740
+ const out = []
741
+ for (const [agentCommId, sessionId] of this._agentCommIds) {
742
+ const entry = this._sessions.get(sessionId)
743
+ if (!entry) continue
744
+ const session = entry.session
745
+ out.push({
746
+ agentCommId,
747
+ sessionId,
748
+ sessionName: typeof entry.name === 'string' ? entry.name : null,
749
+ isBusy: !!(session && session.isRunning),
750
+ // #5984 (epic #5982): positive claude-tui discriminator, not
751
+ // `typeof writeTerminalInput` duck-typing (a user-shell session will
752
+ // also expose it). Strict `=== true` (matches the mailbox gate) so a
753
+ // buggy override returning a truthy non-boolean isn't treated as tui.
754
+ isTui: session?.constructor?.isClaudeTui === true,
755
+ })
756
+ }
757
+ return out
758
+ }
759
+
760
+ /**
761
+ * Resolve the validated "create plan" for a session (#6036 — the front-half
762
+ * SRP extraction out of {@link SessionManager#createSession}). Owns exactly
763
+ * the preflight + isolation + provider/preset resolution responsibilities:
764
+ *
765
+ * 1. session-limit guard + cwd existence check (throws on failure),
766
+ * 2. id generation (preserve-id validation #4983) + name,
767
+ * 3. provider resolution + the #2962 preflight (binary/credential) + the
768
+ * user-shell fail-closed gate (#5985) + the #3403 model soft-fallback,
769
+ * 4. worktree isolation (fresh `git worktree add` OR the #5310 restore
770
+ * rebind with the path-safety check),
771
+ * 5. per-repo session-preset resolution + preamble fold (#5553).
772
+ *
773
+ * Returns a plain plan object; {@link SessionManager#createSession} consumes
774
+ * it to build `providerOpts`, construct the session, register it, and start.
775
+ * Splitting the validation from the wiring keeps them close enough to read
776
+ * together — the "middle-layer trap" (#3224/#3231/#4790) recurs when they
777
+ * drift apart. Behaviour is identical to the previous inline front-half: the
778
+ * same checks run in the same order and throw the same errors.
779
+ *
780
+ * @param {object} args The (already-destructured) createSession options that
781
+ * the plan depends on.
782
+ * @returns {{
783
+ * sessionId: string,
784
+ * sessionName: string,
785
+ * resolvedCwd: string,
786
+ * resolvedModel: (string|null),
787
+ * resolvedPermissionMode: string,
788
+ * resolvedProvider: string,
789
+ * ProviderClass: Function,
790
+ * worktreePath: (string|null),
791
+ * worktreeRepoDir: (string|null),
792
+ * presetDescriptor: (object|null),
793
+ * effectiveSessionPreamble: (string|undefined),
794
+ * }} the validated create plan.
795
+ */
796
+ _resolveCreateSessionPlan({ name, cwd, model, permissionMode, provider, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sessionPreamble, preserveId, isRestore = false } = {}) {
797
+ if (this._sessions.size >= this.maxSessions) {
798
+ log.error(`Cannot create session: limit reached (${this._sessions.size}/${this.maxSessions})`)
799
+ throw new SessionLimitError(this.maxSessions)
800
+ }
801
+
802
+ const baseCwd = cwd || this._defaultCwd
803
+ // #6064/#3403: only an OMITTED model (`undefined`) falls back to the
804
+ // server-config default. An explicit `null` is the #3403 "use the provider's
805
+ // own default" marker and must SURVIVE. `null` is NOT a valid value on the WS
806
+ // wire (`create_session.model` is `z.string().optional()`, so a remote client
807
+ // sends a string or omits the field — never null); in practice it arrives via
808
+ // restoreState (the production path: a session that soft-fell-back to the
809
+ // provider default persists `model: null`) or an explicit internal/test
810
+ // caller passing it deliberately. Coalescing that `null` to `_defaultModel`
811
+ // would re-pin it to a server-config id that may itself be stale — exactly
812
+ // the staleness #3403 avoids — so the marker must be reproduced faithfully.
813
+ // (The prior `??` coalesced null too, contradicting this and the comment that
814
+ // claimed null survived; #6064.)
815
+ let resolvedModel = model === undefined ? this._defaultModel : model
816
+ const resolvedPermissionMode = permissionMode || this._defaultPermissionMode
817
+
818
+ // Validate cwd exists
819
+ try {
820
+ const stat = statSync(baseCwd)
821
+ if (!stat.isDirectory()) {
822
+ throw new SessionDirectoryError(`Not a directory: ${baseCwd}`, baseCwd)
823
+ }
824
+ } catch (err) {
825
+ if (err.code === 'ENOENT') {
826
+ throw new SessionDirectoryError(`Directory does not exist: ${baseCwd}`, baseCwd)
827
+ }
828
+ throw err
829
+ }
830
+
831
+ // #4983 — preserve persisted ID on restoreState so dashboard's
832
+ // localStorage-cached activeSessionId still resolves after a daemon
833
+ // restart. Validate the format strictly (32 lower-case hex chars,
834
+ // matching the randomBytes(16).toString('hex') output below) so a
835
+ // corrupted state file can't inject a malformed id; also guard
836
+ // against accidental collisions with sessions that already exist in
837
+ // this manager (defense in depth — restoreState runs at boot before
838
+ // any other createSession call, but the param is API-exposed and
839
+ // future callers shouldn't be able to clobber a live entry).
840
+ const preserve =
841
+ typeof preserveId === 'string' &&
842
+ /^[a-f0-9]{32}$/.test(preserveId) &&
843
+ !this._sessions.has(preserveId)
844
+ ? preserveId
845
+ : null
846
+ const sessionId = preserve ?? randomBytes(16).toString('hex')
847
+ const sessionName = name || `Session ${++this._sessionCounter}`
848
+
849
+ // Pre-flight: verify the provider's binary exists and required credential
850
+ // env vars are set BEFORE constructing/spawning. Without this, a missing
851
+ // binary surfaces as an opaque ENOENT after the session has already
852
+ // appeared in the UI. Runs BEFORE worktree creation so a failed preflight
853
+ // doesn't leave an orphan worktree behind. (#2962)
854
+ const resolvedProviderType = provider || this._providerType
855
+ const PreflightProviderClass = getProvider(resolvedProviderType)
856
+ // #5985 (epic #5982): fail-closed gate for the embedded user-shell terminal.
857
+ // Enforced here (before any spawn) so it covers EVERY create path — WS
858
+ // create_session, restoreState, and internal callers — not just the WS
859
+ // handler (swarm-audit C3: a handler-only gate is bypassed on restore). Keyed
860
+ // on the resolved provider CLASS (`isUserShell`), not the provider-name
861
+ // string, so any user-shell provider is caught regardless of its registry id
862
+ // — consistent with the serialize-skip and terminal_* gates.
863
+ if (PreflightProviderClass?.isUserShell === true && !this._userShellEnabled) {
864
+ throw new UserShellDisabledError()
865
+ }
866
+ if (!this._skipPreflight) {
867
+ runProviderPreflight(PreflightProviderClass)
868
+ }
869
+ // #6378: a provider opted into `config.providers.allowAnyModel` skips static
870
+ // allowlist validation entirely — the model id passes through verbatim and
871
+ // the upstream API validates it (mirrors ollama's null-allowlist behaviour),
872
+ // so a new model the provider's API already exposes needs no release.
873
+ const modelUnrestricted = this._allowAnyModelProviders.has(resolvedProviderType)
874
+ if (resolvedModel && !modelUnrestricted && typeof PreflightProviderClass.getAllowedModels === 'function') {
875
+ let providerAllowedModels = null
876
+ try {
877
+ const list = PreflightProviderClass.getAllowedModels()
878
+ providerAllowedModels = Array.isArray(list) ? list : null
879
+ } catch {
880
+ providerAllowedModels = null
881
+ }
882
+ if (providerAllowedModels && providerAllowedModels.length > 0 && !providerAllowedModels.includes(resolvedModel)) {
883
+ // Claude providers (claude-sdk, claude-cli, docker variants) share a
884
+ // dynamic model registry fed by the Agent SDK's `supportedModels()`.
885
+ // The dashboard caches `defaultModel` (e.g. `opus-4-6`) and ships it
886
+ // back on every `create_session` — when the model retires (e.g.
887
+ // opus-4-7 supersedes 4-6) the inherited id is no longer valid and
888
+ // a hard rejection breaks otherwise-valid session creation. Soft-
889
+ // fallback to the provider's own default (model:null, which both
890
+ // SdkSession and CliSession treat as "use the upstream default")
891
+ // and log a warning so operators can spot the drift in logs (#3403).
892
+ if (isClaudeProvider(resolvedProviderType, PreflightProviderClass)) {
893
+ log.warn(`Requested model '${resolvedModel}' is not in the current registry for provider '${resolvedProviderType}'; falling back to provider default. Supported: ${providerAllowedModels.slice(0, 8).join(', ')}${providerAllowedModels.length > 8 ? ', …' : ''}`)
894
+ resolvedModel = null
895
+ } else {
896
+ // Non-Claude providers (Codex, Gemini, custom) have small static
897
+ // allowlists — strict rejection still applies because falling
898
+ // back would otherwise mask a real misconfiguration (e.g. a
899
+ // Claude model id sent to a Gemini session).
900
+ throw new ProviderModelNotSupportedError({
901
+ provider: resolvedProviderType,
902
+ model: resolvedModel,
903
+ supported: providerAllowedModels,
904
+ })
905
+ }
906
+ }
907
+ }
908
+
909
+ // Worktree isolation — create a detached git worktree for this session
910
+ let resolvedCwd = baseCwd
911
+ let worktreePath = null
912
+ let worktreeRepoDir = null
913
+ if (restoreWorktreePath) {
914
+ // #5310 (WP-0.4) — restore path: REBIND to the worktree this session
915
+ // already owns instead of creating a new one. Worktree dirs under
916
+ // ~/.chroxy/worktrees/<id> survive a daemon restart, so recreating would
917
+ // fail ("already exists") and — worse — without rebinding, the restored
918
+ // entry carries worktreePath:null and never GCs the dir on destroy
919
+ // (orphan accrual) and reports isolation:'none'. The original repo dir
920
+ // can't be derived from the persisted cwd (which IS the worktree), so it
921
+ // is persisted + threaded through here for `git worktree remove`. If the
922
+ // worktree dir was deleted out from under us (e.g. `chroxy worktree gc`),
923
+ // the generic baseCwd existence check above already fails the restore
924
+ // cleanly and #2954 preserves it for retry.
925
+ //
926
+ // SECURITY (#5310 review): restoreWorktreePath is read from the on-disk
927
+ // state file and later becomes a recursive-deletion target in
928
+ // _removeWorktree (git worktree remove, then an rmSync -rf fallback). A
929
+ // corrupted or tampered state file could otherwise point it at an
930
+ // arbitrary directory and have destroySession() delete it. Worktree dirs
931
+ // are always created deterministically at join(base, sessionId), so a
932
+ // restored path that doesn't resolve to exactly that is rejected: we
933
+ // safe-degrade to a non-worktree session (worktreePath stays null ⇒ no
934
+ // deletion target) and log loudly, rather than rebind an unsafe path.
935
+ const expectedWorktreeDir = resolve(join(this._worktreeBase || DEFAULT_WORKTREE_BASE, sessionId))
936
+ if (resolve(restoreWorktreePath) === expectedWorktreeDir) {
937
+ worktreePath = restoreWorktreePath
938
+ worktreeRepoDir = restoreWorktreeRepoDir || null
939
+ resolvedCwd = restoreWorktreePath
940
+ } else {
941
+ log.warn(`Restored worktreePath "${restoreWorktreePath}" for session ${sessionId} does not match the expected per-session worktree dir "${expectedWorktreeDir}" — ignoring the rebind (treating as non-worktree) so a corrupted state file can't make destroySession() delete an arbitrary path`)
942
+ }
943
+ } else if (worktree) {
944
+ // Verify cwd is inside a git repository
945
+ try {
946
+ execFileSync(GIT, ['-C', baseCwd, 'rev-parse', '--git-dir'], {
947
+ stdio: ['pipe', 'pipe', 'pipe'],
948
+ encoding: 'utf-8',
949
+ })
950
+ } catch {
951
+ throw new WorktreeError(`Not a git repository: ${baseCwd}`)
952
+ }
953
+
954
+ // Create worktree directory
955
+ const worktreeBase = this._worktreeBase || DEFAULT_WORKTREE_BASE
956
+ const worktreeDir = join(worktreeBase, sessionId)
957
+ mkdirSync(worktreeBase, { recursive: true })
958
+
959
+ try {
960
+ execFileSync(GIT, ['-C', baseCwd, 'worktree', 'add', '--detach', worktreeDir, 'HEAD'], {
961
+ stdio: ['pipe', 'pipe', 'pipe'],
962
+ encoding: 'utf-8',
963
+ })
964
+ } catch (err) {
965
+ const msg = err?.stderr?.trim() || err?.message || String(err)
966
+ throw new WorktreeError(`Failed to create worktree: ${msg}`)
967
+ }
968
+
969
+ resolvedCwd = worktreeDir
970
+ worktreePath = worktreeDir
971
+ worktreeRepoDir = baseCwd
972
+ log.info(`Created worktree for session ${sessionId} at ${worktreeDir}`)
973
+ }
974
+
975
+ const resolvedProvider = resolvedProviderType
976
+ const ProviderClass = PreflightProviderClass
977
+
978
+ // #5553: resolve the per-repo session preset now that the cwd is known.
979
+ // The resolver walks up from resolvedCwd to the nearest `.chroxy/session.json`
980
+ // (worktrees inherit the parent repo's preset via the same walk), applies
981
+ // the daemon-override precedence, and consults the trust ledger. A repo-local
982
+ // preset is INERT until the operator approves its content hash; a daemon
983
+ // override is pre-trusted. Everything is wrapped so a preset resolution
984
+ // failure can never break session creation (fail closed = no preset).
985
+ //
986
+ // Skip on restore: a restored session already had its (folded) preamble
987
+ // persisted, and re-folding here would double-apply the repo preamble.
988
+ let presetDescriptor = null
989
+ let effectiveSessionPreamble = sessionPreamble
990
+ if (!isRestore) {
991
+ try {
992
+ const resolved = resolveSessionPreset(resolvedCwd, {
993
+ trustStore: this.presetTrustStore,
994
+ configPath: this.presetConfigPath || undefined,
995
+ })
996
+ if (resolved) {
997
+ // Fold the preamble only when the preset is ACTIVE (trusted + enabled).
998
+ // A pending/disabled preset is still surfaced to the client for
999
+ // disclosure + approval, but never injected.
1000
+ let folded = { value: '', capped: false }
1001
+ if (resolved.active && resolved.preamble) {
1002
+ folded = foldPreamble(resolved.preamble, sessionPreamble)
1003
+ effectiveSessionPreamble = folded.value
1004
+ }
1005
+ presetDescriptor = {
1006
+ source: resolved.source,
1007
+ active: resolved.active,
1008
+ trustState: resolved.trustState,
1009
+ enabled: resolved.enabled,
1010
+ // Only surface the seed when the preset is active — a pending preset
1011
+ // never stages text into the composer.
1012
+ seed: resolved.active ? resolved.seed : '',
1013
+ preambleLength: resolved.preambleLength,
1014
+ seedLength: resolved.seedLength,
1015
+ // `capped` reflects EITHER a read-time over-budget flag OR the fold
1016
+ // truncating the concatenated preamble — so the UI always discloses
1017
+ // a truncation.
1018
+ capped: resolved.capped || folded.capped,
1019
+ repoPath: resolved.repoPath,
1020
+ path: resolved.path,
1021
+ }
1022
+ }
1023
+ } catch (err) {
1024
+ // Leak guard: never echo preset contents in the failure path.
1025
+ log.warn(`Session preset resolution failed for session ${sessionId} (non-fatal): ${getErrorMessage(err, 'error')}`)
1026
+ presetDescriptor = null
1027
+ effectiveSessionPreamble = sessionPreamble
1028
+ }
1029
+ }
1030
+
1031
+ return {
1032
+ sessionId,
1033
+ sessionName,
1034
+ resolvedCwd,
1035
+ resolvedModel,
1036
+ resolvedPermissionMode,
1037
+ resolvedProvider,
1038
+ ProviderClass,
1039
+ worktreePath,
1040
+ worktreeRepoDir,
1041
+ presetDescriptor,
1042
+ effectiveSessionPreamble,
1043
+ }
1044
+ }
1045
+
1046
+ /**
1047
+ * Create a new session.
1048
+ * @param {object} [options]
1049
+ * @param {string} [options.name]
1050
+ * @param {string} [options.cwd]
1051
+ * @param {string} [options.model]
1052
+ * @param {string} [options.permissionMode]
1053
+ * @param {string} [options.resumeSessionId]
1054
+ * @param {string} [options.provider]
1055
+ * @param {boolean} [options.worktree] - When true, creates a git worktree for isolation
1056
+ * @param {object} [options.sandbox] - SDK sandbox settings for lightweight isolation
1057
+ * @param {boolean} [options.promptEvaluator] - Per-session toggle for the auto-evaluator
1058
+ * chain (#3185). Default false — the manual `evaluate_draft` flow remains unaffected.
1059
+ * @param {boolean} [options.chroxyContextHint] - Per-session opt-in toggle for
1060
+ * the Chroxy context-prefix in the system prompt (#3805). Default false —
1061
+ * when true, BaseSession._buildSystemPrompt prepends a short paragraph
1062
+ * telling the model it's running inside Chroxy so it can adjust output
1063
+ * for mobile clients. Persisted across reconnects.
1064
+ * @param {string} [options.sessionPreamble] - Per-session user-authored
1065
+ * preamble prepended to the system prompt every turn (#4660). Default
1066
+ * empty string — when set, BaseSession._buildSystemPrompt puts the
1067
+ * preamble at the FRONT (before the optional chroxy hint and the
1068
+ * skills text). Trimmed + capped to SESSION_PREAMBLE_MAX_LENGTH by
1069
+ * BaseSession. Persisted across reconnects.
1070
+ * @param {string} [options.promptEvaluatorSkipPattern] - Per-session regex source
1071
+ * string consulted by `shouldSkipEvaluator` BEFORE the server-wide
1072
+ * `config.promptEvaluatorSkipPattern` (the global knob landed in #3187;
1073
+ * this per-session override lands here in #3639). Pairs with the
1074
+ * per-session promptEvaluator toggle so different sessions can use
1075
+ * different skip heuristics (e.g. PR-review session skips 'lgtm',
1076
+ * triage session skips 'ack'). Default null — the global pattern from
1077
+ * #3187 still applies as the fallback.
1078
+ * @param {boolean} [options.stdinForwardingDisabled] - Internal: hydrate the SidecarProcess
1079
+ * stdin_disabled latch (#3540) on a session being restored from disk. Only used by
1080
+ * `restoreState()`. Truthy = the prior process latched the flag; the new SdkSession
1081
+ * reports it via `listSessions` and `serializeState` round-trips it on the next write.
1082
+ * @param {string} [options.bootedModel] - Internal/restore-only: pre-seed
1083
+ * `session.bootedModel` so the dashboard can show the actual model on a restored
1084
+ * session immediately, instead of falling back to the registry default until the
1085
+ * next CLI init event lands (#3700b). Empty / non-string ignored.
1086
+ * @param {number} [options.messageCounter] - Internal/restore-only: pre-seed
1087
+ * `session._messageCounter` so a restored session's next sendMessage generates
1088
+ * `msg-{N+1}` instead of restarting from `msg-1` and colliding with messages
1089
+ * the dashboard cached from the previous process (#3700). Non-finite or
1090
+ * negative values ignored.
1091
+ * @param {boolean} [options.skipPersist] - Internal: skip the sync persist flush. Used by
1092
+ * `restoreState()`, which must seed history and budget after createSession before the
1093
+ * state file is rewritten; otherwise each flush would overwrite the on-disk file with
1094
+ * empty history and destroy the very data we're restoring.
1095
+ * @param {boolean} [options.skipPermissions] - #4208 / #4209: spawn the claude TUI with
1096
+ * `--dangerously-skip-permissions` (and elide chroxy's permission hook + sidecar
1097
+ * entirely). Forwarded to ClaudeTuiSession; other providers ignore it harmlessly via
1098
+ * destructuring. When omitted, falls back to the SessionManager-wide
1099
+ * `defaultSkipPermissions` (set from `chroxy start --dangerously-skip-permissions`).
1100
+ * @param {string} [options.preserveId] - Optional 32-char lower-case hex session id to
1101
+ * reuse instead of generating a fresh `randomBytes(16).toString('hex')`. Invalid
1102
+ * format OR a collision with an already-live entry falls back to a fresh random id
1103
+ * so callers can safely pass any value. Primary use: `restoreState` reusing the
1104
+ * persisted id so dashboard's localStorage-cached `activeSessionId` still resolves
1105
+ * after a daemon restart (#4983).
1106
+ * @param {boolean} [options.isRestore] - Internal (#5316): marks a session created by
1107
+ * `restoreState()`. When a provider's start() rejects ASYNCHRONOUSLY, the rejection
1108
+ * handler preserves the restored history + worktree (registers a failed-restore)
1109
+ * instead of fully destroying the session. Fresh sessions omit it and take the
1110
+ * full-destroy path on start failure.
1111
+ * @returns {string} sessionId
1112
+ */
1113
+ createSession({ name, cwd, model, permissionMode, resumeSessionId, provider, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sandbox, containerId, containerUser, containerCliPath, promptEvaluator, promptEvaluatorSkipPattern, chroxyContextHint, sessionPreamble, stdinForwardingDisabled, bootedModel, messageCounter, skipPermissions, agentCommId, skipPersist = false, preserveId, isRestore = false } = {}) {
1114
+ // #6036 — front-half SRP extraction: preflight + isolation + provider/preset
1115
+ // resolution (incl. the limit guard, cwd check, id/name, #2962 preflight,
1116
+ // #5985 user-shell gate, #3403 model fallback, worktree create/restore, and
1117
+ // #5553 preset fold) all live in `_resolveCreateSessionPlan`. It throws the
1118
+ // same errors in the same order the inline code did; this method then
1119
+ // consumes the validated plan to build providerOpts, construct, register,
1120
+ // and start. Both halves stay in the same file so the BaseSession opt
1121
+ // forwarding stays readable next to the construction it feeds.
1122
+ const plan = this._resolveCreateSessionPlan({
1123
+ name,
1124
+ cwd,
1125
+ model,
1126
+ permissionMode,
1127
+ provider,
1128
+ worktree,
1129
+ restoreWorktreePath,
1130
+ restoreWorktreeRepoDir,
1131
+ sessionPreamble,
1132
+ preserveId,
1133
+ isRestore,
1134
+ })
1135
+ const {
1136
+ sessionId,
1137
+ sessionName,
1138
+ resolvedCwd,
1139
+ resolvedModel,
1140
+ resolvedPermissionMode,
1141
+ resolvedProvider,
1142
+ ProviderClass,
1143
+ worktreePath,
1144
+ worktreeRepoDir,
1145
+ presetDescriptor,
1146
+ effectiveSessionPreamble,
1147
+ } = plan
1148
+
1149
+ const providerOpts = {
1150
+ cwd: resolvedCwd,
1151
+ model: resolvedModel,
1152
+ permissionMode: resolvedPermissionMode,
1153
+ port: this._port,
1154
+ apiToken: this._apiToken,
1155
+ resumeSessionId: resumeSessionId || null,
1156
+ transforms: this._transforms,
1157
+ // Provider id flows into BaseSession so the skills loader can apply
1158
+ // the `providers:` filter (#3198) and pick a per-provider injection
1159
+ // default (#3200). Same string SessionManager uses to pick the
1160
+ // ProviderClass via getProvider() — the registry key.
1161
+ provider: resolvedProvider,
1162
+ }
1163
+ if (this._maxToolInput) providerOpts.maxToolInput = this._maxToolInput
1164
+ if (this._resultTimeoutMs != null) providerOpts.resultTimeoutMs = this._resultTimeoutMs
1165
+ if (this._hardTimeoutMs != null) providerOpts.hardTimeoutMs = this._hardTimeoutMs
1166
+ // #5288: forward the operator-configured hard-quiesce window (incl. 0 =
1167
+ // disable). null = unset → BaseSession applies its 4h default.
1168
+ if (this._backgroundShellHardQuiesceMs != null) providerOpts.backgroundShellHardQuiesceMs = this._backgroundShellHardQuiesceMs
1169
+ // #4601: per-provider streamStallTimeoutMs override resolution. Lookup
1170
+ // is by RESOLVED provider id (the same key SessionManager used to fetch
1171
+ // the ProviderClass from `getProvider()` above) so a session whose
1172
+ // explicit `provider` arg differs from the server default picks up the
1173
+ // override for its actual provider rather than the default. When the
1174
+ // map has an entry for `resolvedProvider` it wins over the global value;
1175
+ // `hasOwnProperty` keeps `0` (explicit per-provider disable) honoured.
1176
+ // When the entry is absent we fall back to the global
1177
+ // `_streamStallTimeoutMs` (or omit the key entirely so BaseSession's
1178
+ // 5min default applies).
1179
+ const perProviderStall = this._providerStreamStallTimeoutMs
1180
+ if (perProviderStall && Object.prototype.hasOwnProperty.call(perProviderStall, resolvedProvider)) {
1181
+ providerOpts.streamStallTimeoutMs = perProviderStall[resolvedProvider]
1182
+ } else if (this._streamStallTimeoutMs != null) {
1183
+ providerOpts.streamStallTimeoutMs = this._streamStallTimeoutMs
1184
+ }
1185
+ if (this._mcpToolCallTimeoutMs != null) providerOpts.mcpToolCallTimeoutMs = this._mcpToolCallTimeoutMs
1186
+ if (this._mcpStartCapMs != null) providerOpts.mcpStartCapMs = this._mcpStartCapMs
1187
+ // Skills size budgets — pass through if configured. BaseSession forwards
1188
+ // these to loadActiveSkillsLayered. (#3202)
1189
+ if (this._maxSkillBytes !== null) providerOpts.maxSkillBytes = this._maxSkillBytes
1190
+ if (this._maxTotalSkillBytes !== null) providerOpts.maxTotalSkillBytes = this._maxTotalSkillBytes
1191
+ // Per-provider skill allowlist — passed through verbatim. BaseSession
1192
+ // resolves the per-provider entry against the session's `provider`
1193
+ // key when constructing the loader options. (#3207)
1194
+ if (this._providerSkillAllowlist !== null) {
1195
+ providerOpts.providerSkillAllowlist = this._providerSkillAllowlist
1196
+ }
1197
+ // Skill content-hash trust mode (#3204). Only forwarded when the
1198
+ // operator explicitly configured one of 'warn' / 'block' — leaves
1199
+ // BaseSession's no-op default in place when omitted.
1200
+ if (this._trustMismatchMode !== null) {
1201
+ providerOpts.trustMismatchMode = this._trustMismatchMode
1202
+ }
1203
+ // #4664: per-session toggle/string settings (promptEvaluator,
1204
+ // chroxyContextHint, sessionPreamble) are forwarded through the
1205
+ // registry so adding a new knob is one entry in
1206
+ // PER_SESSION_SETTINGS rather than another `if (typeof x === ...)`
1207
+ // block here. Each registry entry's `acceptFromWire` predicate
1208
+ // mirrors the original per-knob shape — non-matching values are
1209
+ // dropped so BaseSession's constructor coerce applies the default.
1210
+ forwardPerSessionSettingsToProviderOpts(providerOpts, {
1211
+ promptEvaluator,
1212
+ chroxyContextHint,
1213
+ // #5553: the repo preamble is folded into the session-level preamble
1214
+ // (repo first, capped) above. Forward the FOLDED result so the repo
1215
+ // preamble lands in `sessionPreamble` and reaches every provider via
1216
+ // BASE_SESSION_OPT_KEYS.
1217
+ sessionPreamble: effectiveSessionPreamble,
1218
+ })
1219
+ // #3639: per-session promptEvaluatorSkipPattern. Kept out of the
1220
+ // per-session-settings registry because the wire shape ('non-empty
1221
+ // string OR null/empty to clear', with pre-validation regex compile)
1222
+ // doesn't fit the boolean/string factory. Only string sources are
1223
+ // forwarded; null, empty string, or non-string values use
1224
+ // BaseSession's `null` default. Validation (regex compile) happens
1225
+ // inside BaseSession so a hand-edited state file with a malformed
1226
+ // source falls back to null without crashing session creation.
1227
+ if (typeof promptEvaluatorSkipPattern === 'string' && promptEvaluatorSkipPattern.length > 0) {
1228
+ providerOpts.promptEvaluatorSkipPattern = promptEvaluatorSkipPattern
1229
+ }
1230
+ // #3540: hydrate the persisted stdin_disabled flag onto the new
1231
+ // session so restoreState() round-trips correctly. Only forwarded
1232
+ // when explicitly true — undefined/false uses the SdkSession
1233
+ // constructor default (`false`). Forwarded blindly to providerOpts
1234
+ // (non-Sdk providers ignore the unknown key via destructuring; the
1235
+ // signal only originates from SidecarProcess paths).
1236
+ if (stdinForwardingDisabled === true) {
1237
+ providerOpts.stdinForwardingDisabled = true
1238
+ }
1239
+ // #4208 / #4209: per-session skipPermissions, with the server-wide
1240
+ // default as fallback. Only forwarded when truthy so non-TUI providers
1241
+ // never see a `skipPermissions: false` key they have to destructure
1242
+ // around (kept consistent with the existing "forward only when set"
1243
+ // discipline above). Boolean coerce defensively in case a hand-edited
1244
+ // state file or future protocol drift sends a truthy non-boolean.
1245
+ const resolvedSkipPermissions = typeof skipPermissions === 'boolean'
1246
+ ? skipPermissions
1247
+ : this._defaultSkipPermissions
1248
+ if (resolvedSkipPermissions) providerOpts.skipPermissions = true
1249
+ // Sandbox: per-session overrides server-level default
1250
+ const resolvedSandbox = sandbox || this._sandbox
1251
+ if (resolvedSandbox) providerOpts.sandbox = resolvedSandbox
1252
+ // External container support (EnvironmentManager integration)
1253
+ if (containerId) providerOpts.containerId = containerId
1254
+ if (containerUser) providerOpts.containerUser = containerUser
1255
+ if (containerCliPath) providerOpts.containerCliPath = containerCliPath
1256
+ const session = new ProviderClass(providerOpts)
1257
+ // Pre-seed `bootedModel` from a restored snapshot so the dashboard can
1258
+ // surface the session's actual model immediately on reconnect, without
1259
+ // waiting for the next CLI init event to repopulate it (#3700b). Only
1260
+ // accept non-empty strings so older state files (no field) round-trip
1261
+ // as `null`.
1262
+ if (typeof bootedModel === 'string' && bootedModel.length > 0) {
1263
+ session.bootedModel = bootedModel
1264
+ }
1265
+ // Pre-seed `_messageCounter` so the next sendMessage on a restored
1266
+ // session generates `msg-{N+1}` instead of restarting from `msg-1`
1267
+ // and colliding with messages the dashboard cached from the
1268
+ // previous process (#3700). Only accept finite non-negative numbers.
1269
+ if (typeof messageCounter === 'number' && Number.isFinite(messageCounter) && messageCounter >= 0) {
1270
+ session._messageCounter = messageCounter
1271
+ }
1272
+
1273
+ // Derive isolation mode from actual session state, ignoring client-provided value
1274
+ // when it conflicts with reality (e.g. isolation:'container' with a non-container provider)
1275
+ let resolvedIsolation = 'none'
1276
+ if (worktreePath) resolvedIsolation = 'worktree'
1277
+ else if (ProviderClass.capabilities?.containerized) resolvedIsolation = 'container'
1278
+ else if (resolvedSandbox) resolvedIsolation = 'sandbox'
1279
+
1280
+ const entry = {
1281
+ session,
1282
+ name: sessionName,
1283
+ cwd: resolvedCwd,
1284
+ provider: resolvedProvider,
1285
+ createdAt: Date.now(),
1286
+ worktreePath,
1287
+ // Original repo dir needed for `git worktree remove` during cleanup.
1288
+ // #5310: set in both the create and restore-rebind branches above so it
1289
+ // survives a restart (was `worktreePath ? baseCwd : null`, which on
1290
+ // restore wrongly resolved to the worktree dir / null).
1291
+ worktreeRepoDir,
1292
+ isolation: resolvedIsolation,
1293
+ // #5316 (WP-2.2) — marks a session created by restoreState(). When a
1294
+ // provider's start() rejects ASYNCHRONOUSLY (claude-tui spawns its PTY in
1295
+ // an async start()), the .catch() below must preserve the restored history
1296
+ // + worktree binding instead of destroying them. Fresh sessions (false)
1297
+ // have nothing to preserve and take the full-destroy path.
1298
+ _isRestore: isRestore === true,
1299
+ // #4072: cumulative usage accumulator (tokens + cost) populated by
1300
+ // _trackUsage on every priced `result` event. Subscription-only
1301
+ // providers (e.g. claude-tui) emit `result` without `cost`, so the
1302
+ // accumulator stays at zero for them and the dashboard / app side
1303
+ // knows to skip the cost badge.
1304
+ cumulativeUsage: makeZeroCumulativeUsage(),
1305
+ // #5553: the resolved per-repo session-preset descriptor (or null). The
1306
+ // create_session handler reads this off the entry to (a) disclose the
1307
+ // preset metadata on the session_switched reply and (b) stage the seed
1308
+ // editable into the new session's composer. Not persisted — it is
1309
+ // re-resolved from disk on every fresh create, and restores skip folding.
1310
+ sessionPreset: presetDescriptor,
1311
+ }
1312
+
1313
+ this._sessions.set(sessionId, entry)
1314
+ // Mailbox (#5914 follow-up): auto-register the session's AGENT_COMM_ID so the
1315
+ // live-interrupt route resolves agent -> session WITHOUT a separate POST
1316
+ // /api/mailbox/register. registerAgentCommId is the authoritative validator
1317
+ // (drops control chars / over-length to a no-op) and must run AFTER the entry
1318
+ // is in _sessions. Cleared on removal by _cleanupSessionMaps.
1319
+ if (agentCommId) this.registerAgentCommId(sessionId, agentCommId)
1320
+ metrics.inc('sessions.created')
1321
+ this.touchActivity(sessionId)
1322
+ this._wireSessionEvents(sessionId, session)
1323
+
1324
+ try {
1325
+ const result = session.start()
1326
+ // Guard: if start() returns a thenable, catch async rejections (#1141).
1327
+ // claude-tui's start() spawns its PTY asynchronously and (as of #5316)
1328
+ // REJECTS when the PTY fails to come up, so this is the primary failure
1329
+ // signal for that provider.
1330
+ if (result && typeof result.catch === 'function') {
1331
+ result.catch((err) => this._handleAsyncStartFailure(sessionId, err))
1332
+ }
1333
+ } catch (err) {
1334
+ // Clean up phantom session on start() failure (Guardian FM-03)
1335
+ // Mirror destroySession() teardown order: detach listeners before destroy
1336
+ session.removeAllListeners()
1337
+ session.on('error', () => {})
1338
+ try {
1339
+ session.destroy()
1340
+ } catch (destroyErr) {
1341
+ log.error(`Failed to destroy session ${sessionId} during start() failure cleanup: ${destroyErr?.stack || destroyErr}`)
1342
+ }
1343
+ this._cleanupSessionMaps(sessionId)
1344
+ // Clean up the worktree ONLY if we freshly created it this call. #5310:
1345
+ // on a restore-rebind, worktreePath points at a PRE-EXISTING worktree
1346
+ // (with possibly uncommitted work) that we must NOT delete just because
1347
+ // the provider's start() failed — destroying it would lose the user's
1348
+ // work AND make the #2954-preserved retry unrecoverable (the next attempt
1349
+ // would hit the missing-worktree statSync failure). Only the fresh-create
1350
+ // branch should roll back its own creation. Use worktreeRepoDir (the
1351
+ // original repo) for the remove, consistent with the destroy paths.
1352
+ if (worktreePath && !restoreWorktreePath) {
1353
+ this._removeWorktree(worktreePath, worktreeRepoDir, sessionId)
1354
+ }
1355
+ throw err
1356
+ }
1357
+
1358
+ log.info(`Created session ${sessionId} "${sessionName}" (${this._sessions.size}/${this.maxSessions})`)
1359
+ this.emit('session_created', { sessionId, name: sessionName, cwd: resolvedCwd })
1360
+
1361
+ // #5554 Phase 2: record the skills that ACTIVATED for this fresh session.
1362
+ // The narrowest reliable point — `session._skills` is the active set the
1363
+ // loader actually injected into this session's prompt (provider-scoped,
1364
+ // manual-activation-resolved), and the sessionId + repo (resolvedCwd) are
1365
+ // now known. Skip restores (re-hydrating a session is not a new use) and
1366
+ // guard everything so a usage-log failure can never break session creation.
1367
+ if (!isRestore) {
1368
+ try {
1369
+ const activeSkills = Array.isArray(session?._skills)
1370
+ ? session._skills.map(s => (s && typeof s.name === 'string' ? s.name : null)).filter(Boolean)
1371
+ : []
1372
+ if (activeSkills.length > 0) {
1373
+ this.skillsUsageRecorder?.record({ sessionId, repo: resolvedCwd, skills: activeSkills })
1374
+ }
1375
+ } catch (err) {
1376
+ log.debug(`skills-usage: failed to record activation for ${sessionId} (non-fatal): ${getErrorMessage(err, err)}`)
1377
+ }
1378
+ }
1379
+ // Flush synchronously — a new session must survive an abrupt shutdown,
1380
+ // otherwise rebuilds / crashes during the 2s debounce window lose it.
1381
+ // Exception: restoreState calls us in a loop and seeds history/budget
1382
+ // AFTER this returns; flushing here would write empty history to disk
1383
+ // and permanently discard the data being restored.
1384
+ if (!skipPersist) this._flushPersistOrWarn(sessionId)
1385
+ return sessionId
1386
+ }
1387
+
1388
+ /**
1389
+ * Handle a provider start() that rejects ASYNCHRONOUSLY (#1141 guard path).
1390
+ * claude-tui spawns its PTY in an async start() that, as of #5316 (WP-2.2),
1391
+ * rejects when the PTY fails to come up.
1392
+ *
1393
+ * For a FRESH session there is no history worth keeping, so fully destroy it
1394
+ * (removes the worktree it created this call) — the pre-#5316 behaviour.
1395
+ *
1396
+ * For a RESTORED session, destroySession() would erase the restored history
1397
+ * AND remove the pre-existing worktree it rebound to (losing uncommitted work
1398
+ * and making the #2954 retry unrecoverable). So instead snapshot the entry
1399
+ * into a failed-restore payload — which serializeState() writes back to disk,
1400
+ * preserving history + worktree binding for a future retry — tear down only
1401
+ * the live (dead) provider, and surface session_restore_failed so the client
1402
+ * shows the "needs attention" / retry affordance.
1403
+ * @param {string} sessionId
1404
+ * @param {Error} err - The rejection from start()
1405
+ * @private
1406
+ */
1407
+ _handleAsyncStartFailure(sessionId, err) {
1408
+ const entry = this._sessions.get(sessionId)
1409
+ // Already gone — destroyed elsewhere (e.g. a concurrent destroySession or a
1410
+ // respawn_exhausted teardown) before this rejection landed. Nothing to do.
1411
+ if (!entry) return
1412
+ const message = err?.message || String(err)
1413
+ log.error(`Async start() rejected for session ${sessionId}: ${message}${err?.stack ? '\n' + err.stack : ''}`)
1414
+
1415
+ if (!entry._isRestore) {
1416
+ // #5731 T6: a fresh session whose async start() rejects (claude-tui's
1417
+ // PTY failing to spawn is the main case) would otherwise vanish with
1418
+ // only a `session_destroyed` — the client that just received
1419
+ // `session_created` + a success ack for createSession gets no reason for
1420
+ // the disappearance. Surface the failure FIRST so the client shows an
1421
+ // error toast, THEN tear down. There's no history worth preserving, so
1422
+ // this stays a full destroy (unlike the restore-rebind path below, which
1423
+ // round-trips history for a retry). Stamp a default code so the message
1424
+ // is consistent with the restore path's START_FAILED.
1425
+ if (err && !err.code) err.code = 'START_FAILED'
1426
+ this.emit('session_create_failed', {
1427
+ sessionId,
1428
+ name: entry.name,
1429
+ provider: entry.provider || this._providerType,
1430
+ cwd: entry.cwd,
1431
+ model: entry.session?.model || null,
1432
+ errorCode: err?.code || 'START_FAILED',
1433
+ errorMessage: message,
1434
+ })
1435
+ // Full teardown (removes the freshly-created worktree). The emit above
1436
+ // ran synchronously, so subscribers received the error while the session
1437
+ // was still mapped, before this broadcasts `session_destroyed`.
1438
+ this.destroySession(sessionId)
1439
+ return
1440
+ }
1441
+
1442
+ // Restore-rebind: preserve history + worktree, mark the session as a failed
1443
+ // restore so it round-trips to disk and surfaces in the needs-attention UI.
1444
+ const saved = this._serializeSessionEntry(sessionId, entry)
1445
+ // Detach + destroy ONLY the live provider (frees the dead PTY). This does
1446
+ // NOT remove the worktree — that's a SessionManager concern (_removeWorktree),
1447
+ // and we deliberately keep the rebound worktree intact for the retry.
1448
+ entry.session.removeAllListeners()
1449
+ entry.session.on('error', () => {}) // swallow stray error during destroy
1450
+ try {
1451
+ entry.session.destroy()
1452
+ } catch (destroyErr) {
1453
+ log.error(`Failed to destroy provider for failed restore ${sessionId}: ${destroyErr?.stack || destroyErr}`)
1454
+ }
1455
+ // Snapshot is captured above, so dropping the live history map is safe.
1456
+ this._cleanupSessionMaps(sessionId)
1457
+ // Stamp the code so the live `session_restore_failed` emit below and a
1458
+ // LATER reconnect via getFailedRestores() (which defaults a code-less error
1459
+ // to 'RESTORE_FAILED') report the SAME errorCode for this failure. claude-tui
1460
+ // rejects start() with a bare Error (no .code), so without this the same
1461
+ // failure would surface as START_FAILED to clients present at failure time
1462
+ // and RESTORE_FAILED to clients that reconnect afterwards.
1463
+ if (err && !err.code) err.code = 'START_FAILED'
1464
+ this._failedRestores.set(sessionId, { saved, error: err })
1465
+ this.emit('session_restore_failed', {
1466
+ sessionId,
1467
+ name: saved.name,
1468
+ provider: saved.provider || this._providerType,
1469
+ cwd: saved.cwd,
1470
+ model: saved.model || null,
1471
+ permissionMode: saved.permissionMode || null,
1472
+ errorCode: err?.code || 'START_FAILED',
1473
+ errorMessage: message,
1474
+ originalHistoryPreserved: true,
1475
+ historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
1476
+ })
1477
+ // Persist now so the preserved history survives an abrupt shutdown before
1478
+ // the next debounced write.
1479
+ this._flushPersist()
1480
+ }
1481
+
1482
+ /**
1483
+ * Remove a git worktree, logging errors non-fatally.
1484
+ * @param {string} worktreePath - Absolute path to the worktree directory
1485
+ * @param {string} repoDir - The original git repo directory (needed for git context)
1486
+ * @param {string} sessionId - Used for log messages only
1487
+ */
1488
+ _removeWorktree(worktreePath, repoDir, sessionId) {
1489
+ try {
1490
+ execFileSync(GIT, ['-C', repoDir, 'worktree', 'remove', '--force', worktreePath], {
1491
+ stdio: ['pipe', 'pipe', 'pipe'],
1492
+ encoding: 'utf-8',
1493
+ })
1494
+ log.info(`Removed worktree for session ${sessionId}: ${worktreePath}`)
1495
+ return
1496
+ } catch (err) {
1497
+ log.warn(`git worktree remove failed for session ${sessionId}, falling back to direct removal: ${err?.stderr?.trim() || err?.message || String(err)}`)
1498
+ }
1499
+ try {
1500
+ rmSync(worktreePath, { recursive: true, force: true })
1501
+ log.info(`Removed worktree directory for session ${sessionId}: ${worktreePath}`)
1502
+ } catch (err) {
1503
+ log.error(`Failed to remove worktree directory ${worktreePath}: ${err.message}`)
1504
+ }
1505
+ }
1506
+
1507
+ /**
1508
+ * Get a session entry by ID.
1509
+ * Returns null if the session does not exist or is currently being destroyed.
1510
+ * @returns {{ session: object, name: string, cwd: string, createdAt: number } | null}
1511
+ */
1512
+ getSession(sessionId) {
1513
+ const entry = this._sessions.get(sessionId)
1514
+ if (!entry || entry._destroying) return null
1515
+ return entry
1516
+ }
1517
+
1518
+ /**
1519
+ * #5553: read the resolved per-repo session preset for a session entry, in
1520
+ * the shape the create_session reply discloses to clients. Returns null when
1521
+ * the session has no preset (or is unknown). Never includes the preamble
1522
+ * TEXT (it's already folded into the prompt) — only its length + the seed
1523
+ * text (operator-facing, staged editable into the composer) + trust metadata.
1524
+ *
1525
+ * @param {string} sessionId
1526
+ * @returns {null | {
1527
+ * source: 'daemon' | 'repo',
1528
+ * active: boolean,
1529
+ * trustState: 'trusted' | 'pending',
1530
+ * enabled: boolean,
1531
+ * seed: string,
1532
+ * preambleLength: number,
1533
+ * seedLength: number,
1534
+ * capped: boolean,
1535
+ * repoPath: string | null,
1536
+ * }}
1537
+ */
1538
+ getSessionPreset(sessionId) {
1539
+ const entry = this._sessions.get(sessionId)
1540
+ if (!entry || !entry.sessionPreset) return null
1541
+ const p = entry.sessionPreset
1542
+ return {
1543
+ source: p.source,
1544
+ active: p.active,
1545
+ trustState: p.trustState,
1546
+ enabled: p.enabled,
1547
+ seed: p.seed || '',
1548
+ preambleLength: p.preambleLength,
1549
+ seedLength: p.seedLength,
1550
+ capped: !!p.capped,
1551
+ repoPath: p.repoPath || null,
1552
+ }
1553
+ }
1554
+
1555
+ /**
1556
+ * #5553: resolve the per-repo session preset for an arbitrary cwd WITHOUT
1557
+ * creating a session. Powers the create-session modal's pre-create
1558
+ * disclosure ("this repo's preset applies") and the per-repo settings drawer.
1559
+ * Surfaces full preset metadata INCLUDING the preamble + seed text so the
1560
+ * drawer can show a read-only preview. Trust-gated identically to
1561
+ * createSession. Returns null when there is no preset.
1562
+ *
1563
+ * @param {string} cwd
1564
+ * @returns {null | object}
1565
+ */
1566
+ resolveSessionPresetForCwd(cwd) {
1567
+ try {
1568
+ return resolveSessionPreset(cwd, {
1569
+ trustStore: this.presetTrustStore,
1570
+ configPath: this.presetConfigPath || undefined,
1571
+ })
1572
+ } catch (err) {
1573
+ log.warn(`resolveSessionPresetForCwd failed (non-fatal): ${getErrorMessage(err, 'error')}`)
1574
+ return null
1575
+ }
1576
+ }
1577
+
1578
+ /**
1579
+ * #5553: approve the CURRENT content hash of a repo-local preset so it
1580
+ * becomes trusted (and active for future sessions). Re-resolves the preset
1581
+ * from disk to obtain the live hash (so a stale client-supplied hash can't
1582
+ * pin a different version). Returns the updated descriptor or null when the
1583
+ * cwd has no trust-gated repo-local preset (e.g. a daemon override, which is
1584
+ * pre-trusted, or no preset at all).
1585
+ *
1586
+ * @param {string} cwd
1587
+ * @returns {null | object}
1588
+ */
1589
+ approveSessionPreset(cwd) {
1590
+ const resolved = this.resolveSessionPresetForCwd(cwd)
1591
+ if (!resolved || resolved.source !== 'repo' || !resolved.path) return null
1592
+ this.presetTrustStore.approve(resolved.path, resolved.hash)
1593
+ return this.resolveSessionPresetForCwd(cwd)
1594
+ }
1595
+
1596
+ /**
1597
+ * #5553: revoke trust for a repo-local preset so it goes inert (pending)
1598
+ * again. Returns the updated descriptor or null.
1599
+ *
1600
+ * @param {string} cwd
1601
+ * @returns {null | object}
1602
+ */
1603
+ revokeSessionPreset(cwd) {
1604
+ const resolved = this.resolveSessionPresetForCwd(cwd)
1605
+ if (!resolved || resolved.source !== 'repo' || !resolved.path) return null
1606
+ this.presetTrustStore.revoke(resolved.path)
1607
+ return this.resolveSessionPresetForCwd(cwd)
1608
+ }
1609
+
1610
+ /**
1611
+ * List all sessions with summary info.
1612
+ * @returns {Array<{ sessionId, name, cwd, model, permissionMode, isBusy, createdAt, lastActivityAt, stdinForwardingDisabled, stdinDroppedBytes, stdinDroppedCount }>}
1613
+ */
1614
+ listSessions() {
1615
+ const list = []
1616
+ for (const [sessionId, entry] of this._sessions) {
1617
+ if (entry._destroying) continue
1618
+ const ProviderClass = entry.session.constructor
1619
+ // #3573: hydrate cumulative stdin_dropped totals on reconnect.
1620
+ // SdkSession exposes the running counters via the `stdinDroppedTotals`
1621
+ // getter (added in #3544). Other providers (CliSession, Codex, Gemini)
1622
+ // do not drop stdin at the SidecarProcess pre-dial cap, so they
1623
+ // round-trip as `0` — matching the strict-boolean pattern used by
1624
+ // `stdinForwardingDisabled` so reconnecting clients see a stable
1625
+ // numeric shape regardless of provider.
1626
+ const totals = entry.session.stdinDroppedTotals
1627
+ const stdinDroppedBytes = totals && Number.isFinite(totals.bytes) ? totals.bytes : 0
1628
+ const stdinDroppedCount = totals && Number.isFinite(totals.count) ? totals.count : 0
1629
+ const resolvedProvider = entry.provider || this._providerType
1630
+ // #5630/#5629: per-session billing class for the dashboard cost labels.
1631
+ // Prefer the provider's live resolveAuth().billingClass (it already folds
1632
+ // in the era gate + the claude-sdk/claude-cli explicit-key refinement);
1633
+ // fall back to billingClassForProvider() for any provider whose
1634
+ // resolveAuth predates the field. Wrapped defensively so a misbehaving
1635
+ // custom provider's resolveAuth can't crash the snapshot.
1636
+ let billingClass
1637
+ try {
1638
+ billingClass = getProviderAuthInfo(resolvedProvider, ProviderClass)?.billingClass
1639
+ } catch {
1640
+ billingClass = undefined
1641
+ }
1642
+ if (!billingClass) {
1643
+ billingClass = billingClassForProvider(resolvedProvider, Date.now())
1644
+ }
1645
+ list.push({
1646
+ sessionId,
1647
+ name: entry.name,
1648
+ cwd: entry.cwd,
1649
+ // #3687: prefer the user's explicit override (`model`) so a later
1650
+ // `setModel()` isn't masked by a stale `bootedModel` (SdkSession's
1651
+ // setModel doesn't restart, so bootedModel only refreshes on the
1652
+ // next init). Fall back to bootedModel so the session list shows
1653
+ // what's actually running when no override was set. State
1654
+ // persistence (snapshotState below) keeps using `entry.session.model`
1655
+ // only — we want to remember the user's intent (null = "follow
1656
+ // CLI default") across restarts.
1657
+ model: entry.session.model || entry.session.bootedModel || null,
1658
+ permissionMode: entry.session.permissionMode || 'approve',
1659
+ isBusy: entry.session.isRunning,
1660
+ createdAt: entry.createdAt,
1661
+ lastActivityAt: this._sessionLastActivityAt.get(sessionId) || entry.createdAt,
1662
+ conversationId: entry.session.resumeSessionId || null,
1663
+ provider: resolvedProvider,
1664
+ // #5630/#5629: era-aware billing class so the dashboard labels the
1665
+ // cost row per class (api-key → "Cost (BYOK)", programmatic-credit →
1666
+ // "Credit spend", subscription → "Included (subscription)").
1667
+ billingClass,
1668
+ capabilities: ProviderClass.capabilities || {},
1669
+ worktree: entry.worktreePath != null,
1670
+ repoCwd: entry.worktreeRepoDir || null,
1671
+ isolation: entry.isolation || 'none',
1672
+ // #4664: per-session toggle/string settings (promptEvaluator,
1673
+ // chroxyContextHint, sessionPreamble) surface through the
1674
+ // registry so the dashboard can hydrate every knob's current
1675
+ // state without a separate round-trip. Each registry entry's
1676
+ // `coerce` doubles as the defensive cast guarding against a
1677
+ // custom provider that skipped BaseSession's field initialiser.
1678
+ ...serializePerSessionSettings(entry.session),
1679
+ // #3639: surface the per-session skip-pattern source so the
1680
+ // dashboard can show / edit the per-session override without
1681
+ // having to introspect via a separate request. `null` when
1682
+ // unset — the global config.promptEvaluatorSkipPattern still
1683
+ // applies as a fallback (see input-handlers.js). Treat empty
1684
+ // string as unset so the wire shape stays stable across the
1685
+ // setter/constructor (which normalise '' to null) and a
1686
+ // serialise -> restore round-trip. Kept out of the registry
1687
+ // because the empty-as-null shape doesn't fit the
1688
+ // boolean/string factory.
1689
+ promptEvaluatorSkipPattern:
1690
+ typeof entry.session.promptEvaluatorSkipPattern === 'string' &&
1691
+ entry.session.promptEvaluatorSkipPattern.length > 0
1692
+ ? entry.session.promptEvaluatorSkipPattern
1693
+ : null,
1694
+ // #3540: surface the latched stdin_disabled flag so reconnecting
1695
+ // clients (and clients connecting after a server restart) see
1696
+ // the disabled state without waiting for a fresh `error` event.
1697
+ // This is the canonical signal for cold restarts — the runtime
1698
+ // `error` event remains the live signal for newly-disabled
1699
+ // sessions in the same process. Strict-boolean coerce so
1700
+ // non-Sdk providers round-trip as `false`.
1701
+ stdinForwardingDisabled: !!entry.session._stdinForwardingDisabled,
1702
+ // #3573: hydrate cumulative stdin_dropped totals on reconnect so a
1703
+ // dashboard / mobile client that joins after one or more drops
1704
+ // already happened can paint the live "X bytes lost over N drops"
1705
+ // indicator without waiting for the next drop to fire. The runtime
1706
+ // `stdin_dropped_totals` event remains the live signal; this field
1707
+ // is the authoritative seed for clients connecting late.
1708
+ stdinDroppedBytes,
1709
+ stdinDroppedCount,
1710
+ // #4072: hydrate cumulative token usage + cost so a dashboard /
1711
+ // mobile client connecting after a session has already racked up
1712
+ // turns sees the running totals immediately instead of waiting
1713
+ // for the next `session_usage` event. Overlay the entry's stored
1714
+ // values on top of the zero template so the snapshot ALWAYS has
1715
+ // every key — a custom provider or future restoreState path that
1716
+ // stores a partial object can't produce a wire shape with
1717
+ // missing fields (#4088 review). Shallow-copy on the wire so a
1718
+ // client that mutates the payload can't corrupt the canonical
1719
+ // accumulator. Subscription-only sessions never emit `cost` so
1720
+ // this stays zero — the UI uses `turnsBilled === 0` or
1721
+ // `costUsd === 0` to suppress the cost badge.
1722
+ cumulativeUsage: { ...makeZeroCumulativeUsage(), ...(entry.cumulativeUsage || {}) },
1723
+ // #4307: hydrate pending background-shell entries so a client
1724
+ // joining mid-flight (fresh tab, server reconnect, app
1725
+ // resume) sees the waiting-on-shell state without needing to
1726
+ // wait for the next `background_work_changed` event. Always
1727
+ // an array — sessions with no pending work serialize as `[]`
1728
+ // (no defensive `undefined` on the wire, mirrors how
1729
+ // `cumulativeUsage` always carries a zero block). Empty array
1730
+ // is the common path; the dashboard's renderer treats it as
1731
+ // "no waiting indicator." Defensive guard: providers that
1732
+ // skip BaseSession's field initialiser (older custom
1733
+ // providers, hypothetical) round-trip an empty array rather
1734
+ // than crashing `getPendingBackgroundShells()` on undefined.
1735
+ pendingBackgroundShells:
1736
+ typeof entry.session.getPendingBackgroundShells === 'function'
1737
+ ? entry.session.getPendingBackgroundShells()
1738
+ : [],
1739
+ })
1740
+ }
1741
+ return list
1742
+ }
1743
+
1744
+ /**
1745
+ * Read git/project context for a session's working directory.
1746
+ * @param {string} [sessionId] - If omitted, uses first session
1747
+ * @returns {Promise<{ sessionId: string, gitBranch: string|null, gitDirty: number, gitAhead: number, projectName: string|null } | null>}
1748
+ */
1749
+ async getSessionContext(sessionId) {
1750
+ const entry = sessionId
1751
+ ? this._sessions.get(sessionId)
1752
+ : this._sessions.values().next().value
1753
+ if (!entry) return null
1754
+ const id = sessionId || this._sessions.keys().next().value
1755
+ const ctx = await readSessionContext(entry.cwd)
1756
+ return { sessionId: id, ...ctx }
1757
+ }
1758
+
1759
+ /**
1760
+ * Check if a session is currently locked for mutation.
1761
+ * @param {string} sessionId
1762
+ * @returns {boolean}
1763
+ */
1764
+ isSessionLocked(sessionId) {
1765
+ return this._locks.isLocked(sessionId)
1766
+ }
1767
+
1768
+ /**
1769
+ * Acquire a mutation lock for a session. Returns a release function.
1770
+ * @param {string} sessionId
1771
+ * @returns {Promise<() => void>}
1772
+ */
1773
+ acquireSessionLock(sessionId) {
1774
+ return this._locks.acquire(sessionId)
1775
+ }
1776
+
1777
+ /**
1778
+ * Rename a session with mutation lock.
1779
+ * @returns {Promise<boolean>}
1780
+ */
1781
+ async renameSessionLocked(sessionId, name) {
1782
+ const release = await this._locks.acquire(sessionId)
1783
+ try {
1784
+ return this.renameSession(sessionId, name)
1785
+ } finally {
1786
+ release()
1787
+ }
1788
+ }
1789
+
1790
+ /**
1791
+ * Destroy a session with mutation lock.
1792
+ * Sets _destroying immediately (before lock acquisition) so concurrent
1793
+ * getSession() calls see the session as unavailable right away.
1794
+ * @returns {Promise<boolean>}
1795
+ */
1796
+ async destroySessionLocked(sessionId) {
1797
+ const entry = this._sessions.get(sessionId)
1798
+ if (entry) entry._destroying = true
1799
+ const release = await this._locks.acquire(sessionId)
1800
+ try {
1801
+ return this.destroySession(sessionId)
1802
+ } finally {
1803
+ release()
1804
+ }
1805
+ }
1806
+
1807
+ /**
1808
+ * Rename a session.
1809
+ * @returns {boolean}
1810
+ */
1811
+ renameSession(sessionId, name) {
1812
+ const entry = this._sessions.get(sessionId)
1813
+ if (!entry) {
1814
+ log.error(`Cannot rename: session ${sessionId} not found`)
1815
+ return false
1816
+ }
1817
+ entry.name = name
1818
+ entry._autoLabeled = true // prevent auto-label from overwriting manual rename
1819
+ log.info(`Renamed session ${sessionId} to "${name}"`)
1820
+ this.emit('session_updated', { sessionId, name })
1821
+ // Flush synchronously — before this, renames were never persisted at all,
1822
+ // so a restart would show the pre-rename label.
1823
+ this._flushPersistOrWarn(sessionId, name)
1824
+ return true
1825
+ }
1826
+
1827
+ /**
1828
+ * Destroy a specific session.
1829
+ * Sets _destroying = true at the start so concurrent getSession() calls
1830
+ * treat the session as unavailable while cleanup is in progress.
1831
+ * @returns {boolean}
1832
+ */
1833
+ destroySession(sessionId) {
1834
+ const entry = this._sessions.get(sessionId)
1835
+ if (!entry) {
1836
+ log.error(`Cannot destroy: session ${sessionId} not found`)
1837
+ return false
1838
+ }
1839
+ // Mark as destroying immediately — getSession() will return null from here on
1840
+ entry._destroying = true
1841
+ metrics.inc('sessions.destroyed')
1842
+ // Detach listeners BEFORE destroy to prevent orphaned events (FM-04)
1843
+ entry.session.removeAllListeners()
1844
+ // Prevent unhandled 'error' throw if session emits error during destroy
1845
+ entry.session.on('error', () => {})
1846
+ // Emit synthetic stream_end for any in-flight streams so clients see termination
1847
+ const closedMessageIds = this._history.closePendingStreams(sessionId)
1848
+ for (const messageId of closedMessageIds) {
1849
+ this.emit('session_event', { sessionId, event: 'stream_end', data: { messageId } })
1850
+ }
1851
+ try {
1852
+ entry.session.destroy()
1853
+ } catch (destroyErr) {
1854
+ log.error(`Error destroying session ${sessionId} "${entry.name}": ${destroyErr?.stack || destroyErr}`)
1855
+ }
1856
+ this._cleanupSessionMaps(sessionId)
1857
+ if (entry.worktreePath) {
1858
+ this._removeWorktree(entry.worktreePath, entry.worktreeRepoDir, sessionId)
1859
+ }
1860
+ log.info(`Destroyed session ${sessionId} "${entry.name}" (${this._sessions.size}/${this.maxSessions})`)
1861
+ // #5985 audit — close the user-shell trail opened at create. Exit code is
1862
+ // the shell's natural code if it ended before this teardown, else null (the
1863
+ // destroy() above SIGTERMs a live shell asynchronously). Read off the
1864
+ // session, set in UserShellSession._onShellExit.
1865
+ if (entry.session?.constructor?.isUserShell === true) {
1866
+ auditShellDestroy({
1867
+ sessionId,
1868
+ exitCode: entry.session._exitCode ?? null,
1869
+ reason: entry.session._exitReason ?? 'destroyed',
1870
+ })
1871
+ // #6276: a clean teardown SIGTERMs the shell, so drop its orphan-reaper
1872
+ // record — otherwise the next boot would try to reap an already-dead pid.
1873
+ forgetShell(this._userShellSidecarPath, sessionId)
1874
+ }
1875
+ this.emit('session_destroyed', { sessionId })
1876
+ // Flush synchronously so the deletion survives an abrupt shutdown. The
1877
+ // entry is already out of `_sessions` by now, so pass its name explicitly.
1878
+ this._flushPersistOrWarn(sessionId, entry.name)
1879
+ return true
1880
+ }
1881
+
1882
+ /**
1883
+ * Sever every live user-shell session — the #6006 token-revoke primitive.
1884
+ *
1885
+ * Iterates a SNAPSHOT of the session map (destroySession() mutates it) and
1886
+ * destroys each session whose provider CLASS is a user-shell, leaving every
1887
+ * other session untouched. Called by WsServer's `token_rotated` handler when
1888
+ * an operator REVOKES the token (the panic button), never on a scheduled
1889
+ * rotation — a periodic re-key must not kill long-running shells.
1890
+ *
1891
+ * The destroy trail is closed by destroySession()'s #5985 audit; `reason` is
1892
+ * stamped onto each still-live shell first so the trail records WHY it died
1893
+ * (e.g. 'revoked') without clobbering a shell that already exited naturally.
1894
+ *
1895
+ * @param {string} [reason='revoked'] - audit reason recorded on each shell
1896
+ * @returns {number} count of shells severed
1897
+ */
1898
+ destroyAllUserShellSessions(reason = 'revoked') {
1899
+ let severed = 0
1900
+ // Snapshot: destroySession() deletes from _sessions mid-iteration.
1901
+ for (const [sessionId, entry] of [...this._sessions]) {
1902
+ if (entry.session?.constructor?.isUserShell !== true) continue
1903
+ // Record the reason only for a still-live shell — preserve a natural
1904
+ // exit reason already set by UserShellSession._onShellExit.
1905
+ if (entry.session._exitReason == null) {
1906
+ entry.session._exitReason = reason
1907
+ }
1908
+ if (this.destroySession(sessionId)) severed++
1909
+ }
1910
+ if (severed > 0) {
1911
+ log.warn(`Severed ${severed} user-shell session(s): ${reason}`)
1912
+ }
1913
+ return severed
1914
+ }
1915
+
1916
+ /**
1917
+ * Destroy all sessions (shutdown cleanup).
1918
+ *
1919
+ * Sets `_destroying` so any persist call after this point — whether from a
1920
+ * duplicate shutdown handler invocation or from a stray late-arriving event
1921
+ * — is a no-op. Without that guard, a second shutdown pass ran
1922
+ * `serializeState()` against the already-cleared `_sessions` Map and wrote
1923
+ * 0 sessions to disk, erasing the user's restored state across upgrade/quit
1924
+ * cycles (#3697).
1925
+ */
1926
+ destroyAll() {
1927
+ this.stopSessionTimeouts()
1928
+ this._persistence.cancelPersist()
1929
+ try {
1930
+ this.serializeState()
1931
+ } catch (err) {
1932
+ // #5701: this is the final write before the process exits — a failure
1933
+ // here loses the whole session list on the next start. Log loudly so the
1934
+ // operator can act (disk space / permissions) rather than discovering it
1935
+ // silently gone after restart.
1936
+ log.error(`CRITICAL: failed to serialize session state during shutdown — sessions may NOT be restored on next start (check disk space and write permissions for ${this._stateFilePath}): ${err?.stack || err}`)
1937
+ }
1938
+ // Set the destroying flag AFTER the final write — every persist call from
1939
+ // here on (duplicate shutdown handler, late-arriving session event) will
1940
+ // be a no-op so the good state on disk survives (#3697).
1941
+ this._destroying = true
1942
+ for (const [sessionId, entry] of this._sessions) {
1943
+ entry.session.removeAllListeners()
1944
+ entry.session.on('error', () => {})
1945
+ try {
1946
+ entry.session.destroy()
1947
+ } catch (destroyErr) {
1948
+ log.error(`Error destroying session ${sessionId} "${entry.name}" during destroyAll(): ${destroyErr?.stack || destroyErr}`)
1949
+ }
1950
+ // Do NOT remove the worktree here. destroyAll() is a process-shutdown
1951
+ // teardown, not a user-initiated session destroy: the session was just
1952
+ // serialized as live above, and on the next start restoreState() rebinds
1953
+ // it to this exact worktree dir (#5310). Deleting it now orphaned the
1954
+ // restore — the worktree session came back pointing at a directory that
1955
+ // no longer existed, losing any uncommitted work in it. Worktree removal
1956
+ // belongs only in destroySessionLocked() (the explicit per-session
1957
+ // destroy). Orphan worktrees from sessions that DON'T come back are
1958
+ // swept at boot — see worktree-gc (P1-7 follow-up).
1959
+ // #5985 audit — user-shells are non-persisted, so a live shell at
1960
+ // shutdown is torn down here (not via destroySession); close its trail.
1961
+ if (entry.session?.constructor?.isUserShell === true) {
1962
+ auditShellDestroy({
1963
+ sessionId,
1964
+ exitCode: entry.session._exitCode ?? null,
1965
+ reason: entry.session._exitReason ?? 'shutdown',
1966
+ })
1967
+ }
1968
+ this.emit('session_destroyed', { sessionId })
1969
+ }
1970
+ this._sessions.clear()
1971
+ this._timeoutManager.destroy()
1972
+ this._history.clear()
1973
+ this._costBudget.clear()
1974
+ // #5554: persist any pending usage records on shutdown (best-effort).
1975
+ try { this.skillsUsageRecorder?.flush() } catch { /* non-fatal */ }
1976
+ }
1977
+
1978
+ /**
1979
+ * Get the first session ID (used as default).
1980
+ * @returns {string | null}
1981
+ */
1982
+ get firstSessionId() {
1983
+ for (const [id, entry] of this._sessions) {
1984
+ if (!entry._destroying) return id
1985
+ }
1986
+ return null
1987
+ }
1988
+
1989
+ get defaultCwd() {
1990
+ return this._defaultCwd
1991
+ }
1992
+
1993
+ /**
1994
+ * Current max messages per session (from SessionMessageHistory).
1995
+ * @returns {number}
1996
+ */
1997
+ get maxMessages() {
1998
+ return this._history.maxMessages
1999
+ }
2000
+
2001
+ /**
2002
+ * Serialize session state to disk for graceful restart.
2003
+ * Called during drain before the process exits.
2004
+ * @returns {object|null} The serialized state, or `null` if `destroyAll()`
2005
+ * has already run — late callers (duplicate shutdown handler, stray
2006
+ * session event) cannot overwrite the on-disk state (#3697).
2007
+ */
2008
+ serializeState() {
2009
+ // After destroyAll() has cleared the in-memory Map, any further write
2010
+ // would persist 0 sessions and overwrite the good state already on disk.
2011
+ // Skip silently — the destroyAll() call did the final write itself
2012
+ // (#3697).
2013
+ if (this._destroying) return null
2014
+ const state = { version: 1, timestamp: Date.now(), sessions: [] }
2015
+ for (const [id, entry] of this._sessions) {
2016
+ // #5983 (epic #5982): never persist a user-shell session. Restoring one
2017
+ // would re-spawn a $SHELL on boot — bypassing the userShell.enabled gate
2018
+ // if it was since turned off (swarm-audit C3 / Skeptic finding 4) — and a
2019
+ // shell has no resumable conversation state worth keeping anyway.
2020
+ if (entry.session?.constructor?.isUserShell === true) continue
2021
+ state.sessions.push(this._serializeSessionEntry(id, entry))
2022
+ }
2023
+
2024
+ // Preserve sessions that failed to restore (#2954 — Guardian FM-01).
2025
+ // Without this, the next successful write drops them from disk and the
2026
+ // user's history is permanently lost. We write them back exactly as
2027
+ // they were loaded so a retry (after the user sets the missing env var
2028
+ // and restarts) can fully re-hydrate history.
2029
+ for (const [, { saved }] of this._failedRestores) {
2030
+ state.sessions.push(saved)
2031
+ }
2032
+
2033
+ // Persist cost tracking so budget survives restarts
2034
+ const budgetState = this._costBudget.serialize()
2035
+ state.costs = budgetState.costs
2036
+ state.budgetWarned = budgetState.budgetWarned
2037
+ state.budgetExceeded = budgetState.budgetExceeded
2038
+ state.budgetPaused = budgetState.budgetPaused
2039
+
2040
+ return this._persistence.serializeState(state)
2041
+ }
2042
+
2043
+ /**
2044
+ * Serialize a single live session entry to the on-disk persisted shape.
2045
+ * Extracted from serializeState() so the async start-failure path (#5316,
2046
+ * WP-2.2) can snapshot a restored session into a failed-restore payload that
2047
+ * round-trips through restoreState() identically. Keep this in lockstep with
2048
+ * the restore-side reader in restoreState().
2049
+ * @param {string} id - The session id
2050
+ * @param {object} entry - The in-memory session entry
2051
+ * @returns {object} The persisted session payload
2052
+ * @private
2053
+ */
2054
+ _serializeSessionEntry(id, entry) {
2055
+ const history = this._history.getHistory(id).map(e => this._history.truncateEntry(e))
2056
+ return {
2057
+ id,
2058
+ sdkSessionId: (typeof entry.session.resumeSessionId !== 'undefined' ? entry.session.resumeSessionId : null),
2059
+ conversationId: entry.session.resumeSessionId || null,
2060
+ cwd: entry.cwd,
2061
+ model: entry.session.model,
2062
+ // Persist the model the underlying CLI actually booted with (#3700b).
2063
+ // `model` reflects an explicit user override; `bootedModel` is what
2064
+ // the provider chose when no override was set. Surfacing this on
2065
+ // restore lets the dashboard show the real model in the dropdown
2066
+ // immediately, instead of falling back to the registry default
2067
+ // until the next init event lands.
2068
+ bootedModel: entry.session.bootedModel || null,
2069
+ // Persist the per-session messageId counter so a server restart
2070
+ // doesn't restart from `msg-1` and collide with messages the
2071
+ // dashboard already has cached in localStorage from the previous
2072
+ // process — the dashboard's stream-id collision logic would
2073
+ // silently REUSE the old `msg-1` response message and append
2074
+ // the new turn's text to it, leaving the bottom of the chat
2075
+ // empty (#3700). Falsy/missing on older state files round-trips
2076
+ // as 0 which is the original constructor default.
2077
+ messageCounter: entry.session._messageCounter || 0,
2078
+ permissionMode: entry.session.permissionMode,
2079
+ provider: entry.provider || null,
2080
+ name: entry.name,
2081
+ // #5310 (WP-0.4) — persist the worktree binding so a restored session
2082
+ // rebinds to its existing worktree (rather than losing it). worktreePath
2083
+ // is also the session's cwd, but worktreeRepoDir (the ORIGINAL repo,
2084
+ // needed for `git worktree remove`) is NOT derivable from cwd, so both
2085
+ // must round-trip. Null for non-worktree sessions; older state files
2086
+ // (pre-#5310) restore as null → treated as a non-worktree session.
2087
+ worktreePath: entry.worktreePath || null,
2088
+ worktreeRepoDir: entry.worktreeRepoDir || null,
2089
+ // Mailbox (#5914 follow-up): persist the registered AGENT_COMM_ID so a
2090
+ // session keeps its mailbox identity across a daemon restart (re-applied
2091
+ // via createSession on restore below). Null when the session never
2092
+ // registered one; older state files (no field) restore as null.
2093
+ agentCommId: entry.agentCommId || null,
2094
+ lastActivityAt: this._sessionLastActivityAt.get(id) || entry.createdAt,
2095
+ history,
2096
+ // #4664: persist per-session toggle/string settings via the
2097
+ // shared registry — each entry's coerce produces the same
2098
+ // strict-boolean/string-default shape the pre-refactor per-knob
2099
+ // code wrote (so an old state file round-trips identically).
2100
+ ...serializePerSessionSettings(entry.session),
2101
+ // #3639: persist the per-session skip-pattern source. Null when
2102
+ // unset — old state files (pre-#3639) restore as null (the
2103
+ // BaseSession default) so this is fully backward compatible.
2104
+ // Treat empty string as null too: the setter and restoreState
2105
+ // both normalise '' to null, so persisting '' would not
2106
+ // round-trip and would violate the non-empty-string-or-null
2107
+ // invariant.
2108
+ promptEvaluatorSkipPattern:
2109
+ typeof entry.session.promptEvaluatorSkipPattern === 'string' &&
2110
+ entry.session.promptEvaluatorSkipPattern.length > 0
2111
+ ? entry.session.promptEvaluatorSkipPattern
2112
+ : null,
2113
+ // #3540: persist the SidecarProcess `stdin_disabled` latch so a
2114
+ // server restart preserves the disabled state. Without this, a
2115
+ // client connecting after restart would not see the banner — the
2116
+ // original `error` event fired against the previous process and
2117
+ // was not replayed. Strict-boolean coerce so non-Sdk providers
2118
+ // (which never set this field) round-trip as `false`.
2119
+ stdinForwardingDisabled: !!entry.session._stdinForwardingDisabled,
2120
+ // #4089: persist cumulativeUsage so the dashboard sidebar badge
2121
+ // (#4073) and mobile session-header badge (#4074) survive a
2122
+ // server restart. Without this, the badge resets to $0 on
2123
+ // restart even though the operator's spending continues. Round-
2124
+ // trips through restoreState below as the entry's
2125
+ // `cumulativeUsage` field. Older state files (pre-#4089) restore
2126
+ // as null — restoreState seeds an all-zero block in that case.
2127
+ cumulativeUsage: entry.cumulativeUsage || null,
2128
+ // #4124: persist the per-session threshold-notified latch so the
2129
+ // "you've spent $X" warning fires once per LOGICAL session, not
2130
+ // once per process. Without this the warning re-fires on every
2131
+ // restart even after the user has already seen and dismissed it.
2132
+ //
2133
+ // Strict-boolean check (not `!!`) so a stray truthy non-boolean
2134
+ // value (an accidentally-stored string, etc.) does not silently
2135
+ // round-trip as `true` — only an explicit `true` latches.
2136
+ // Mirrors the restore side which gates on `=== true`.
2137
+ costThresholdNotified: entry.costThresholdNotified === true,
2138
+ }
2139
+ }
2140
+
2141
+ /**
2142
+ * Restore session state from disk after a restart.
2143
+ * Creates new sessions using saved parameters. SdkSession can resume
2144
+ * via resumeSessionId; CliSession starts fresh (process state is ephemeral).
2145
+ * @returns {string|null} The first restored session ID, or null
2146
+ */
2147
+ restoreState() {
2148
+ // #6276: reap orphaned user-shell PTYs FIRST — before the no-prior-state
2149
+ // early return below — so it runs on EVERY boot. A SIGKILL/crash skips
2150
+ // destroySession's SIGTERM, leaving a `$SHELL` reparented to init with no
2151
+ // destroy-audit entry; the daemon may have no session state to restore yet
2152
+ // still have a live orphaned shell recorded in the sidecar, so this cannot
2153
+ // hang off state restoration. Runs unconditionally (independent of the
2154
+ // userShell.enabled gate, so a shell from when the feature was enabled is
2155
+ // cleaned up after it's turned off). No-op when the sidecar is absent (the
2156
+ // clean-shutdown case). Best-effort — a reaper hiccup never affects boot.
2157
+ try {
2158
+ const { reaped, skipped } = reapOrphanShells(this._userShellSidecarPath, this._userShellReapSeams)
2159
+ for (const r of reaped) {
2160
+ auditShellDestroy({ sessionId: r.sessionId, exitCode: null, reason: 'orphan_reaper' })
2161
+ }
2162
+ if (reaped.length || skipped.length) {
2163
+ log.warn(`user-shell orphan reaper: reaped=${reaped.length} skipped=${skipped.length}`)
2164
+ }
2165
+ } catch (err) {
2166
+ log.warn(`user-shell orphan reaper failed (non-fatal): ${err?.message || err}`)
2167
+ }
2168
+
2169
+ const state = this._persistence.restoreState()
2170
+ if (!state) return null
2171
+
2172
+ const hasVersion = typeof state.version === 'number'
2173
+
2174
+ let firstId = null
2175
+ let anyFailure = false
2176
+ const oldToNew = new Map() // old serialized session ID → new session ID
2177
+ for (const saved of state.sessions) {
2178
+ try {
2179
+ // skipPersist: we rewrite the state file once at the end of
2180
+ // restoreState, after history and cost budget have been reseeded.
2181
+ // Flushing per-session here would overwrite the on-disk file with
2182
+ // empty history for all not-yet-processed sessions, erasing the
2183
+ // data we're trying to restore.
2184
+ const sessionId = this.createSession({
2185
+ // #4983 — reuse the persisted ID so dashboard's localStorage-
2186
+ // cached activeSessionId still resolves after a daemon restart.
2187
+ // createSession validates the format (32-char lower-case hex);
2188
+ // a malformed or duplicate id falls back to randomBytes so the
2189
+ // call still succeeds. The dashboard's #4982 SESSION_NOT_FOUND
2190
+ // chip is the safety net for the malformed/missing/cross-host
2191
+ // cases that this preservation can't help with.
2192
+ preserveId: saved.id,
2193
+ name: saved.name,
2194
+ cwd: saved.cwd,
2195
+ model: saved.model,
2196
+ permissionMode: saved.permissionMode,
2197
+ resumeSessionId: saved.sdkSessionId,
2198
+ provider: saved.provider || undefined,
2199
+ // #5310 (WP-0.4) — rebind to the existing worktree (don't recreate).
2200
+ // Only string paths flow through; non-worktree sessions and older
2201
+ // state files (no field) pass undefined and take the normal path.
2202
+ restoreWorktreePath: typeof saved.worktreePath === 'string' && saved.worktreePath.length > 0
2203
+ ? saved.worktreePath
2204
+ : undefined,
2205
+ restoreWorktreeRepoDir: typeof saved.worktreeRepoDir === 'string' && saved.worktreeRepoDir.length > 0
2206
+ ? saved.worktreeRepoDir
2207
+ : undefined,
2208
+ // #4664: restore per-session toggle/string settings via the
2209
+ // shared registry. Each registry entry's `acceptFromConstructor`
2210
+ // predicate drops malformed values to `undefined` so
2211
+ // createSession applies BaseSession's default — exact match for
2212
+ // the pre-refactor per-knob behaviour, and older state files
2213
+ // (without these fields) round-trip cleanly.
2214
+ ...restorePerSessionSettings(saved),
2215
+ // #3639: forward the persisted skip-pattern source. Non-string /
2216
+ // empty values are dropped (createSession ignores them) so older
2217
+ // state files restore as null. Kept out of the registry because
2218
+ // the empty-string-as-null wire shape doesn't fit the
2219
+ // boolean/string factory.
2220
+ promptEvaluatorSkipPattern: typeof saved.promptEvaluatorSkipPattern === 'string' && saved.promptEvaluatorSkipPattern.length > 0
2221
+ ? saved.promptEvaluatorSkipPattern
2222
+ : undefined,
2223
+ // #3540: forward the persisted stdin_disabled latch. Only
2224
+ // truthy values flip the flag; pre-#3540 state files (no
2225
+ // field) restore as `false`. The SdkSession constructor
2226
+ // initialises `_stdinForwardingDisabled` from this opt and
2227
+ // the existing `_attachSidecarProcessListeners` short-circuit
2228
+ // ensures no warn/error is re-emitted on restore — clients
2229
+ // observe the disabled state via session_list metadata.
2230
+ stdinForwardingDisabled: saved.stdinForwardingDisabled === true ? true : undefined,
2231
+ // Restore the previously-booted model (#3700b) so the dashboard
2232
+ // dropdown shows the real model on reconnect, not the registry
2233
+ // fallback. createSession() ignores non-string / empty values so
2234
+ // older state files (pre-#3700b) restore cleanly as null.
2235
+ bootedModel: typeof saved.bootedModel === 'string' && saved.bootedModel.length > 0
2236
+ ? saved.bootedModel
2237
+ : undefined,
2238
+ // Restore the messageId counter so new turns don't reuse old IDs
2239
+ // and collide with dashboard-cached messages (#3700).
2240
+ messageCounter: typeof saved.messageCounter === 'number' && Number.isFinite(saved.messageCounter) && saved.messageCounter >= 0
2241
+ ? saved.messageCounter
2242
+ : undefined,
2243
+ // Mailbox (#5914 follow-up): re-register the persisted AGENT_COMM_ID so
2244
+ // a restored session is reachable by the live-interrupt route again.
2245
+ // createSession validates it (drops bad values to a no-op); older
2246
+ // state files (no field) restore with no mailbox identity.
2247
+ agentCommId: typeof saved.agentCommId === 'string' && saved.agentCommId.length > 0
2248
+ ? saved.agentCommId
2249
+ : undefined,
2250
+ skipPersist: true,
2251
+ // #5316 (WP-2.2) — mark this as a restore so an ASYNC provider
2252
+ // start() rejection (claude-tui PTY warmup death) preserves the
2253
+ // restored history + worktree instead of destroying them.
2254
+ isRestore: true,
2255
+ })
2256
+ if (saved.id) oldToNew.set(saved.id, sessionId)
2257
+ // #4089 / #4124: restore the per-session running totals + the
2258
+ // threshold-notified latch onto the freshly-created entry. We do
2259
+ // this AFTER createSession so the entry exists, and BEFORE
2260
+ // history replay so a synthetic result event during replay
2261
+ // (unlikely but defensive) doesn't double-count. Validate shape:
2262
+ // missing / corrupt cumulativeUsage falls back to all-zero;
2263
+ // non-boolean costThresholdNotified falls back to false.
2264
+ //
2265
+ // Per-field clamps:
2266
+ // - Token counts + turnsBilled are monotonic counters; corrupt
2267
+ // state with negatives clamps to 0.
2268
+ // - costUsd accepts negatives per #4099 (refund / credit
2269
+ // adjustments). Only non-finite values fall back to 0.
2270
+ const restoredEntry = this._sessions.get(sessionId)
2271
+ const nonNegFinite = (v) => (Number.isFinite(v) && v >= 0 ? v : 0)
2272
+ if (restoredEntry) {
2273
+ if (saved.cumulativeUsage && typeof saved.cumulativeUsage === 'object') {
2274
+ const u = saved.cumulativeUsage
2275
+ restoredEntry.cumulativeUsage = {
2276
+ inputTokens: nonNegFinite(u.inputTokens),
2277
+ outputTokens: nonNegFinite(u.outputTokens),
2278
+ cacheReadTokens: nonNegFinite(u.cacheReadTokens),
2279
+ cacheCreationTokens: nonNegFinite(u.cacheCreationTokens),
2280
+ costUsd: Number.isFinite(u.costUsd) ? u.costUsd : 0,
2281
+ turnsBilled: nonNegFinite(u.turnsBilled),
2282
+ }
2283
+ }
2284
+ if (saved.costThresholdNotified === true) {
2285
+ restoredEntry.costThresholdNotified = true
2286
+ }
2287
+ }
2288
+ // Keep _sessionCounter ahead of any restored "Session N" names so the
2289
+ // first new auto-named session after restore never collides (#2338).
2290
+ if (saved.name) {
2291
+ const match = saved.name.match(/^Session (\d+)$/)
2292
+ if (match) {
2293
+ const n = parseInt(match[1], 10)
2294
+ if (n > this._sessionCounter) this._sessionCounter = n
2295
+ }
2296
+ }
2297
+ // Restore message history if present (v1+).
2298
+ // Sweep any `tool_start` that lacks a matching `tool_result` and
2299
+ // splice in a synthetic interrupted result (#4617) BEFORE seeding
2300
+ // history so the subsequent dashboard history replay never sees a
2301
+ // dangling tool_start. Without this, an unresolved tool_use from
2302
+ // before shutdown re-enters `activeTools` on replay and never gets
2303
+ // cleared — the footer shows "Running X · Nh Mm" forever.
2304
+ if (hasVersion && Array.isArray(saved.history) && saved.history.length > 0) {
2305
+ const swept = SessionMessageHistory.sweepUnresolvedToolStarts(saved.history)
2306
+ this._history.setHistory(sessionId, swept)
2307
+ }
2308
+ if (typeof saved.lastActivityAt === 'number' && Number.isFinite(saved.lastActivityAt) && saved.lastActivityAt > 0) {
2309
+ this._sessionLastActivityAt.set(sessionId, saved.lastActivityAt)
2310
+ }
2311
+ if (!firstId) firstId = sessionId
2312
+ log.info(`Restored session "${saved.name}" (SDK resume: ${saved.sdkSessionId || 'none'})`)
2313
+ } catch (err) {
2314
+ // Guardian FM-01 (#2954): don't silently drop the session. Track it
2315
+ // so serializeState() rewrites it back to disk (preserving history)
2316
+ // and surface an event so clients can show a "needs attention" UI.
2317
+ anyFailure = true
2318
+ const failedId = this._registerFailedRestore(saved, err)
2319
+ // Advance _sessionCounter past failed "Session N" names too, so any
2320
+ // new sessions created during this boot don't collide with the name
2321
+ // still occupying disk state.
2322
+ if (saved.name) {
2323
+ const match = saved.name.match(/^Session (\d+)$/)
2324
+ if (match) {
2325
+ const n = parseInt(match[1], 10)
2326
+ if (n > this._sessionCounter) this._sessionCounter = n
2327
+ }
2328
+ }
2329
+ log.error(`Failed to restore session "${saved.name}" (${saved.provider || 'default'}): ${err.message}`)
2330
+ this.emit('session_restore_failed', {
2331
+ sessionId: failedId,
2332
+ name: saved.name,
2333
+ provider: saved.provider || this._providerType,
2334
+ cwd: saved.cwd,
2335
+ model: saved.model || null,
2336
+ permissionMode: saved.permissionMode || null,
2337
+ errorCode: err?.code || 'RESTORE_FAILED',
2338
+ errorMessage: err?.message || String(err),
2339
+ originalHistoryPreserved: true,
2340
+ historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
2341
+ })
2342
+ }
2343
+ }
2344
+
2345
+ // Restore cost tracking data (v1+), remapping old IDs to new IDs.
2346
+ this._costBudget.restore(state, oldToNew.size > 0 ? oldToNew : null)
2347
+
2348
+ // Swarm-audit: drop failed-restore entries whose session has been inactive
2349
+ // past the TTL. A chronically-failing session (e.g. a missing env var the
2350
+ // user never fixes) otherwise re-fails + re-persists on EVERY boot, growing
2351
+ // _failedRestores + session-state.json without bound (clearFailedRestore is
2352
+ // only called on a user retry/dismiss, which may never come). Runs BEFORE the
2353
+ // flush (so the prune lands on disk) and BEFORE the worktree sweep (so a
2354
+ // pruned session's worktree is reclaimed too).
2355
+ this._pruneStaleFailedRestores()
2356
+
2357
+ // Now that history and budget are reseeded, flush once so the on-disk
2358
+ // state reflects the restored state (and so any subsequent abrupt
2359
+ // shutdown preserves it). Flush if we restored any session OR had any
2360
+ // failure — otherwise the next successful save would drop failed-restore
2361
+ // entries. (serializeState() re-includes them from _failedRestores.)
2362
+ if (firstId || anyFailure) this._flushPersist()
2363
+
2364
+ // #5859 (audit P1-7): now that the live session set is rebuilt, sweep
2365
+ // orphaned chroxy session worktrees — dirs under the worktree base whose
2366
+ // session id is no longer live (left by a SIGKILL / crash / dropped state
2367
+ // file; P0-3 stopped deleting them on clean shutdown, so they accrue). Opt-in
2368
+ // and clean-tree-guarded (never deletes uncommitted/untracked/ignored work);
2369
+ // best-effort so a GC hiccup never affects boot.
2370
+ if (this._sweepOrphanWorktrees) {
2371
+ try {
2372
+ // The live set MUST include FAILED-restore sessions: those are kept in
2373
+ // _failedRestores keyed by their original id (= the worktree dir
2374
+ // basename) with worktreePath preserved on disk for a later retry
2375
+ // (#2954). Treating their clean worktree as an orphan would delete the
2376
+ // very checkout #2954 preserves — and a --detach worktree's commits
2377
+ // would become unreachable. Union both so neither live nor failed-but-
2378
+ // retained sessions are ever swept.
2379
+ const liveSessionIds = new Set([...this._sessions.keys(), ...this._failedRestores.keys()])
2380
+ const report = sweepOrphanChroxyWorktrees({
2381
+ worktreeBase: this._worktreeBase || DEFAULT_WORKTREE_BASE,
2382
+ liveSessionIds,
2383
+ })
2384
+ if (report.removed.length || report.skippedDirty.length || report.skippedError.length) {
2385
+ log.info(`worktree orphan sweep: removed=${report.removed.length} skippedDirty=${report.skippedDirty.length} skippedError=${report.skippedError.length} (scanned ${report.scanned})`)
2386
+ }
2387
+ } catch (err) {
2388
+ log.warn(`worktree orphan sweep failed (non-fatal): ${err?.message || err}`)
2389
+ }
2390
+ }
2391
+
2392
+ return firstId
2393
+ }
2394
+
2395
+ /**
2396
+ * Register a failed-restore entry so its history is preserved on disk.
2397
+ * Returns the synthetic session ID used for external reporting.
2398
+ * @param {object} saved - The saved session payload from the state file
2399
+ * @param {Error} err - The error thrown during restore
2400
+ * @returns {string} sessionId
2401
+ * @private
2402
+ */
2403
+ _registerFailedRestore(saved, err) {
2404
+ // Reuse the saved id when present so the client-visible identity is
2405
+ // stable across restart attempts; fall back to a random id otherwise.
2406
+ const sessionId = saved.id || randomBytes(16).toString('hex')
2407
+ this._failedRestores.set(sessionId, { saved, error: err })
2408
+ return sessionId
2409
+ }
2410
+
2411
+ /**
2412
+ * Drop failed-restore entries whose session has been inactive longer than the
2413
+ * TTL, so a chronically-failing session can't grow _failedRestores +
2414
+ * session-state.json without bound across boots. Conservative by design: a
2415
+ * recently-active failure is KEPT (it still surfaces in the "needs attention"
2416
+ * UI for retry), and an entry with no usable timestamp is kept rather than
2417
+ * guessed-stale. Failed-restore entries are display + retry only, so pruning a
2418
+ * long-dead one has no operational effect beyond removing the stale UI entry.
2419
+ * Worktree-backed failed-restores are NEVER pruned (guard below) so the #2954
2420
+ * worktree-preservation contract is never widened by this cleanup.
2421
+ * @param {number} [now]
2422
+ * @returns {number} count pruned
2423
+ */
2424
+ _pruneStaleFailedRestores(now = Date.now()) {
2425
+ const TTL_MS = 30 * 24 * 60 * 60 * 1000 // 30 days
2426
+ let pruned = 0
2427
+ for (const [sessionId, entry] of this._failedRestores) {
2428
+ const saved = entry?.saved
2429
+ // NEVER prune a worktree-backed failed-restore. Removing its id from the
2430
+ // live set exposes its worktree to the orphan sweep, whose clean-tree guard
2431
+ // can't see committed-but-UNREACHABLE commits on a --detach worktree (#2954)
2432
+ // and would reclaim (then GC) that work. Bounding only the worktree-less
2433
+ // entries still closes the common unbounded-growth case (config-error
2434
+ // restores) without widening the #2954 worktree-preservation contract.
2435
+ if (saved?.worktreePath) continue
2436
+ const last = (typeof saved?.lastActivityAt === 'number' && saved.lastActivityAt > 0)
2437
+ ? saved.lastActivityAt
2438
+ : (typeof saved?.createdAt === 'number' && saved.createdAt > 0 ? saved.createdAt : null)
2439
+ if (last !== null && Number.isFinite(last) && now - last > TTL_MS) {
2440
+ this._failedRestores.delete(sessionId)
2441
+ pruned++
2442
+ log.info(`Pruned stale failed-restore "${saved?.name || sessionId}" (inactive since ${new Date(last).toISOString()})`)
2443
+ }
2444
+ }
2445
+ if (pruned > 0) log.info(`Pruned ${pruned} stale failed-restore session(s) (inactive > 30d)`)
2446
+ return pruned
2447
+ }
2448
+
2449
+ /**
2450
+ * Return the list of sessions that failed to restore at startup.
2451
+ * UI uses this to show a "needs attention" state with a retry affordance.
2452
+ * @returns {Array<{ sessionId, name, provider, errorCode, errorMessage, needsAttention, historyLength }>}
2453
+ */
2454
+ getFailedRestores() {
2455
+ const list = []
2456
+ for (const [sessionId, { saved, error }] of this._failedRestores) {
2457
+ list.push({
2458
+ sessionId,
2459
+ name: saved.name,
2460
+ provider: saved.provider || this._providerType,
2461
+ cwd: saved.cwd,
2462
+ model: saved.model || null,
2463
+ permissionMode: saved.permissionMode || null,
2464
+ errorCode: error?.code || 'RESTORE_FAILED',
2465
+ errorMessage: error?.message || String(error),
2466
+ needsAttention: true,
2467
+ historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
2468
+ })
2469
+ }
2470
+ return list
2471
+ }
2472
+
2473
+ /**
2474
+ * Clear a failed-restore entry. Called after a successful retry (or when
2475
+ * the user dismisses the failed session so it stops reappearing).
2476
+ * @param {string} sessionId
2477
+ * @returns {boolean} true if an entry was cleared
2478
+ */
2479
+ clearFailedRestore(sessionId) {
2480
+ if (!this._failedRestores.has(sessionId)) return false
2481
+ this._failedRestores.delete(sessionId)
2482
+ this._flushPersist()
2483
+ return true
2484
+ }
2485
+
2486
+ /**
2487
+ * Check if all sessions are idle (not busy).
2488
+ * Used by drain protocol to wait for in-flight work.
2489
+ * @returns {boolean}
2490
+ */
2491
+ allIdle() {
2492
+ for (const [, entry] of this._sessions) {
2493
+ if (entry.session.isRunning) return false
2494
+ }
2495
+ return true
2496
+ }
2497
+
2498
+ /**
2499
+ * Get message history for a session.
2500
+ * @returns {Array<{ type, ...data }>}
2501
+ */
2502
+ getHistory(sessionId) {
2503
+ return this._history.getHistory(sessionId)
2504
+ }
2505
+
2506
+ /**
2507
+ * Get the count of messages in the ring buffer for a session.
2508
+ * @param {string} sessionId
2509
+ * @returns {number}
2510
+ */
2511
+ getHistoryCount(sessionId) {
2512
+ return this._history.getHistoryCount(sessionId)
2513
+ }
2514
+
2515
+ /**
2516
+ * @param {string} sessionId
2517
+ * @returns {boolean}
2518
+ */
2519
+ isHistoryTruncated(sessionId) {
2520
+ return this._history.isHistoryTruncated(sessionId)
2521
+ }
2522
+
2523
+ /**
2524
+ * #5555.3 — seq of the oldest history entry still retained in the ring
2525
+ * buffer (null when empty). The cursor-replay path compares a client's
2526
+ * `lastSeq` against this to detect a trim gap.
2527
+ * @param {string} sessionId
2528
+ * @returns {number|null}
2529
+ */
2530
+ getOldestHistorySeq(sessionId) {
2531
+ return this._history.getOldestSeq(sessionId)
2532
+ }
2533
+
2534
+ /**
2535
+ * #5555.3 — seq of the newest history entry (0 when empty). When a client's
2536
+ * `lastSeq >= this`, there is nothing newer to replay.
2537
+ * @param {string} sessionId
2538
+ * @returns {number}
2539
+ */
2540
+ getLatestHistorySeq(sessionId) {
2541
+ return this._history.getLatestSeq(sessionId)
2542
+ }
2543
+
2544
+ /**
2545
+ * Get the conversation ID (SDK session ID) for a session.
2546
+ * @returns {string|null}
2547
+ */
2548
+ getConversationId(sessionId) {
2549
+ const entry = this._sessions.get(sessionId)
2550
+ if (!entry) return null
2551
+ return entry.session.resumeSessionId || null
2552
+ }
2553
+
2554
+ /**
2555
+ * Get full conversation history asynchronously by reading the JSONL file.
2556
+ * Avoids blocking the event loop for large files (use in WS handlers).
2557
+ * Falls back to the ring buffer if JSONL is unavailable.
2558
+ * @returns {Promise<Array<{ type, content, tool?, timestamp, messageId? }>>}
2559
+ */
2560
+ async getFullHistoryAsync(sessionId) {
2561
+ const entry = this._sessions.get(sessionId)
2562
+ if (!entry || entry._destroying) return []
2563
+
2564
+ const conversationId = entry.session.resumeSessionId
2565
+ if (conversationId) {
2566
+ try {
2567
+ const filePath = resolveJsonlPath(entry.cwd, conversationId)
2568
+ const history = await readConversationHistoryAsync(filePath)
2569
+ if (history.length > 0) return history
2570
+ } catch (err) {
2571
+ log.error(`Failed to read JSONL history for session ${sessionId}: ${err?.message || err}`)
2572
+ }
2573
+ }
2574
+
2575
+ // Fallback to ring buffer
2576
+ return this.getHistory(sessionId)
2577
+ }
2578
+
2579
+ /**
2580
+ * Record a user input message in the session's history ring buffer.
2581
+ * Public API for ws-server to record user messages so they survive reconnect replay.
2582
+ *
2583
+ * On the first non-empty input, auto-labels sessions with default names
2584
+ * ("Session N" or "New Session") to a truncation of the input text.
2585
+ *
2586
+ * @param {string} sessionId
2587
+ * @param {string} text
2588
+ * @param {string} [messageId] - Stable ID propagated to replay and the
2589
+ * live-echo broadcast so clients can dedup their optimistic copy against
2590
+ * rehydrated history on reconnect (issue #2902).
2591
+ */
2592
+ recordUserInput(sessionId, text, messageId) {
2593
+ const entry = this._sessions.get(sessionId)
2594
+ this._history.recordUserInput(sessionId, text, entry || undefined, messageId)
2595
+ }
2596
+
2597
+ /**
2598
+ * Record an event into the session's message history ring buffer.
2599
+ * Delegates to SessionMessageHistory and triggers persist when needed.
2600
+ */
2601
+ _recordHistory(sessionId, event, data) {
2602
+ const { persistNeeded, truncated } = this._history.recordHistory(sessionId, event, data)
2603
+ if (persistNeeded) {
2604
+ this._schedulePersist()
2605
+ }
2606
+ if (truncated) {
2607
+ // #6431 — an over-size stream delta was dropped from history. The client
2608
+ // still received it (forwarded independently via the stream_delta proxy),
2609
+ // so its local copy now diverges from the persisted message. Surface a
2610
+ // client-visible error so the truncation is observable instead of a silent
2611
+ // desync. Emitted once per stream (the history layer dedupes).
2612
+ // The event-normalizer's generic `error` builder forwards only `message`
2613
+ // + `code` to clients, so the payload is kept to exactly what reaches them
2614
+ // — no dead `messageId` / `recoverable` fields that would imply a
2615
+ // correlation the wire never delivers (#6431 review).
2616
+ this.emit('session_event', {
2617
+ sessionId,
2618
+ event: 'error',
2619
+ data: {
2620
+ code: 'stream_truncated',
2621
+ message: 'A response exceeded the server buffer limit and was truncated server-side; the saved message may be incomplete.',
2622
+ },
2623
+ })
2624
+ }
2625
+ }
2626
+
2627
+ /**
2628
+ * Push an entry to the history array, trimming to max size.
2629
+ * Backward-compatible delegate to SessionMessageHistory._pushHistory.
2630
+ * @param {Array} history - The session history array to push to
2631
+ * @param {object} entry - The history entry to add
2632
+ * @param {string} sessionId - The session ID (used for truncation tracking)
2633
+ */
2634
+ _pushHistory(history, entry, sessionId) {
2635
+ this._history._pushHistory(history, entry, sessionId)
2636
+ }
2637
+
2638
+ /**
2639
+ * Schedule a debounced persist. Multiple rapid calls reset the timer.
2640
+ * No-op once `destroyAll()` has run — see `serializeState()` (#3697).
2641
+ */
2642
+ _schedulePersist() {
2643
+ if (this._destroying) return
2644
+ this._persistence.schedulePersist(() => this.serializeState())
2645
+ }
2646
+
2647
+ /**
2648
+ * Flush persist synchronously, bypassing the debounce. Use for session-list
2649
+ * mutations (create/rename/destroy) where losing the write on abrupt
2650
+ * shutdown erases a user's session. History/budget updates should keep
2651
+ * using the debounced path to avoid write amplification.
2652
+ */
2653
+ _flushPersist() {
2654
+ return this._persistence.flushPersist(() => this.serializeState())
2655
+ }
2656
+
2657
+ /**
2658
+ * #5701: flush a session-list mutation and surface a failure instead of
2659
+ * swallowing it. flushPersist used to catch-and-log write errors (disk full,
2660
+ * locked file, read-only home), so a create/rename/destroy could succeed in
2661
+ * memory yet never reach disk and silently revert on the next restart. Now a
2662
+ * failed flush is logged at error level with an operator-actionable hint and
2663
+ * emits `session_persist_failed` so it is observable. (A client-facing banner
2664
+ * is a follow-up — it needs a new wire message type; `session_warning` is
2665
+ * reserved for the idle-timeout countdown UI and must not be overloaded.)
2666
+ * @param {string} sessionId
2667
+ * @param {string|null} name - pass explicitly to control the logged label:
2668
+ * the new name on rename, or the entry's name on destroy (where the entry
2669
+ * is already removed from `_sessions` before this flush, so a lookup would
2670
+ * be nameless). Omit to look it up from `_sessions`.
2671
+ * @returns {boolean} true if the write succeeded.
2672
+ */
2673
+ _flushPersistOrWarn(sessionId, name = null) {
2674
+ if (this._flushPersist()) return true
2675
+ const resolvedName = name || this._sessions.get(sessionId)?.name || null
2676
+ log.error(`Session state for ${sessionId}${resolvedName ? ` ("${resolvedName}")` : ''} was NOT persisted — it may be lost on restart. Check disk space and write permissions for ${this._stateFilePath}.`)
2677
+ this.emit('session_persist_failed', { sessionId, name: resolvedName })
2678
+ return false
2679
+ }
2680
+
2681
+ /**
2682
+ * Wire session events to unified session_event emission.
2683
+ * Handles both CliSession and PtySession events.
2684
+ */
2685
+ _wireSessionEvents(sessionId, session) {
2686
+ // #5431: background_tasks_changed — claude-tui's idle transcript re-scan
2687
+ // reporting that outstanding background work changed (a task-notification
2688
+ // landed or a wakeup fired while no turn was running). Deliberately NOT
2689
+ // an ACTIVITY_EVENT: the session is idle by definition when it fires, so
2690
+ // it must not reset the idle timeout.
2691
+ const PROXIED_EVENTS = ['ready', 'stream_start', 'stream_delta', 'stream_end', 'message', 'tool_start', 'tool_result', 'result', 'error', 'user_question', 'background_tasks_changed']
2692
+ // Events that indicate meaningful activity (reset idle timeout)
2693
+ const ACTIVITY_EVENTS = new Set(['message', 'stream_start', 'tool_start', 'result', 'user_question'])
2694
+ // Session-scoped logger — entries are tagged with sessionId for per-session routing
2695
+ const sessionLog = log.withSession(sessionId)
2696
+ // Events worth logging to the System tab (skip noisy delta/tool_result)
2697
+ const LOGGED_EVENTS = new Set(['ready', 'stream_start', 'stream_end', 'result', 'error'])
2698
+
2699
+ // #5835 Phase 1: claude-tui live PTY mirror (the "remote viewer" / authenticity
2700
+ // surface). These are transient, high-frequency redraw bytes — proxy them to
2701
+ // subscribed clients but keep them OUT of _recordHistory (not conversation
2702
+ // history) and OUT of touchActivity (a mirror frame is not user activity).
2703
+ // Wired separately from PROXIED_EVENTS for exactly that reason.
2704
+ session.on('terminal_output', (data) => {
2705
+ this.emit('session_event', { sessionId, event: 'terminal_output', data })
2706
+ })
2707
+
2708
+ // #5835 Phase 2: authoritative live-PTY size changes (a primary viewer drove
2709
+ // a resize). Like terminal_output, transient and kept out of history/activity
2710
+ // — ws-forwarding broadcasts it to terminal subscribers as `terminal_size`.
2711
+ session.on('terminal_resize', (data) => {
2712
+ this.emit('session_event', { sessionId, event: 'terminal_resize', data })
2713
+ })
2714
+
2715
+ // #5982 — auto-remove a user-shell session when its PTY exits on its own
2716
+ // (the user typed `exit`, or the shell died). A short grace lets a live
2717
+ // viewer read the "[shell exited]" marker, then the session is destroyed so
2718
+ // no dead zombie shells linger in the list. UserShellSession emits
2719
+ // `shell_exited` ONLY from its natural-exit path; an explicit destroySession
2720
+ // detaches this listener first (removeAllListeners), so a deliberate
2721
+ // teardown never schedules a redundant auto-remove. The timer is unref'd so
2722
+ // it can't keep the process alive, and re-checks the session still exists
2723
+ // (and isn't already tearing down) before destroying.
2724
+ if (session.constructor?.isUserShell === true) {
2725
+ // #6276: record the live PTY pid to the orphan-reaper sidecar so a shell
2726
+ // left running by an ungraceful daemon death (SIGKILL/crash, which skips
2727
+ // destroySession's SIGTERM) can be reaped + audited on the next boot. The
2728
+ // matching record is dropped by destroySession on a clean teardown.
2729
+ session.on('shell_spawned', ({ pid } = {}) => {
2730
+ recordShell(this._userShellSidecarPath, { sessionId, pid, shell: session._shellPath })
2731
+ })
2732
+ session.on('shell_exited', () => {
2733
+ const timer = setTimeout(() => {
2734
+ const entry = this._sessions.get(sessionId)
2735
+ if (entry && !entry._destroying) {
2736
+ log.info(`Auto-removing exited user-shell session ${sessionId}`)
2737
+ // Calls destroySession directly, intentionally bypassing the
2738
+ // handler-layer "cannot destroy the last session" guard: that guard
2739
+ // stops a USER from emptying their list, not a dead shell from being
2740
+ // reaped — a zombie shell shouldn't be force-kept just because it's
2741
+ // the last session.
2742
+ this.destroySession(sessionId)
2743
+ }
2744
+ }, AUTO_REMOVE_ON_EXIT_DELAY_MS)
2745
+ if (typeof timer.unref === 'function') timer.unref()
2746
+ })
2747
+ }
2748
+
2749
+ for (const event of PROXIED_EVENTS) {
2750
+ session.on(event, (data) => {
2751
+ if (ACTIVITY_EVENTS.has(event)) this.touchActivity(sessionId)
2752
+ this._recordHistory(sessionId, event, data)
2753
+ this.emit('session_event', { sessionId, event, data })
2754
+ if (LOGGED_EVENTS.has(event)) {
2755
+ const detail = event === 'error' ? `: ${data?.message || ''}` : ''
2756
+ const logFn = event === 'error' ? sessionLog.error : sessionLog.info
2757
+ logFn(`[${event}]${detail}`)
2758
+ }
2759
+
2760
+ // When SDK session reports ready, emit conversation_id if available
2761
+ if (event === 'ready' && session.resumeSessionId) {
2762
+ this.emit('session_event', {
2763
+ sessionId,
2764
+ event: 'conversation_id',
2765
+ data: { conversationId: session.resumeSessionId },
2766
+ })
2767
+ }
2768
+
2769
+ // Track cumulative cost and token usage on turn-terminal events.
2770
+ // Both `result` (success path) AND `error` (failure path, partial
2771
+ // spend surfaced by #5037) fold into the same cumulative tracker —
2772
+ // otherwise the user-billed tokens on a failed turn would silently
2773
+ // drop out of cumulativeUsage / sessionCost / budget gates (#5038).
2774
+ //
2775
+ // Billing-class cost contract (#5630/#5629): which turns produce a
2776
+ // real dollar figure depends on the session's billing class.
2777
+ // - subscription (claude-tui/claude-channel, and HOST claude-cli/sdk
2778
+ // BEFORE 2026-06-15): `total_cost_usd: null` → no per-turn dollar
2779
+ // charge; the cost accumulator stays zero and the UI shows the
2780
+ // no-dollar "Included (subscription)" chip.
2781
+ // - programmatic-credit (HOST claude-cli/sdk ON/AFTER 2026-06-15):
2782
+ // real metered credit spend — the provider now forwards a finite
2783
+ // `total_cost_usd`, so the finite-cost gate below accumulates it
2784
+ // exactly like api-key spend.
2785
+ // - api-key (byok, docker-byok, docker-cli/sdk — which forward an
2786
+ // ANTHROPIC_API_KEY into the container with no OAuth fallback — and
2787
+ // every non-Claude provider): real per-token spend, always a finite
2788
+ // cost (or `null` when pricing is unknown — see computePromptCostUsd,
2789
+ // which now degrades 0→null; the finite gate skips a null without
2790
+ // poisoning the accumulator).
2791
+ //
2792
+ // Two independent gates (#5115):
2793
+ // 1. COST gate — `Number.isFinite(data?.cost)`. Drives _trackCost
2794
+ // (the $ accumulator + budget thresholds). Subscription-billed
2795
+ // runs report `total_cost_usd: null`, so this stays zero for
2796
+ // them (no dollar budget applies to a flat subscription).
2797
+ // 2. USAGE gate — finite cost OR finite `usage.input_tokens`.
2798
+ // Drives _trackUsage (the cumulativeUsage token accumulator
2799
+ // that lights up the dashboard header meter). A subscription
2800
+ // `claude -p` turn carries real token counts with `cost: null`
2801
+ // (#5095 / #5108 verified cli-session forwards the full usage
2802
+ // payload verbatim), so the meter must ratchet on tokens, not
2803
+ // cost. _trackUsage itself drops a non-finite cost via an
2804
+ // explicit Number.isFinite coercion, so cumulativeCost is never
2805
+ // poisoned even when this gate passes on tokens alone.
2806
+ //
2807
+ // Single-counting guarantee: each priced/usage-bearing turn folds
2808
+ // in exactly once.
2809
+ // - Happy path: a single `result` (finite cost AND usage) per turn.
2810
+ // - Subscription path: a single `result` (cost null, finite
2811
+ // input_tokens) per turn → counted via the usage gate.
2812
+ // - byok-session error path: a single `error` (finite cost for the
2813
+ // partial spend, see #5037).
2814
+ // - Stream-stall path (sdk-session._handleStreamStall and
2815
+ // cli-session._handleStreamStall — the latter calls
2816
+ // _emitInterruptedTurnResult for the synthetic `result` and
2817
+ // then emits the `error` itself): emits BOTH a synthetic
2818
+ // `result` AND `error` for the same turn — but the synthetic
2819
+ // `result` carries `cost: null` AND `usage: null`, so BOTH gates
2820
+ // filter it. The `error` half is plain stream-stall metadata
2821
+ // (no cost / no usage field), also filtered by both gates.
2822
+ // No emit topology change is needed to add new failure paths as long
2823
+ // as they keep this invariant (terminal turn ⇒ at most one event
2824
+ // carrying a finite cost and/or finite input_tokens).
2825
+ //
2826
+ // Number.isFinite also guards against NaN / Infinity (provider
2827
+ // bugs) poisoning cumulative totals or triggering spurious budget
2828
+ // events (#4088 review).
2829
+ if (event === 'result' || event === 'error') {
2830
+ const hasFiniteCost = Number.isFinite(data?.cost)
2831
+ const hasFiniteTokens = Number.isFinite(data?.usage?.input_tokens)
2832
+ if (hasFiniteCost) {
2833
+ const sessionEntry = this._sessions.get(sessionId)
2834
+ const model = session.currentModel || sessionEntry?.model || null
2835
+ this._trackCost(sessionId, data.cost, model)
2836
+ }
2837
+ // #4072 / #5115: accumulate token usage for cumulative-display.
2838
+ // Runs when EITHER cost OR input_tokens is finite, so
2839
+ // subscription-only providers (cost: null, finite tokens) ratchet
2840
+ // the header meter (#5115) while NaN/Infinity-only payloads still
2841
+ // can't poison the accumulator.
2842
+ //
2843
+ // #5038: an errored turn DOES count as a billed turn — the user
2844
+ // was charged for the partial work — so `turnsBilled` ticks
2845
+ // exactly as it would on the success path.
2846
+ if (hasFiniteCost || hasFiniteTokens) {
2847
+ this._trackUsage(sessionId, data)
2848
+ }
2849
+ }
2850
+ })
2851
+ }
2852
+
2853
+ // Transient events — forwarded but not recorded in history (not replayed on reconnect).
2854
+ // `skill_changed` (#3204) lands here so a paired dashboard / mobile client can
2855
+ // surface a "this skill's content has changed since first activation" prompt
2856
+ // without the event being replayed on every reconnect (the loader re-checks
2857
+ // the hash every time skills are scanned, so the latest state is always
2858
+ // canonical).
2859
+ // #4756: `stopped` is a transient signal — CliSession emits it when the
2860
+ // child process exits cleanly after a user-initiated Stop (see
2861
+ // cli-session.js `_handleChildClose`, gated on `_intentionalStop`). It
2862
+ // pairs with `error` (which fires for unexpected crashes that trigger
2863
+ // auto-respawn) so a paired dashboard / mobile client can render a quiet
2864
+ // "Session stopped." confirmation distinct from the louder crash toast.
2865
+ // Transient so it isn't replayed on reconnect — by the time a client
2866
+ // reconnects, either the session was destroyed or the user already saw
2867
+ // the confirmation.
2868
+ // #5016: `agent_event` carries a Task subagent's intermediate wire
2869
+ // events (tool_start / tool_result / tool_input_delta / stream_delta)
2870
+ // tagged with the parent's toolUseId. Transient (not replayed on
2871
+ // reconnect — the canonical Task tool_result fold lands in history).
2872
+ // #5160: `activity_delta` / `activity_snapshot` carry the Control Room
2873
+ // activity tree (ActivityRegistry on BaseSession). Transient — not
2874
+ // replayed from history; a reconnecting client gets the full tree from
2875
+ // the snapshot-on-subscribe in ws-history.sendSessionInfo.
2876
+ // #5936: message_queued / message_dequeued mirror the server-authoritative
2877
+ // outgoing-message queue (BaseSession `_outgoingQueue`). Transient (like
2878
+ // activity_delta) — they are delta events, NOT replayed from history. This
2879
+ // slice ships only the deltas; a server→client queue SNAPSHOT (so a
2880
+ // reconnecting client can rehydrate any still-queued state) is the
2881
+ // store-core follow-up (#5937). Until then a client that reconnects
2882
+ // mid-queue won't see the pre-existing queued items — acceptable for the
2883
+ // foundation slice, tracked in #5937.
2884
+ const builtinTransient = ['permission_request', 'permission_resolved', 'permission_expired', 'agent_spawned', 'agent_completed', 'agent_event', 'plan_started', 'plan_ready', 'mcp_servers', 'skill_changed', 'skill_trust_request', 'skill_trust_granted', 'inactivity_warning', 'background_work_changed', 'stopped', 'activity_delta', 'activity_snapshot', 'message_queued', 'message_dequeued']
2885
+ const customEvents = Array.isArray(session.constructor.customEvents) ? session.constructor.customEvents : []
2886
+ const TRANSIENT_EVENTS = [...new Set([...builtinTransient, ...customEvents])]
2887
+ for (const event of TRANSIENT_EVENTS) {
2888
+ session.on(event, (data) => {
2889
+ this.emit('session_event', { sessionId, event, data })
2890
+ })
2891
+ }
2892
+
2893
+ // models_updated is global (not per-session) — forward as transient event
2894
+ session.on('models_updated', (data) => {
2895
+ this.emit('session_event', { sessionId, event: 'models_updated', data })
2896
+ })
2897
+
2898
+ // #5315 (WP-2.1) — a provider that exhausts its bounded PTY auto-respawn
2899
+ // budget emits `respawn_exhausted`. The transient-events loop above already
2900
+ // forwarded it to clients (it's in ClaudeTuiSession.customEvents); here we
2901
+ // ALSO drop the session from the list so the audit AC holds: the session
2902
+ // leaves the list with a clear error instead of lingering as an
2903
+ // input-rejecting zombie tab. Mirrors the session_timeout → destroySession
2904
+ // coordination (this file, ~457). Guard on _sessions.has so a duplicate
2905
+ // signal doesn't log a spurious "session not found" error — destroySession
2906
+ // logs + returns false on a missing id rather than no-opping silently.
2907
+ session.on('respawn_exhausted', (data) => {
2908
+ if (!this._sessions.has(sessionId)) return
2909
+ sessionLog.error(`[respawn_exhausted] ${data?.reason || 'pty respawn gave up'} — destroying session`)
2910
+ this.destroySession(sessionId)
2911
+ })
2912
+ }
2913
+
2914
+ // ---------------------------------------------------------------------------
2915
+ // Session idle timeout (delegated to SessionTimeoutManager)
2916
+ // ---------------------------------------------------------------------------
2917
+
2918
+ /**
2919
+ * Set the function used to check if a session has active WebSocket viewers.
2920
+ * Called by WsServer after construction to wire the two components together.
2921
+ * @param {(sessionId: string) => boolean} fn
2922
+ */
2923
+ setActiveViewersFn(fn) {
2924
+ this._timeoutManager.setActiveViewersFn(fn)
2925
+ }
2926
+
2927
+ /**
2928
+ * Record activity for a session (resets idle timer).
2929
+ * Called internally on relevant events, and publicly by WsServer on user input.
2930
+ */
2931
+ touchActivity(sessionId) {
2932
+ this._sessionLastActivityAt.set(sessionId, Date.now())
2933
+ this._timeoutManager.touchActivity(sessionId)
2934
+ }
2935
+
2936
+ /**
2937
+ * Expose internal timeout tracking state for backward compatibility.
2938
+ * Tests and internal code may reference these directly.
2939
+ */
2940
+ get _lastActivity() {
2941
+ return this._timeoutManager._lastActivity
2942
+ }
2943
+
2944
+ get _sessionWarned() {
2945
+ return this._timeoutManager._sessionWarned
2946
+ }
2947
+
2948
+ // ---------------------------------------------------------------------------
2949
+ // Cost budget tracking
2950
+ // ---------------------------------------------------------------------------
2951
+
2952
+ /**
2953
+ * Track cumulative cost for a session and check budget thresholds.
2954
+ * @param {string} sessionId
2955
+ * @param {number} cost - Cost of the latest query in dollars
2956
+ */
2957
+ _trackCost(sessionId, cost, model = null) {
2958
+ const budgetEvent = this._costBudget.trackCost(sessionId, cost, model)
2959
+ const cumulative = this._costBudget.getSessionCost(sessionId)
2960
+
2961
+ // Emit cost_update for every result so app can track cumulative cost
2962
+ const entry = this._sessions.get(sessionId)
2963
+ this.emit('session_event', {
2964
+ sessionId,
2965
+ event: 'cost_update',
2966
+ data: {
2967
+ sessionCost: cumulative,
2968
+ totalCost: this._costBudget.getTotalCost(),
2969
+ budget: this._costBudget.getBudget(),
2970
+ },
2971
+ })
2972
+
2973
+ if (budgetEvent) {
2974
+ const budget = this._costBudget.getBudget()
2975
+ this.emit('session_event', {
2976
+ sessionId,
2977
+ event: budgetEvent.event,
2978
+ data: {
2979
+ ...budgetEvent.data,
2980
+ message: budgetEvent.event === 'budget_exceeded'
2981
+ ? `Session "${entry?.name || sessionId}" has exceeded the $${budget.toFixed(2)} budget ($${cumulative.toFixed(4)})`
2982
+ : `Session "${entry?.name || sessionId}" has used ${budgetEvent.data.percent}% of the $${budget.toFixed(2)} budget ($${cumulative.toFixed(4)})`,
2983
+ },
2984
+ })
2985
+ }
2986
+ }
2987
+
2988
+ /**
2989
+ * Accumulate per-session token usage + cost across turns and broadcast
2990
+ * a `session_usage` event so subscribed clients can update their
2991
+ * cost/token badges live (#4072 — sub-task of #4054).
2992
+ *
2993
+ * Reads SDK-style usage shape (`input_tokens`, `output_tokens`,
2994
+ * `cache_read_input_tokens`, `cache_creation_input_tokens`) and the
2995
+ * `cost` field added by #4056. Emits the camelCased aggregate shape
2996
+ * for the UI.
2997
+ *
2998
+ * Defensive: if the entry has no `cumulativeUsage` (e.g. a custom
2999
+ * provider built the entry directly without going through createSession),
3000
+ * lazily initialize on first use so subsequent calls accumulate.
3001
+ * @param {string} sessionId
3002
+ * @param {{ usage?: object, cost?: number }} resultData
3003
+ */
3004
+ _trackUsage(sessionId, resultData) {
3005
+ const entry = this._sessions.get(sessionId)
3006
+ if (!entry) return
3007
+ if (!entry.cumulativeUsage) entry.cumulativeUsage = makeZeroCumulativeUsage()
3008
+ const u = resultData?.usage || {}
3009
+ const acc = entry.cumulativeUsage
3010
+ // #5115: coerce each delta defensively before accumulating. Plain
3011
+ // `Number(x) || 0` does NOT reject Infinity (Infinity is truthy), so a
3012
+ // provider bug that reports Infinity tokens / cost would poison the
3013
+ // accumulator. Now that the usage gate lets `cost: null` / non-finite
3014
+ // cost through (so subscription tokens ratchet), the cost line in
3015
+ // particular MUST drop a non-finite cost rather than add it — exactly
3016
+ // the cumulativeCost-poison guard called out in #5115's acceptance
3017
+ // criteria and #4088.
3018
+ //
3019
+ // Per-field coercion mirrors the restore-time clamp (restoreState's
3020
+ // `nonNegFinite`) and CumulativeUsageSchema (@chroxy/protocol):
3021
+ // - Token fields are monotonic NON-NEGATIVE integer counters. A
3022
+ // negative provider delta (bug) would drive them below zero and
3023
+ // violate the schema's `.nonnegative()` contract, so drop any delta
3024
+ // that isn't a finite, >= 0 number.
3025
+ // - costUsd is finite but intentionally SIGNED — a refund / credit
3026
+ // adjustment turn (#4099) legitimately subtracts — so only reject
3027
+ // a non-finite cost.
3028
+ const tokenDelta = (x) => (Number.isFinite(x) && x >= 0 ? x : 0)
3029
+ const finiteCost = (x) => (Number.isFinite(x) ? x : 0)
3030
+ acc.inputTokens += tokenDelta(Number(u.input_tokens))
3031
+ acc.outputTokens += tokenDelta(Number(u.output_tokens))
3032
+ acc.cacheReadTokens += tokenDelta(Number(u.cache_read_input_tokens))
3033
+ acc.cacheCreationTokens += tokenDelta(Number(u.cache_creation_input_tokens))
3034
+ acc.costUsd += finiteCost(Number(resultData?.cost))
3035
+ acc.turnsBilled += 1
3036
+ // #5630/#5629: carry the per-session billing class on the live usage
3037
+ // event so a client that joined before the first session_list (or after a
3038
+ // mid-session era flip) labels the cost row correctly without a refetch.
3039
+ // Resolved the same way as listSessions; defensive so a misbehaving
3040
+ // provider can't break the usage broadcast.
3041
+ const usageProvider = entry.provider || this._providerType
3042
+ let billingClass
3043
+ try {
3044
+ billingClass = getProviderAuthInfo(usageProvider, entry.session.constructor)?.billingClass
3045
+ } catch {
3046
+ billingClass = undefined
3047
+ }
3048
+ if (!billingClass) billingClass = billingClassForProvider(usageProvider, Date.now())
3049
+ // Shallow-copy on emit so a subscriber that mutates the payload
3050
+ // can't corrupt the canonical accumulator (#4072 review-prep).
3051
+ this.emit('session_event', {
3052
+ sessionId,
3053
+ event: 'session_usage',
3054
+ data: { cumulativeUsage: { ...acc }, billingClass },
3055
+ })
3056
+ // #5665: feed this turn's cost into the machine-wide monthly
3057
+ // programmatic-credit meter, but ONLY for programmatic-credit sessions
3058
+ // (claude-cli/sdk on/after the 2026-06-15 era). The era gate is implicit:
3059
+ // billingClass only resolves to PROGRAMMATIC_CREDIT post-boundary. Broadcast
3060
+ // the updated meter to ALL clients (it's per-machine, not per-session).
3061
+ if (billingClass === BILLING_CLASSES.PROGRAMMATIC_CREDIT) {
3062
+ // Pass the RAW cost (not finiteCost-coerced) so recordSpend's own
3063
+ // Number.isFinite guard drops a non-finite turn entirely — coercing to 0
3064
+ // here would still bump turnsBilled for a turn with no real cost.
3065
+ const { status, justWarned, justExceeded } = this._creditBudget.recordSpend(Number(resultData?.cost), Date.now())
3066
+ this.emit('session_event', {
3067
+ sessionId,
3068
+ event: 'monthly_budget',
3069
+ data: { ...status, justWarned, justExceeded },
3070
+ })
3071
+ }
3072
+ // #4075: soft threshold crossing. Fire ONCE per session: the latch
3073
+ // (`costThresholdNotified`) stays true for the session's lifetime so
3074
+ // a tool-heavy turn that crosses the threshold doesn't spam the
3075
+ // banner. Subscription-billed providers never trigger this because
3076
+ // their cost stays at 0 — the `> 0` gate on the threshold itself
3077
+ // also short-circuits when an operator disables the feature.
3078
+ //
3079
+ // Both the latch and `cumulativeUsage` are persisted in the
3080
+ // session-state snapshot (#4089 / #4124), so the warning fires once
3081
+ // per LOGICAL session — survives server restarts and matches what
3082
+ // the dashboard / mobile UI shows.
3083
+ if (
3084
+ this._costThresholdUsd > 0 &&
3085
+ !entry.costThresholdNotified &&
3086
+ acc.costUsd >= this._costThresholdUsd
3087
+ ) {
3088
+ entry.costThresholdNotified = true
3089
+ this.emit('session_event', {
3090
+ sessionId,
3091
+ event: 'session_cost_threshold_crossed',
3092
+ data: {
3093
+ costUsd: acc.costUsd,
3094
+ thresholdUsd: this._costThresholdUsd,
3095
+ },
3096
+ })
3097
+ }
3098
+ }
3099
+
3100
+ /**
3101
+ * #5665: current monthly programmatic-credit meter snapshot (machine-wide).
3102
+ * Sent to a client on connect so a freshly-loaded dashboard shows the meter
3103
+ * without waiting for the next billed turn. Shape mirrors the `monthly_budget`
3104
+ * event payload (minus the one-shot justWarned/justExceeded flags).
3105
+ */
3106
+ getMonthlyBudgetStatus() {
3107
+ return this._creditBudget.getStatus(Date.now())
3108
+ }
3109
+
3110
+ /**
3111
+ * #4075: Validate + clamp a costThresholdUsd input. Accepts finite
3112
+ * non-negative numbers; coerces null/undefined to the supplied default;
3113
+ * rejects strings, NaN, Infinity, negatives.
3114
+ * @param {unknown} value
3115
+ * @param {number} fallback
3116
+ * @returns {number} threshold in USD; 0 means "disabled"
3117
+ */
3118
+ _normalizeCostThreshold(value, fallback) {
3119
+ if (value === null || value === undefined) return fallback
3120
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
3121
+ return fallback
3122
+ }
3123
+ return value
3124
+ }
3125
+
3126
+ /**
3127
+ * #4601: Sanitise a per-provider timeout-override map at construction time.
3128
+ *
3129
+ * Returns a NEW plain object containing only the entries whose value passed
3130
+ * `isOperatorTimeoutInRange`. Non-object inputs return `null` (no overrides
3131
+ * apply). Each rejected entry logs ONE warn line tagged with the offending
3132
+ * provider id so an operator scanning logs can correlate it back to the
3133
+ * config.json key path.
3134
+ *
3135
+ * Keeping the validation here (vs. inlining it in createSession) means
3136
+ * each session boot does a single map lookup instead of revalidating
3137
+ * every entry on every call.
3138
+ *
3139
+ * @param {unknown} input — raw config map (object | null | undefined | bogus)
3140
+ * @param {object} opts
3141
+ * @param {string} opts.name — config-key prefix used in warn logs
3142
+ * (e.g. `providerStreamStallTimeoutMs`); each rejected entry is logged as
3143
+ * `<name>.<providerId>` so the warn matches the operator's config path.
3144
+ * @param {boolean} [opts.allowZero=false] — passed through to
3145
+ * `isOperatorTimeoutInRange` (set true for stream-stall, which uses 0 as
3146
+ * an explicit per-provider disable).
3147
+ * @returns {object|null} sanitised entries, or null if the input wasn't a
3148
+ * plain object.
3149
+ */
3150
+ _sanitizeProviderTimeoutMap(input, { name, allowZero = false }) {
3151
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null
3152
+ const sanitised = {}
3153
+ const MAX_SANE_DURATION_MS = 24 * 60 * 60 * 1000
3154
+ for (const [providerId, value] of Object.entries(input)) {
3155
+ const ok = isOperatorTimeoutInRange(value, { allowZero, name: `${name}.${providerId}`, log })
3156
+ if (ok) {
3157
+ sanitised[providerId] = value
3158
+ continue
3159
+ }
3160
+ // `isOperatorTimeoutInRange` already emits a tagged warn for the
3161
+ // over-ceiling case (see duration.js:39); avoid duplicating it
3162
+ // here. The lower-bound / non-finite / negative paths return
3163
+ // false silently, so we still need to surface those — emit ONE
3164
+ // warn so an operator scanning logs can correlate the dropped
3165
+ // entry back to the config.json key path.
3166
+ const numericValue = typeof value === 'number' ? value : NaN
3167
+ if (Number.isFinite(numericValue) && numericValue > MAX_SANE_DURATION_MS) continue
3168
+ log.warn(`ignoring invalid entry '${name}.${providerId}'=${String(value)} — falling back to global / default`)
3169
+ }
3170
+ return sanitised
3171
+ }
3172
+
3173
+ /**
3174
+ * #4075: Get the current cost threshold (USD). 0 means disabled.
3175
+ * @returns {number}
3176
+ */
3177
+ getCostThresholdUsd() {
3178
+ return this._costThresholdUsd
3179
+ }
3180
+
3181
+ /**
3182
+ * #4075: Update the cost threshold at runtime (e.g. from the dashboard
3183
+ * settings panel). Setting to 0 disables the soft warning. Does NOT
3184
+ * reset per-session latches — operators raising the threshold mid-
3185
+ * session won't re-trigger an already-fired warning on the SAME session,
3186
+ * since the latch records "we already warned." Lowering the threshold
3187
+ * causes the next turn that crosses the new threshold to fire as
3188
+ * expected on sessions that haven't yet been notified.
3189
+ *
3190
+ * Invalid input (negative, NaN, Infinity, non-number) is silently
3191
+ * coerced to the CURRENT value via `_normalizeCostThreshold`'s
3192
+ * fallback — bad input is a no-op. Callers that want to validate
3193
+ * up-front should compare the return value against the input.
3194
+ * @param {number} value USD; must be a finite non-negative number
3195
+ * @returns {number} the applied value (unchanged if input was invalid)
3196
+ */
3197
+ setCostThresholdUsd(value) {
3198
+ this._costThresholdUsd = this._normalizeCostThreshold(value, this._costThresholdUsd)
3199
+ return this._costThresholdUsd
3200
+ }
3201
+
3202
+ /**
3203
+ * Read the current cumulative usage for a session, or null if missing.
3204
+ * Returns a shallow copy so callers can't mutate the canonical entry.
3205
+ * @param {string} sessionId
3206
+ */
3207
+ getCumulativeUsage(sessionId) {
3208
+ const entry = this._sessions.get(sessionId)
3209
+ if (!entry?.cumulativeUsage) return null
3210
+ return { ...entry.cumulativeUsage }
3211
+ }
3212
+
3213
+ /**
3214
+ * Start periodic session timeout checks.
3215
+ * Only starts if sessionTimeout was configured.
3216
+ */
3217
+ startSessionTimeouts() {
3218
+ this._timeoutManager.start()
3219
+ }
3220
+
3221
+ /**
3222
+ * Stop periodic session timeout checks.
3223
+ */
3224
+ stopSessionTimeouts() {
3225
+ this._timeoutManager.stop()
3226
+ }
3227
+
3228
+ getSessionCost(sessionId) {
3229
+ return this._costBudget.getSessionCost(sessionId)
3230
+ }
3231
+
3232
+ getTotalCost() {
3233
+ return this._costBudget.getTotalCost()
3234
+ }
3235
+
3236
+ getCostBudget() {
3237
+ return this._costBudget.getBudget()
3238
+ }
3239
+
3240
+ isBudgetPaused(sessionId) {
3241
+ return this._costBudget.isPaused(sessionId)
3242
+ }
3243
+
3244
+ resumeBudget(sessionId) {
3245
+ this._costBudget.resume(sessionId)
3246
+ this._schedulePersist()
3247
+ log.info(`Budget pause overridden for session ${sessionId}`)
3248
+ }
3249
+
3250
+ getCostByModel() {
3251
+ return this._costBudget.getCostByModel()
3252
+ }
3253
+
3254
+ getSpendRate() {
3255
+ return this._costBudget.getSpendRate()
3256
+ }
3257
+ }