@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,1518 @@
1
+ /**
2
+ * BaseSession — shared state and behavior for all session providers.
3
+ *
4
+ * Extracts the common state machine (busy/ready flags, message counter,
5
+ * agent tracking) and shared method patterns (setModel guard,
6
+ * setPermissionMode validation, _clearMessageState) so CliSession,
7
+ * SdkSession, and GeminiSession don't duplicate them.
8
+ */
9
+ import { EventEmitter } from 'events'
10
+ import { randomBytes } from 'crypto'
11
+ import { resolveModelId } from './models.js'
12
+ import {
13
+ formatSkillsForPrompt,
14
+ SKILLS_PROMPT_HEADER,
15
+ } from './skills-loader.js'
16
+ import { SkillsManager } from './skills-manager.js'
17
+ import { BackgroundShellTracker } from './background-shell-tracker.js'
18
+ import { isOperatorTimeoutInRange } from './duration.js'
19
+ import { createLogger } from './logger.js'
20
+ import { ActivityRegistry } from './activity-registry.js'
21
+ import { ALLOWED_PERMISSION_MODE_IDS } from './handler-utils.js'
22
+
23
+ const log = createLogger('base-session')
24
+
25
+ // #3805: opt-in Chroxy context paragraph. Prepended to `_buildSystemPrompt()`
26
+ // output when `chroxyContextHint` is true so the model knows it's running
27
+ // inside Chroxy's remote-terminal front-end and can adjust its output for
28
+ // mobile clients (narrower code blocks, no wide ASCII diagrams). Kept short
29
+ // (~50 words) to minimise token overhead on every turn.
30
+ export const CHROXY_CONTEXT_HINT_TEXT =
31
+ 'You are running inside Chroxy, a remote-control front-end that bridges this session to a mobile phone over a Cloudflare tunnel. ' +
32
+ 'The user may be on a small screen. Prefer concise, copyable answers; keep code blocks narrow (<80 cols); ' +
33
+ 'avoid ASCII diagrams and wide tables; chunk long output so it scrolls smoothly on mobile.'
34
+
35
+ // #4660: per-session user-authored preamble, prepended to `_buildSystemPrompt()`
36
+ // output every turn so the user can pre-load context once instead of retyping
37
+ // it in every message. Cap at 4000 chars so a hand-edited state file or a
38
+ // malicious client can't bloat the system prompt without bound — comfortably
39
+ // fits a dense paragraph or two of style/stack notes while keeping the per-
40
+ // turn token overhead predictable.
41
+ export const SESSION_PREAMBLE_MAX_LENGTH = 4000
42
+
43
+ // #5936 (epic #5935): explicit overflow cap for the shared outgoing-message
44
+ // queue (`_outgoingQueue`). Replaces the SDK's hard-coded mid-turn cap of 3
45
+ // (#5711) with one bounded, surfaced limit shared by SDK + CLI. A send-while-
46
+ // busy message past this cap is discarded with a visible `error` event
47
+ // (`code: 'queue_full'`) — never a silent drop. Generous enough for a realistic
48
+ // burst of owner follow-ups while still bounding memory if a client wedges.
49
+ export const OUTGOING_QUEUE_MAX = 10
50
+
51
+ // #3884 / #3749 / #3899: default SOFT inactivity warning (ms). Activity-based
52
+ // — every provider event (SDK iterator message, CLI stdout JSONL line)
53
+ // resets the timer; the window only bounds *silent stretches*, not wall-
54
+ // clock turn duration. Was 5 min → 20 min (#3749) → 30 min (#3884).
55
+ //
56
+ // Pre-#3899 this was the kill timer (when it fired, the session was
57
+ // force-cleared). Post-#3899 it fires the `inactivity_warning` event
58
+ // instead — the session stays alive and the client surfaces a check-in
59
+ // affordance. The kill path now lives behind `_hardTimeoutMs` below.
60
+ //
61
+ // Operators can override per server via config.resultTimeoutMs or
62
+ // CHROXY_RESULT_TIMEOUT_MS.
63
+ export const DEFAULT_RESULT_TIMEOUT_MS = 30 * 60 * 1000
64
+
65
+ // #3899: HARD-cap timeout (ms). When silence continues for this long
66
+ // past `sendMessage` (with no activity to reset it AND no user check-in
67
+ // after the soft warning), the session is force-cleared, pending
68
+ // permissions are auto-denied, and an error is emitted — the pre-#3899
69
+ // behaviour, preserved as the absolute backstop for genuinely stuck
70
+ // sessions (dead SDK iterator, host suspended, network hang the OS
71
+ // hasn't surfaced yet).
72
+ //
73
+ // Default 2h: wide enough to cover marathons users actually run
74
+ // (/batch-merge over 20+ PRs, multi-hour /tackle-issues sessions);
75
+ // tight enough to bound runaway sessions before they accumulate
76
+ // real cost / memory.
77
+ //
78
+ // Operators can override per server via config.hardTimeoutMs or
79
+ // CHROXY_HARD_TIMEOUT_MS.
80
+ export const DEFAULT_HARD_TIMEOUT_MS = 2 * 60 * 60 * 1000
81
+
82
+ // #4467: stream-stall recovery timeout (ms). Resets on ANY stream event from
83
+ // the child (stdout line, stream_delta, tool_start, etc.). When no event has
84
+ // arrived for this long while busy, emit a recoverable error (code:
85
+ // `stream_stall`) and clear busy state so the user can retry. Distinct from
86
+ // the soft inactivity warning — the warning is passive (just a chip); this
87
+ // is active recovery.
88
+ //
89
+ // Default 5 minutes: a stalled HTTPS connection to the Anthropic API
90
+ // (half-open TCP, mobile NAT idle, Cloudflare timeout) typically would have
91
+ // recovered by then if it was going to; longer-than-5min legitimate gaps
92
+ // between events are rare (interactive tools poll faster than that).
93
+ //
94
+ // Operators with workloads that have long compile-then-edit gaps can raise
95
+ // via config.streamStallTimeoutMs or CHROXY_STREAM_STALL_TIMEOUT_MS, or set
96
+ // to 0 to disable.
97
+ export const DEFAULT_STREAM_STALL_TIMEOUT_MS = 5 * 60 * 1000
98
+
99
+ // #5376: the background-shell sweep/quiesce machinery moved to
100
+ // background-shell-tracker.js. Re-exported here so existing importers
101
+ // (session-timeout-manager, tests) keep their import path. See that module for
102
+ // the #5177 / #5247 / #5265 rationale on each window.
103
+ export {
104
+ BACKGROUND_SHELL_SWEEP_MS,
105
+ BACKGROUND_SHELL_QUIESCE_MS,
106
+ BACKGROUND_SHELL_HARD_QUIESCE_MS,
107
+ } from './background-shell-tracker.js'
108
+
109
+ // #5367: canonical list of the opts BaseSession's constructor accepts, in the
110
+ // exact order they appear in the destructure below. Single source of truth for
111
+ // `buildBaseSessionOpts()` — the picker each subclass uses to forward opts down
112
+ // without hand-maintaining a parallel destructure (the "middle-layer trap" that
113
+ // re-shipped three times: #3224 / #3231 / #4790). The CI lint
114
+ // (lint-session-opt-forwarding.mjs) ASSERTS this array equals the set parsed
115
+ // from the constructor destructure, so the two can never drift apart.
116
+ export const BASE_SESSION_OPT_KEYS = [
117
+ 'cwd',
118
+ 'model',
119
+ 'permissionMode',
120
+ 'skillsDir',
121
+ 'repoSkillsDir',
122
+ 'maxSkillBytes',
123
+ 'maxTotalSkillBytes',
124
+ 'provider',
125
+ 'activeManualSkills',
126
+ 'providerSkillAllowlist',
127
+ 'trustStore',
128
+ 'trustMismatchMode',
129
+ 'promptEvaluator',
130
+ 'promptEvaluatorSkipPattern',
131
+ 'chroxyContextHint',
132
+ 'sessionPreamble',
133
+ 'resultTimeoutMs',
134
+ 'hardTimeoutMs',
135
+ 'streamStallTimeoutMs',
136
+ 'backgroundShellHardQuiesceMs',
137
+ ]
138
+
139
+ // #5367: pick the BaseSession opts out of a subclass's full opts bag and merge
140
+ // per-subclass `overrides` on top (overrides win — e.g. provider/model
141
+ // defaults). Uses `if (k in fullOpts)` rather than `??` so an explicitly-passed
142
+ // falsy value (notably `backgroundShellHardQuiesceMs: 0`, which disables
143
+ // hard-reaping) is preserved, and absent keys are omitted entirely (so
144
+ // BaseSession's own `|| default` fallbacks still apply).
145
+ export function buildBaseSessionOpts(fullOpts = {}, overrides = {}) {
146
+ const out = {}
147
+ for (const k of BASE_SESSION_OPT_KEYS) {
148
+ if (k in fullOpts) out[k] = fullOpts[k]
149
+ }
150
+ return { ...out, ...overrides }
151
+ }
152
+
153
+ // #3639: validate a constructor-supplied promptEvaluatorSkipPattern. Only
154
+ // real regex sources survive — anything else (non-string, malformed
155
+ // regex, empty string) falls back to null. Pulled out of the constructor
156
+ // body because the same shape is consulted by `setPromptEvaluatorSkipPattern`
157
+ // at runtime, but the runtime path needs to distinguish "rejected" from
158
+ // "no-op clear" — the constructor only needs the final stored value.
159
+ function _coerceSkipPatternOpt(source) {
160
+ if (typeof source !== 'string' || source.length === 0) return null
161
+ try {
162
+ new RegExp(source, 'i')
163
+ return source
164
+ } catch {
165
+ return null
166
+ }
167
+ }
168
+
169
+ // #4660: validate a constructor-supplied sessionPreamble. Only strings are
170
+ // accepted; anything else (undefined, null, number, object) yields the
171
+ // empty-string default so _buildSystemPrompt() stays byte-identical to
172
+ // pre-#4660. Trim whitespace + cap to SESSION_PREAMBLE_MAX_LENGTH so a
173
+ // hand-edited state file can't smuggle in unbounded text past the wire-
174
+ // level cap enforced by ws-schemas. Empty-after-trim falls back to '' so
175
+ // the OFF semantics (no injection) line up with `chroxyContextHint: false`.
176
+ function _coerceSessionPreambleOpt(value) {
177
+ if (typeof value !== 'string') return ''
178
+ const trimmed = value.trim()
179
+ if (trimmed.length === 0) return ''
180
+ if (trimmed.length > SESSION_PREAMBLE_MAX_LENGTH) {
181
+ return trimmed.slice(0, SESSION_PREAMBLE_MAX_LENGTH)
182
+ }
183
+ return trimmed
184
+ }
185
+
186
+ export class BaseSession extends EventEmitter {
187
+ /**
188
+ * Custom event names emitted by this provider class that should be proxied
189
+ * by SessionManager in addition to the built-in PROXIED_EVENTS list.
190
+ *
191
+ * Override in a subclass and return an array of event name strings.
192
+ * Each name will be forwarded as a transient session_event (not recorded
193
+ * in history and not replayed on reconnect).
194
+ *
195
+ * @returns {string[]}
196
+ */
197
+ static get customEvents() {
198
+ return []
199
+ }
200
+
201
+ /**
202
+ * #5984 (epic #5982): is this session class the claude-tui PTY mirror — the
203
+ * ONLY session type that is a legitimate target for server-initiated
204
+ * PTY-write paths (the mailbox live-interrupt wakeup) and the Control Room's
205
+ * `isTui` flag? Defaults to false; ClaudeTuiSession overrides to true.
206
+ *
207
+ * This replaces the previous `typeof session.writeTerminalInput === 'function'`
208
+ * duck-typing at those sites. The user-shell session (#5983) will ALSO expose
209
+ * `writeTerminalInput` (to receive `terminal_input`), so duck-typing would
210
+ * mis-detect it as claude-tui and let the weaker ingest-secret holder inject
211
+ * an executed line into a root shell (swarm-audit finding C2). A positive
212
+ * class discriminator fails safe: anything not explicitly claude-tui — incl.
213
+ * a future user-shell — is excluded by construction.
214
+ *
215
+ * @returns {boolean}
216
+ */
217
+ static get isClaudeTui() {
218
+ return false
219
+ }
220
+
221
+ /**
222
+ * #5985b (epic #5982): is this session class the general-purpose user shell
223
+ * (spawns the operator's `$SHELL` — arbitrary code execution on the dev
224
+ * machine)? Defaults to false; UserShellSession (#5983) overrides to true.
225
+ *
226
+ * The WS create + terminal_* (input / resize / subscribe) gates use this to
227
+ * require the PRIMARY token class for a shell — a much stricter bar than the
228
+ * session-scoped viewer/primary-claim checks that suffice for the claude-tui
229
+ * mirror (swarm-audit findings C1/C4). Read off the instance via
230
+ * `session.constructor?.isUserShell`. False by construction for every existing
231
+ * session type, so these gates are inert until the provider lands (#5983).
232
+ *
233
+ * @returns {boolean}
234
+ */
235
+ static get isUserShell() {
236
+ return false
237
+ }
238
+
239
+ constructor({
240
+ cwd,
241
+ model,
242
+ permissionMode,
243
+ skillsDir,
244
+ repoSkillsDir,
245
+ maxSkillBytes,
246
+ maxTotalSkillBytes,
247
+ provider,
248
+ activeManualSkills,
249
+ providerSkillAllowlist,
250
+ trustStore,
251
+ trustMismatchMode,
252
+ promptEvaluator,
253
+ promptEvaluatorSkipPattern,
254
+ // #3805: opt-in flag — when true, _buildSystemPrompt prepends a
255
+ // short paragraph telling the model it's running inside Chroxy so
256
+ // it can adjust output for mobile clients (narrower code blocks,
257
+ // no wide ASCII diagrams). Default false — existing users see no
258
+ // observable change.
259
+ chroxyContextHint,
260
+ // #4660: user-authored preamble prepended to `_buildSystemPrompt()`
261
+ // output every turn. String, trimmed + capped to
262
+ // SESSION_PREAMBLE_MAX_LENGTH on construction. Empty string (or any
263
+ // non-string input) is the byte-identical-to-pre-#4660 default.
264
+ sessionPreamble,
265
+ // #3749 / #3884 / #3899: configurable SOFT-warning timeout (the
266
+ // inactivity safety net). Subclasses arm this timer; when it fires
267
+ // they emit an `inactivity_warning` event so the client can render
268
+ // a check-in affordance ("Status update?"). The session stays alive
269
+ // — pre-#3899 this kill behavior moved to `hardTimeoutMs` below.
270
+ // Default 30 min — wide enough to cover long agent loops (batch
271
+ // ops, big refactors) before the user is prompted. Override via
272
+ // ~/.chroxy/config.json#resultTimeoutMs or CHROXY_RESULT_TIMEOUT_MS.
273
+ resultTimeoutMs,
274
+ // #3899: configurable HARD-cap timeout (the kill-the-session
275
+ // backstop). Subclasses arm this in parallel with the soft timer;
276
+ // when it fires they force-clear busy state, auto-deny pending
277
+ // permissions, and emit an error — the pre-#3899 behavior, kept as
278
+ // the absolute safety valve for genuinely stuck sessions. Default
279
+ // 2h. Override via ~/.chroxy/config.json#hardTimeoutMs or
280
+ // CHROXY_HARD_TIMEOUT_MS.
281
+ hardTimeoutMs,
282
+ // #4467: stream-stall recovery timeout. See DEFAULT_STREAM_STALL_TIMEOUT_MS.
283
+ streamStallTimeoutMs,
284
+ // #5288: HARD-quiesce window (ms) for background shells. A finished-but-
285
+ // never-polled shell is reaped after this much continuous output silence
286
+ // so it stops pinning the session "running". Defaults to
287
+ // BACKGROUND_SHELL_HARD_QUIESCE_MS (4h); 0 disables hard-reaping (revert
288
+ // to #5247 advisory-only). Forwarded from config via SessionManager.
289
+ backgroundShellHardQuiesceMs,
290
+ } = {}) {
291
+ super()
292
+ this.cwd = cwd || process.cwd()
293
+ this.model = model || null
294
+ // Actual model the underlying CLI/SDK reports at init time. May differ
295
+ // from `this.model` (the user's requested override) when no override
296
+ // was set — e.g. user sent create_session with no `model`, the CLI
297
+ // booted with whatever `~/.claude/settings.json` had configured. Used
298
+ // for display only; spawn/respawn still uses `this.model` so a null
299
+ // override keeps following the upstream default after CLI updates.
300
+ // Set by subclasses in their init handlers (#3687).
301
+ this.bootedModel = null
302
+ this.permissionMode = permissionMode || 'approve'
303
+ // #3185: per-session toggle for the auto-evaluator chain (parent epic
304
+ // #3068). Default `false` — the existing manual `evaluate_draft` flow
305
+ // (PR #3089) is unaffected by this flag. Coerced to a strict boolean
306
+ // here so JSON.stringify produces `true`/`false` (not `1`/`null`) on
307
+ // the auth_ok / session_list wires.
308
+ this.promptEvaluator = !!promptEvaluator
309
+ // #3639: per-session regex source string used by `shouldSkipEvaluator`
310
+ // to extend the default continuation/ack skip list. Mirrors the
311
+ // server-wide `config.promptEvaluatorSkipPattern` from #3187 but is
312
+ // evaluated FIRST in input-handlers.js so a per-session override
313
+ // beats the global default. Stored as the source string (not a
314
+ // RegExp) — the prompt-evaluator module owns compilation + caching.
315
+ // Validated here as a real regex source on construction; malformed
316
+ // values fall back to null so a hand-edited state file can't crash
317
+ // session creation. The runtime setter (setPromptEvaluatorSkipPattern)
318
+ // does the same validation but reports the rejection so the operator
319
+ // sees a session_error in the dashboard instead of a silent default.
320
+ this.promptEvaluatorSkipPattern = _coerceSkipPatternOpt(promptEvaluatorSkipPattern)
321
+ // #3805: per-session Chroxy context hint flag. Coerced to a strict
322
+ // boolean so `undefined` (omitted by clients on older protocol
323
+ // versions) yields the safe `false` default and JSON.stringify
324
+ // produces `true`/`false` (not `1`/`null`) on the wire.
325
+ this.chroxyContextHint = !!chroxyContextHint
326
+ // #4660: per-session preamble. String-typed: anything else (undefined,
327
+ // null, number, object) falls back to the empty-string default so the
328
+ // _buildSystemPrompt() output stays byte-identical to pre-#4660. Trim
329
+ // + cap so a hand-edited state file or a malformed restore can't
330
+ // smuggle in unbounded text. The runtime setter (setSessionPreamble)
331
+ // does the same coercion and reports rejection on type mismatch.
332
+ this.sessionPreamble = _coerceSessionPreambleOpt(sessionPreamble)
333
+
334
+ this._isBusy = false
335
+ this._processReady = false
336
+ // #5375: user-initiated stop vs crash. Set by interrupt() (markIntentionalStop),
337
+ // captured-and-cleared by the provider's close/error handler
338
+ // (_consumeIntentionalStop) so a clean stop is not reported as an error.
339
+ // Hoisted here from the three providers (#4602/#4881) — see _consumeIntentionalStop
340
+ // and _clearIntentionalStop below. The capture and the safety-net clear are kept
341
+ // as SEPARATE helpers on purpose: SDK relies on a catch-block consume plus a
342
+ // `finally` safety-net clear (the interrupt-races-result case), and collapsing
343
+ // them would reopen that race.
344
+ this._intentionalStop = false
345
+ // #4307/#5177/#5247/#5265: pending background-shell tracking + the reaping
346
+ // sweep live in BackgroundShellTracker (#5376). BaseSession composes one and
347
+ // delegates the public surface (trackBackgroundShell / clearBackgroundShell /
348
+ // getPendingBackgroundShells / _destroyPendingBackgroundShells) plus the
349
+ // test-facing tunables (`_backgroundShell*` get/set shims below) to it;
350
+ // `isRunning` consults its pending count. Events flow from the session via the
351
+ // injected emit. #5288: `backgroundShellHardQuiesceMs` is config-driven; the
352
+ // tracker honours an explicit 0 (disable). See background-shell-tracker.js for
353
+ // the transient-by-design (#4417) and quiescence-window (#4417/#5247/#5265)
354
+ // rationale.
355
+ this._backgroundShellTracker = new BackgroundShellTracker({
356
+ emit: (event, payload) => this.emit(event, payload),
357
+ hardQuiesceMs: backgroundShellHardQuiesceMs,
358
+ })
359
+ // #4307: ephemeral map of recent `Bash` tool_uses dispatched with
360
+ // `run_in_background: true`, keyed by toolUseId. Used to recover the
361
+ // command string when the matching tool_result lands carrying the
362
+ // shellId — the command string is informational (surfaced in the
363
+ // dashboard "waiting on …" chip). Cleared on `_clearMessageState`
364
+ // because once a turn ends, any tool_use blocks that did not see a
365
+ // result this turn are stranded; the agent's next turn re-emits a
366
+ // fresh `tool_use` if it cares to wait again.
367
+ this._pendingBackgroundCommands = new Map()
368
+ // #4628: in-flight tool_start tracking. Each entry is the toolUseId
369
+ // of a tool_start the session has emitted but for which no matching
370
+ // tool_result has fired yet. On `result` (turn end), `_emitResult`
371
+ // sweeps any remaining entries and emits synthetic tool_results so
372
+ // the dashboard's activeTools chip clears. Without this, claude TUI
373
+ // sessions that drop a PostToolUse hook (rare but observed — one
374
+ // Bash out of 35 per the #4628 forensic) leave the chip ticking
375
+ // forever AND persist the orphan to session-state.json. Companion
376
+ // path: SessionMessageHistory.sweepUnresolvedToolStarts (#4617/#4619)
377
+ // catches stragglers at restore-time as a backstop.
378
+ this._inFlightToolStarts = new Map()
379
+ // #5160: per-session activity registry (Control Room). A thin unifying
380
+ // layer that maps the signals BaseSession already emits (tool_start /
381
+ // tool_result / agent_spawned / agent_completed / background_work_changed
382
+ // / permission_request / user_question / permission_resolved) into the
383
+ // `ActivityEntry` wire shape and re-emits `activity_delta` /
384
+ // `activity_snapshot` for the WS layer. NOT a parallel tracker — it
385
+ // listens to this session's own events (wired in _setupActivityRegistry)
386
+ // so it can never drift from the canonical signal source.
387
+ this._activity = new ActivityRegistry({
388
+ sessionId: '',
389
+ emit: (event, payload) => this.emit(event, payload),
390
+ })
391
+ this._setupActivityRegistry()
392
+ this._messageCounter = 0
393
+ // Boot-unique prefix mixed into every emitted messageId (#3700).
394
+ // The dashboard caches up to 100 messages per session in localStorage
395
+ // keyed by server-assigned messageId. Pre-fix, every server boot
396
+ // restarted the counter from 0, so a fresh `msg-1` collided with the
397
+ // dashboard's cached `msg-1` from the previous boot's session — the
398
+ // dashboard's resolveStreamId silently REUSED the old response and
399
+ // appended new deltas to it, leaving the bottom of the chat empty.
400
+ // A 3-byte (6 hex char) random prefix per boot guarantees IDs from
401
+ // different server processes can never share a string namespace, even
402
+ // if the counter happens to land on the same value. 16⁶ ≈ 16.7M
403
+ // values — collision across realistic restart counts is astronomical.
404
+ this._messageIdPrefix = randomBytes(3).toString('hex')
405
+ this._currentMessageId = null
406
+ this._destroying = false
407
+ // #5936 (epic #5935): server-authoritative outgoing-message queue. Holds a
408
+ // follow-up message the OWNER sent while the session was still mid-turn
409
+ // (busy) and flushes it FIFO on the turn-complete `result` event — the
410
+ // single canonical "no more response is coming" signal (where `_isBusy`
411
+ // clears via `_clearMessageState`). Replaces the SDK's ad-hoc `_pendingInput`
412
+ // (cap 3) and the CLI's mid-turn reject, giving both providers one
413
+ // consistent queue → flush-on-complete behaviour. Each entry is
414
+ // `{ prompt, attachments, sendOptions }`; `sendOptions.clientMessageId`
415
+ // (when supplied) lets clients reconcile their optimistic queued bubble.
416
+ // Cross-device arbitration is enforced ABOVE this layer (input-handlers'
417
+ // input_conflict gate) — by the time a send reaches the queue it is the
418
+ // owner's own follow-up, never a way around primary-client arbitration.
419
+ this._outgoingQueue = []
420
+ this._activeAgents = new Map()
421
+ this._resultTimeout = null
422
+ // #3899: parallel hard-cap setTimeout handle. Armed alongside
423
+ // `_resultTimeout` on every activity reset, cleared in lockstep.
424
+ // Fires `_handleHardTimeout` when silence reaches `_hardTimeoutMs`
425
+ // even if the user never engages with the soft check-in prompt.
426
+ this._hardTimeout = null
427
+ // #4467: stream-stall recovery timer. See _streamStallTimeoutMs and
428
+ // CliSession._handleStreamStall for the active-recovery path.
429
+ this._streamStallTimeout = null
430
+ // #3749 / #3884 / #3899: effective SOFT-warning timeout in ms.
431
+ // Defaults to 30 minutes; overrides come from
432
+ // SessionManager(resultTimeoutMs:…) which itself reads
433
+ // ~/.chroxy/config.json#resultTimeoutMs or
434
+ // CHROXY_RESULT_TIMEOUT_MS.
435
+ //
436
+ // #4509: `isOperatorTimeoutInRange` mirrors the ceiling check #4503
437
+ // added to `ws-history.js sendPostAuthInfo`. BaseSession is the final
438
+ // destination — it arms the actual setTimeout against this value — so
439
+ // even when an over-ceiling number sneaks past SessionManager (e.g. a
440
+ // provider that hand-builds providerOpts) we still clamp it here so the
441
+ // inactivity-warning path can't effectively never fire.
442
+ this._resultTimeoutMs =
443
+ isOperatorTimeoutInRange(resultTimeoutMs, { name: 'resultTimeoutMs', log })
444
+ ? resultTimeoutMs
445
+ : DEFAULT_RESULT_TIMEOUT_MS
446
+ // #3899: effective HARD-cap timeout in ms. Defaults to 2 hours.
447
+ // Overrides via SessionManager(hardTimeoutMs:…) ← config.hardTimeoutMs
448
+ // / CHROXY_HARD_TIMEOUT_MS. Operators wanting tight kill-on-stuck
449
+ // semantics can drop this; the soft warning fires first regardless.
450
+ this._hardTimeoutMs =
451
+ isOperatorTimeoutInRange(hardTimeoutMs, { name: 'hardTimeoutMs', log })
452
+ ? hardTimeoutMs
453
+ : DEFAULT_HARD_TIMEOUT_MS
454
+ // #4467: stream-stall recovery timer. 0 disables the active recovery
455
+ // path (the soft warning + hard cap still apply). Non-finite, negative,
456
+ // or above the 24h ceiling falls back to the default.
457
+ this._streamStallTimeoutMs =
458
+ isOperatorTimeoutInRange(streamStallTimeoutMs, { allowZero: true, name: 'streamStallTimeoutMs', log })
459
+ ? streamStallTimeoutMs
460
+ : DEFAULT_STREAM_STALL_TIMEOUT_MS
461
+
462
+ // Provider id (registry key from providers.js — `claude-sdk`, `codex`,
463
+ // etc.). Stored so frontmatter `providers:` filtering (#3198) and
464
+ // injection-mode defaulting (#3200) can run at construction. Optional
465
+ // — tests and ad-hoc instantiations may omit it; the loader treats
466
+ // null provider as "no provider scoping" (skills with a `providers:`
467
+ // list are filtered OUT, skills without one still apply).
468
+ this._provider = provider || null
469
+
470
+ // #2957/#3199/#3204/#3248: the shared-skills system — the manual-activation
471
+ // set, the immutable load-time inputs (dirs, byte caps, provider allowlist),
472
+ // the trust store, the parse cache, and the loader-built caches — lives in
473
+ // SkillsManager (#5376). BaseSession composes one and exposes compat getters
474
+ // (`_skills`, `_skillsDir`, `_activeManualSkills`, `_trustStore`,
475
+ // `_providerSkillAllowlist`, …) so existing consumers, the prompt builders,
476
+ // and the #5367 opt sentinel keep their surface; activateSkill /
477
+ // deactivateSkill / _loadSkills delegate to it. `_provider` (above) is kept
478
+ // on the session for non-skills use and also passed through here.
479
+ this._skillsManager = new SkillsManager({
480
+ cwd: this.cwd,
481
+ provider,
482
+ activeManualSkills,
483
+ skillsDir,
484
+ repoSkillsDir,
485
+ maxSkillBytes,
486
+ maxTotalSkillBytes,
487
+ providerSkillAllowlist,
488
+ trustStore,
489
+ trustMismatchMode,
490
+ emit: (...args) => this.emit(...args),
491
+ })
492
+
493
+ // Skills are scanned at construction. #3209 adds a runtime reload path for
494
+ // manual activation toggles. The construction load deliberately RETURNS its
495
+ // mismatch / community-trust events so they re-emit on `process.nextTick`:
496
+ // SessionManager wires event listeners AFTER the constructor returns, so a
497
+ // synchronous emit here would land on an empty listener set.
498
+ const { trustEvents: pendingTrustEvents, communityTrustEvents: pendingCommunityTrustEvents } = this._skillsManager.loadSkills({ collectTrustEvents: true })
499
+ if (pendingTrustEvents.length > 0 || pendingCommunityTrustEvents.length > 0) {
500
+ process.nextTick(() => {
501
+ for (const ev of pendingTrustEvents) {
502
+ this.emit('skill_changed', ev)
503
+ }
504
+ for (const ev of pendingCommunityTrustEvents) {
505
+ this.emit('skill_trust_request', ev)
506
+ }
507
+ })
508
+ }
509
+ }
510
+
511
+ /**
512
+ * #5376: delegate to SkillsManager. Kept as a session method because
513
+ * settings-handlers.js calls `session._loadSkills()` to rebuild after a
514
+ * trust grant. Returns the pending trust / community-trust events for the
515
+ * caller to emit (the construction path emits them on `process.nextTick`).
516
+ *
517
+ * @param {{ collectTrustEvents?: boolean }} [opts]
518
+ * @returns {{ trustEvents: Array<object>, communityTrustEvents: Array<object> }}
519
+ * @private
520
+ */
521
+ _loadSkills(opts = {}) {
522
+ return this._skillsManager.loadSkills(opts)
523
+ }
524
+
525
+ /**
526
+ * Indicates whether runtime skill toggles take effect on the wire
527
+ * for this provider (#3209 / #3246). The default is `false` — only
528
+ * SdkSession overrides to `true` because the SDK rebuilds
529
+ * `systemPrompt.append` on every turn from `_buildSystemPrompt()`.
530
+ *
531
+ * Subprocess providers (CliSession, CodexSession, GeminiSession)
532
+ * embed the skills text into the persistent subprocess at start
533
+ * (claude `--append-system-prompt`) or onto the first user message
534
+ * (Codex / Gemini's `_skillsPrepended` flag). Mutating in-memory
535
+ * state mid-session does NOT propagate to the running model, so the
536
+ * WS handler refuses the toggle with `SKILL_TOGGLE_UNSUPPORTED` for
537
+ * those providers and the dashboard hides / disables the checkbox.
538
+ *
539
+ * @returns {boolean}
540
+ */
541
+ supportsRuntimeSkillToggle() {
542
+ return false
543
+ }
544
+
545
+ /**
546
+ * Activate a manual skill at runtime (#3209). The skill must
547
+ * actually exist on disk AND declare `activation: manual` —
548
+ * arbitrary strings, typos, and `activation: auto` skill names
549
+ * are rejected (return `false`). Without the existence check, a
550
+ * stale entry would sit in `_activeManualSkills` forever, the
551
+ * loader would silently drop it on every `_loadSkills()` call,
552
+ * and the dashboard checkbox would falsely report success.
553
+ *
554
+ * Returns `true` when the active set actually changed (caller can
555
+ * broadcast `skill_activated` and re-emit). `false` when already
556
+ * active, when the name doesn't correspond to a real manual
557
+ * skill, or when the input shape is invalid.
558
+ *
559
+ * @param {string} skillName
560
+ * @returns {boolean}
561
+ */
562
+ activateSkill(skillName) {
563
+ return this._skillsManager.activateSkill(skillName)
564
+ }
565
+
566
+ /**
567
+ * Deactivate a manual skill at runtime (#3209). Returns true when the active
568
+ * set actually changed; false otherwise. #5376: delegates to SkillsManager.
569
+ *
570
+ * @param {string} skillName
571
+ * @returns {boolean}
572
+ */
573
+ deactivateSkill(skillName) {
574
+ return this._skillsManager.deactivateSkill(skillName)
575
+ }
576
+
577
+ /**
578
+ * #4307: a session is "running" — i.e. NOT idle, NOT subject to
579
+ * `SessionTimeoutManager` reaping — when EITHER:
580
+ * - `_isBusy` is true (the model is mid-turn), OR
581
+ * - the pending-background-shells map is non-empty (the agent
582
+ * dispatched a `run_in_background` Bash and is waiting on it).
583
+ *
584
+ * The second clause is the #4307 fix: previously a session that
585
+ * kicked off a long-running background shell and returned looked
586
+ * indistinguishable from a finished session — `_isBusy` had cleared
587
+ * at turn-end. Now it stays "running" until the agent acknowledges
588
+ * the shell (via a `BashOutput` call) or the session is destroyed.
589
+ *
590
+ * #5247: the map size counts shells the mtime sweep has marked
591
+ * `quiesced` too. The sweep is ADVISORY — it clears the dashboard
592
+ * banner (see `getPendingBackgroundShells`) but must NOT flip liveness,
593
+ * because mtime quiescence can't tell "finished" from "idle but alive"
594
+ * (a dev server that logs once then waits for connections). Letting it
595
+ * flip `isRunning` reaped live processes and let `SessionTimeoutManager`
596
+ * time the session out as idle — re-opening #4307. Liveness authority is
597
+ * therefore BashOutput / destroy only, exactly as #4307 intended; the
598
+ * sweep just affects what the banner shows.
599
+ */
600
+ get isRunning() {
601
+ if (this._isBusy) return true
602
+ return this._backgroundShellTracker.size > 0
603
+ }
604
+
605
+ /**
606
+ * #4307: read-only snapshot of pending background shells.
607
+ * #5376: delegates to BackgroundShellTracker.
608
+ */
609
+ getPendingBackgroundShells() {
610
+ return this._backgroundShellTracker.getPendingBackgroundShells()
611
+ }
612
+
613
+ /**
614
+ * #4307: record a new pending background shell. Idempotent on shellId.
615
+ * #5376: delegates to BackgroundShellTracker. Called by SdkSession /
616
+ * ClaudeTuiSession as a session method.
617
+ *
618
+ * @param {{ shellId: string, command?: string, outputPath?: string }} opts
619
+ * @returns {boolean} true if a new entry was added
620
+ */
621
+ trackBackgroundShell(opts = {}) {
622
+ return this._backgroundShellTracker.trackBackgroundShell(opts)
623
+ }
624
+
625
+ /**
626
+ * #4307: clear a pending background shell by id. Returns true when an entry
627
+ * actually existed. #5376: delegates to BackgroundShellTracker.
628
+ *
629
+ * @param {string} shellId
630
+ * @returns {boolean}
631
+ */
632
+ clearBackgroundShell(shellId) {
633
+ return this._backgroundShellTracker.clearBackgroundShell(shellId)
634
+ }
635
+
636
+ /**
637
+ * #5936: current depth of the outgoing-message queue. Read-only snapshot for
638
+ * tests + any caller that wants to reflect queued state without reaching into
639
+ * `_outgoingQueue` directly.
640
+ *
641
+ * @returns {number}
642
+ */
643
+ get outgoingQueueLength() {
644
+ return this._outgoingQueue.length
645
+ }
646
+
647
+ /**
648
+ * #5936: accept a send-while-busy follow-up into the shared outgoing queue.
649
+ * Called by a provider's `sendMessage` when `_isBusy` (the model is mid-turn)
650
+ * INSTEAD of dropping the message (old SDK) or rejecting with an error (old
651
+ * CLI). The message is held and flushed FIFO on the next `result` via
652
+ * `dequeueNextOutgoing()`.
653
+ *
654
+ * Overflow is surfaced, never silent: past `OUTGOING_QUEUE_MAX` the message is
655
+ * discarded with an `error` event (`code: 'queue_full'`) so the client can
656
+ * tell the user, rather than the queue growing unbounded.
657
+ *
658
+ * Emits `message_queued` (transient; mirrored to clients via the normalizer)
659
+ * on success so both clients can render the queued bubble.
660
+ *
661
+ * @param {{ prompt: any, attachments?: any, sendOptions?: object }} item
662
+ * @returns {boolean} true if the message was queued, false on overflow.
663
+ */
664
+ enqueueOutgoingMessage({ prompt, attachments, sendOptions } = {}) {
665
+ if (this._outgoingQueue.length >= OUTGOING_QUEUE_MAX) {
666
+ this.emit('error', {
667
+ code: 'queue_full',
668
+ message: `Outgoing message queue full (max ${OUTGOING_QUEUE_MAX}) — message discarded`,
669
+ recoverable: true,
670
+ })
671
+ return false
672
+ }
673
+ const opts = sendOptions || {}
674
+ this._outgoingQueue.push({ prompt, attachments, sendOptions: opts })
675
+ this.emit('message_queued', {
676
+ clientMessageId: typeof opts.clientMessageId === 'string' ? opts.clientMessageId : undefined,
677
+ text: typeof prompt === 'string' ? prompt : '',
678
+ queueLength: this._outgoingQueue.length,
679
+ })
680
+ ;(this._log || log).info(`Queued follow-up message (${this._outgoingQueue.length} pending)`)
681
+ return true
682
+ }
683
+
684
+ /**
685
+ * #5936: flush the head of the outgoing queue. Called on the turn-complete
686
+ * `result` path (`_clearMessageState` for CLI, the post-turn `finally` for
687
+ * SDK). Shifts exactly ONE item and re-dispatches it via `sendMessage` on a
688
+ * `process.nextTick` — that send re-sets `_isBusy`, so the NEXT `result`
689
+ * drains the following item, preserving FIFO order one-turn-at-a-time without
690
+ * re-entrancy (synchronous `result` listeners finish first).
691
+ *
692
+ * Emits `message_dequeued` with `reason: 'flush'` so clients transition the
693
+ * bubble from queued → sent.
694
+ *
695
+ * @returns {object|null} the dequeued item, or null when nothing to flush.
696
+ */
697
+ dequeueNextOutgoing() {
698
+ if (this._destroying || this._outgoingQueue.length === 0) return null
699
+ const item = this._outgoingQueue.shift()
700
+ const clientMessageId = typeof item.sendOptions?.clientMessageId === 'string'
701
+ ? item.sendOptions.clientMessageId
702
+ : undefined
703
+ // queueLength is captured now (post-shift) but the event + re-dispatch are
704
+ // deferred to the next tick together, so message_dequeued(flush) — which a
705
+ // client reads as "this queued message is being sent" — only fires when we
706
+ // are ACTUALLY about to send (a destroy() landing in this window suppresses
707
+ // both). Deferring also guarantees the event lands AFTER the turn's
708
+ // synchronous `result` broadcast on every turn-end path (the natural-result
709
+ // path emits `result` then drains; the abnormal paths drain via
710
+ // _emitInterruptedTurnResult then emit `result`), so a client never sees the
711
+ // dequeue ahead of the result that triggered it.
712
+ const remaining = this._outgoingQueue.length
713
+ process.nextTick(() => {
714
+ if (this._destroying) return
715
+ this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'flush' })
716
+ ;(this._log || log).info(`Dequeuing follow-up message (${remaining} remaining)`)
717
+ this.sendMessage(item.prompt, item.attachments, item.sendOptions)
718
+ })
719
+ return item
720
+ }
721
+
722
+ /**
723
+ * #5936: drop every queued outgoing message. Called by `interrupt()` so a
724
+ * deliberate Stop cancels the owner's pending follow-ups rather than letting
725
+ * them auto-fire after the turn the user just halted — the canonical interrupt
726
+ * policy for the queue (cancel, not flush; see issue #5936). Emits one
727
+ * `message_dequeued` per cleared item with `reason: 'interrupted'` so clients
728
+ * remove each queued bubble. `emit` defaults true; destroy() passes false to
729
+ * tear the queue down silently (no listeners care once the session is gone).
730
+ *
731
+ * @param {{ emit?: boolean }} [opts]
732
+ * @returns {number} how many messages were cleared.
733
+ */
734
+ clearOutgoingQueue({ emit = true } = {}) {
735
+ if (this._outgoingQueue.length === 0) return 0
736
+ const cleared = this._outgoingQueue.splice(0)
737
+ if (emit) {
738
+ // Report a DESCENDING queueLength as each item is removed (cleared.length
739
+ // - 1, - 2, … 0) so the field keeps its documented "count remaining AFTER
740
+ // this item left" meaning — matching dequeueNextOutgoing. The array is
741
+ // already spliced empty, so derive the count from the index rather than
742
+ // reading `_outgoingQueue.length` (which would report 0 for every item).
743
+ cleared.forEach((item, i) => {
744
+ const clientMessageId = typeof item.sendOptions?.clientMessageId === 'string'
745
+ ? item.sendOptions.clientMessageId
746
+ : undefined
747
+ this.emit('message_dequeued', {
748
+ clientMessageId,
749
+ queueLength: cleared.length - i - 1,
750
+ reason: 'interrupted',
751
+ })
752
+ })
753
+ ;(this._log || log).info(`Cleared ${cleared.length} queued follow-up message(s) (interrupted)`)
754
+ }
755
+ return cleared.length
756
+ }
757
+
758
+ /**
759
+ * #5943: cancel ONE queued outgoing message by its `clientMessageId`, leaving
760
+ * the rest of the queue intact. Called by the `cancel_queued` handler so the
761
+ * owner can drop a single send-while-busy follow-up they no longer want,
762
+ * WITHOUT the whole-queue cancellation an `interrupt` performs. Emits
763
+ * `message_dequeued` with `reason: 'cancelled'` (the per-item analogue of
764
+ * `clearOutgoingQueue`'s `'interrupted'`) so every client removes just that
765
+ * queued bubble. `queueLength` carries the count remaining AFTER removal,
766
+ * matching the documented meaning on the other dequeue paths.
767
+ *
768
+ * A no-op (returns false, no event) when the id is missing, empty, or matches
769
+ * nothing — an entry queued without a `clientMessageId` cannot be targeted
770
+ * (only the owner's optimistic copy carries one), and a stale/duplicate cancel
771
+ * for an already-flushed item must not emit a spurious dequeue.
772
+ *
773
+ * Authority is enforced upstream, NOT here: the `cancel_queued` handler
774
+ * resolves the caller to THIS session via the standard binding gate before
775
+ * calling in, and the queue is per-session, so reaching this method already
776
+ * means the caller owns the session. Keep that the ownership boundary if the
777
+ * queue is ever refactored to a cross-session structure.
778
+ *
779
+ * @param {string} clientMessageId
780
+ * @returns {boolean} true if an entry was found and removed.
781
+ */
782
+ cancelQueuedMessage(clientMessageId) {
783
+ if (this._destroying || typeof clientMessageId !== 'string' || clientMessageId.length === 0) {
784
+ return false
785
+ }
786
+ const idx = this._outgoingQueue.findIndex(
787
+ (item) => item.sendOptions?.clientMessageId === clientMessageId,
788
+ )
789
+ if (idx === -1) return false
790
+ this._outgoingQueue.splice(idx, 1)
791
+ const remaining = this._outgoingQueue.length
792
+ this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'cancelled' })
793
+ ;(this._log || log).info(`Cancelled queued follow-up message ${clientMessageId} (${remaining} remaining)`)
794
+ return true
795
+ }
796
+
797
+ /**
798
+ * #5160: wire the activity registry to this session's own lifecycle
799
+ * events. The registry is a pure consumer — it only maps already-emitted
800
+ * signals into `ActivityEntry` records, so listening here keeps it a thin
801
+ * unifying layer rather than a parallel tracker. Listeners are attached on
802
+ * the session itself (an EventEmitter) so every provider that routes
803
+ * through these canonical events feeds the registry for free.
804
+ *
805
+ * @private
806
+ */
807
+ _setupActivityRegistry() {
808
+ this.on('tool_start', (d) => this._activity.onToolStart(d))
809
+ this.on('tool_result', (d) => this._activity.onToolResult(d))
810
+ this.on('agent_spawned', (d) => this._activity.onAgentSpawned(d))
811
+ this.on('agent_completed', (d) => this._activity.onAgentCompleted(d))
812
+ this.on('agent_event', (d) => this._activity.onAgentEvent(d))
813
+ this.on('background_work_changed', (d) => this._activity.onBackgroundWorkChanged(d))
814
+ this.on('permission_request', (d) => this._activity.onPermissionRequest(d))
815
+ this.on('user_question', (d) => this._activity.onUserQuestion(d))
816
+ this.on('permission_resolved', (d) => this._activity.onPermissionResolved(d))
817
+ this.on('permission_expired', (d) => this._activity.onPermissionExpired(d))
818
+ }
819
+
820
+ /**
821
+ * #5160: clear the activity registry before any listener teardown. Every
822
+ * provider's `destroy()` routes through `removeAllListeners()` (directly,
823
+ * or via super.destroy() chaining — cli/jsonl/gemini/codex call it; sdk/tui
824
+ * also clear the registry explicitly via `_destroyPendingBackgroundShells`).
825
+ * Overriding here is the single chokepoint that guarantees a destroyed
826
+ * session emits `ended` deltas for any still-open node (so live subscribers
827
+ * see the tree drain) and leaves no stale entries — without having to touch
828
+ * each subclass's bespoke destroy(). Clearing BEFORE super removes the
829
+ * listeners means the `activity_delta` emits still reach the wired
830
+ * forwarder. Idempotent: a second call (or a session that already cleared
831
+ * via `_destroyPendingBackgroundShells`) sees an empty registry and no-ops.
832
+ */
833
+ removeAllListeners(eventName) {
834
+ // Only the full teardown variant (no event name) clears the registry —
835
+ // a targeted removeAllListeners('foo') must not drain the activity tree.
836
+ // Note: `super.removeAllListeners(undefined)` is NOT equivalent to the
837
+ // no-arg call — EventEmitter treats `undefined` as the event named
838
+ // `undefined` and removes nothing. So branch on arity and forward each
839
+ // shape with the right argument count.
840
+ if (eventName === undefined) {
841
+ this._activity.clear()
842
+ // #5177: stop the background-shell sweep on full teardown too. Most
843
+ // providers (cli/jsonl/gemini/codex) destroy via removeAllListeners()
844
+ // and never call _destroyPendingBackgroundShells, so this is the
845
+ // chokepoint that guarantees no provider leaks the recurring timer.
846
+ this._stopBackgroundShellSweep()
847
+ return super.removeAllListeners()
848
+ }
849
+ return super.removeAllListeners(eventName)
850
+ }
851
+
852
+ /**
853
+ * #5160: keep the activity registry's session id in sync. Subclasses that
854
+ * learn their canonical session id late (SDK sessions, on `init`) call this
855
+ * so emitted `activity_*` messages carry the right id.
856
+ * @param {string} sessionId
857
+ */
858
+ setActivitySessionId(sessionId) {
859
+ this._activity.setSessionId(sessionId)
860
+ }
861
+
862
+ /**
863
+ * #5160: full current activity tree as an `activity_snapshot` message.
864
+ * Served to a fresh subscriber (snapshot-on-subscribe) and on resync.
865
+ * @returns {object} the `activity_snapshot` wire message
866
+ */
867
+ getActivitySnapshot() {
868
+ return this._activity.getSnapshotMessage()
869
+ }
870
+
871
+ /**
872
+ * #5269 (Control Room Phase 2a): cancel a single in-flight activity node by
873
+ * its `activityId` (an `activity_snapshot`/`activity_delta` entry id).
874
+ *
875
+ * Default (base) behavior: not supported. Only providers that expose a
876
+ * per-task control surface override this — today that is the Agent-SDK path
877
+ * (`SdkSession`, which maps an `agent` node to the SDK's `query.stopTask`).
878
+ * Background shells and individual tool calls are NOT individually
879
+ * cancellable (chroxy does not own the OS process; see activity-registry.js),
880
+ * and CLI/TUI providers have no per-subagent control surface — they fall
881
+ * through to this default. Whole-turn interruption stays on the existing
882
+ * `interrupt()` path, unchanged.
883
+ *
884
+ * @param {string} _activityId
885
+ * @returns {Promise<{ ok: boolean, reason?: string, error?: string }>}
886
+ */
887
+ async cancelActivity(_activityId) {
888
+ return { ok: false, reason: 'not-supported' }
889
+ }
890
+
891
+ /**
892
+ * #5376: the following are thin delegators to BackgroundShellTracker. They
893
+ * stay on BaseSession because `background-shells.test.js` drives them as
894
+ * session methods (and `removeAllListeners` stops the sweep via
895
+ * `_stopBackgroundShellSweep`). The sweep / quiescence logic and the
896
+ * test-injected tunables (`_backgroundShell*` get/set shims below) live on the
897
+ * tracker — see background-shell-tracker.js for the #5177/#5247/#5265 rationale.
898
+ * @private
899
+ */
900
+ _emitBackgroundWorkChanged() {
901
+ return this._backgroundShellTracker._emitBackgroundWorkChanged()
902
+ }
903
+
904
+ /** @private #5376: delegates to BackgroundShellTracker. */
905
+ _ensureBackgroundShellSweep() {
906
+ return this._backgroundShellTracker._ensureBackgroundShellSweep()
907
+ }
908
+
909
+ /** @private #5376: delegates to BackgroundShellTracker. */
910
+ _stopBackgroundShellSweep() {
911
+ return this._backgroundShellTracker._stopBackgroundShellSweep()
912
+ }
913
+
914
+ /** @private #5376: delegates to BackgroundShellTracker. */
915
+ _sweepQuiescedBackgroundShells() {
916
+ return this._backgroundShellTracker._sweepQuiescedBackgroundShells()
917
+ }
918
+
919
+ /** @private #5376: delegates to BackgroundShellTracker. */
920
+ _isBackgroundShellHardQuiesced(entry) {
921
+ return this._backgroundShellTracker._isBackgroundShellHardQuiesced(entry)
922
+ }
923
+
924
+ /** @private #5376: delegates to BackgroundShellTracker. */
925
+ _isBackgroundShellQuiesced(entry) {
926
+ return this._backgroundShellTracker._isBackgroundShellQuiesced(entry)
927
+ }
928
+
929
+ /**
930
+ * #4307: clear the pending map on session destroy. Pulled into a
931
+ * helper so subclasses can call it from their own `destroy()` after
932
+ * the existing teardown — keeping the map alive past destroy would
933
+ * leak memory and confuse late session-list snapshots.
934
+ *
935
+ * @private
936
+ */
937
+ _destroyPendingBackgroundShells() {
938
+ // #5376: the tracker stops its sweep and clears the pending map (#5177 — so
939
+ // no tick fires against a half-torn-down session). The session-level
940
+ // companions are torn down here:
941
+ this._backgroundShellTracker.destroy()
942
+ this._pendingBackgroundCommands.clear()
943
+ // #5160: tear down the activity registry alongside the other transient
944
+ // per-session work maps. Ends every remaining node (the session is gone,
945
+ // so nothing is still in flight) and empties the registry — no leak, and
946
+ // a late session-list snapshot can't surface a destroyed session's tree.
947
+ this._activity.clear()
948
+ }
949
+
950
+ // ───────────────────────────────────────────────────────────────────────
951
+ // #5376: compat accessors. The skills + background-shell state moved into
952
+ // SkillsManager / BackgroundShellTracker, but existing consumers (the prompt
953
+ // builders, settings-handlers, the #5367 opt sentinel) and the unchanged
954
+ // background-shells.test.js / base-session.test.js suites read (and a couple
955
+ // write) these as session fields. Each reads through to the collaborator's
956
+ // identically-named field so there is a single source of truth — the
957
+ // collaborator. Setters exist only where a test assigns: `_skillsText`
958
+ // (base-session.test.js prompt-builder cases) and `_providerSkillAllowlist`
959
+ // (settings-handlers.test.js allowlist override). Mutating-collection reads
960
+ // (`_pendingBackgroundShells`, `_activeManualSkills`) return the live
961
+ // reference, so `.set`/`.add`/`.delete` operate on the collaborator's state.
962
+ // ───────────────────────────────────────────────────────────────────────
963
+
964
+ // Background-shell tracker
965
+ get _pendingBackgroundShells() { return this._backgroundShellTracker._pendingBackgroundShells }
966
+ get _backgroundShellSweepTimer() { return this._backgroundShellTracker._backgroundShellSweepTimer }
967
+ set _backgroundShellSweepTimer(v) { this._backgroundShellTracker._backgroundShellSweepTimer = v }
968
+ get _backgroundShellSweepMs() { return this._backgroundShellTracker._backgroundShellSweepMs }
969
+ set _backgroundShellSweepMs(v) { this._backgroundShellTracker._backgroundShellSweepMs = v }
970
+ get _backgroundShellQuiesceMs() { return this._backgroundShellTracker._backgroundShellQuiesceMs }
971
+ set _backgroundShellQuiesceMs(v) { this._backgroundShellTracker._backgroundShellQuiesceMs = v }
972
+ get _backgroundShellQuiesceCheck() { return this._backgroundShellTracker._backgroundShellQuiesceCheck }
973
+ set _backgroundShellQuiesceCheck(v) { this._backgroundShellTracker._backgroundShellQuiesceCheck = v }
974
+ get _backgroundShellHardQuiesceMs() { return this._backgroundShellTracker._backgroundShellHardQuiesceMs }
975
+ set _backgroundShellHardQuiesceMs(v) { this._backgroundShellTracker._backgroundShellHardQuiesceMs = v }
976
+ get _backgroundShellHardQuiesceCheck() { return this._backgroundShellTracker._backgroundShellHardQuiesceCheck }
977
+ set _backgroundShellHardQuiesceCheck(v) { this._backgroundShellTracker._backgroundShellHardQuiesceCheck = v }
978
+
979
+ // Skills manager
980
+ get _skills() { return this._skillsManager._skills }
981
+ get _skillsByMode() { return this._skillsManager._skillsByMode }
982
+ get _skillsText() { return this._skillsManager._skillsText }
983
+ set _skillsText(v) { this._skillsManager._skillsText = v }
984
+ get _prependSkillsText() { return this._skillsManager._prependSkillsText }
985
+ get _activeManualSkills() { return this._skillsManager._activeManualSkills }
986
+ get _manualSkillNames() { return this._skillsManager._manualSkillNames }
987
+ get _skillsDir() { return this._skillsManager._skillsDir }
988
+ get _repoSkillsDir() { return this._skillsManager._repoSkillsDir }
989
+ get _trustStore() { return this._skillsManager._trustStore }
990
+ get _skillsParseCache() { return this._skillsManager._skillsParseCache }
991
+ get _maxSkillBytes() { return this._skillsManager._maxSkillBytes }
992
+ get _maxTotalSkillBytes() { return this._skillsManager._maxTotalSkillBytes }
993
+ get _providerSkillAllowlist() { return this._skillsManager._providerSkillAllowlist }
994
+ set _providerSkillAllowlist(v) { this._skillsManager._providerSkillAllowlist = v }
995
+
996
+ /** Current thinking level. Override in subclasses that support it. */
997
+ get thinkingLevel() { return undefined }
998
+
999
+ get isReady() {
1000
+ return this._processReady && !this._isBusy
1001
+ }
1002
+
1003
+ /**
1004
+ * #5375: arm the user-initiated-stop flag. Called by each provider's
1005
+ * interrupt() so the subsequent process close/error is treated as a clean
1006
+ * stop rather than a crash.
1007
+ */
1008
+ markIntentionalStop() {
1009
+ this._intentionalStop = true
1010
+ }
1011
+
1012
+ /**
1013
+ * #5375: capture-and-clear the user-initiated-stop flag in one step. The
1014
+ * provider's close/error handler calls this at the top to decide the
1015
+ * stopped-vs-error branch, disarming the flag so the next natural exit is
1016
+ * not misread. Returns whether the flag was armed.
1017
+ */
1018
+ _consumeIntentionalStop() {
1019
+ const was = this._intentionalStop
1020
+ this._intentionalStop = false
1021
+ return was
1022
+ }
1023
+
1024
+ /**
1025
+ * #5375: plain disarm, for destroy()/finally safety-nets where we only need
1026
+ * to clear the flag without reading it. Kept separate from
1027
+ * _consumeIntentionalStop so SDK's catch-then-finally clear (the
1028
+ * interrupt-races-result race, #4881) stays a two-step sequence.
1029
+ */
1030
+ _clearIntentionalStop() {
1031
+ this._intentionalStop = false
1032
+ }
1033
+
1034
+ /**
1035
+ * Change the model. Centralizes the busy/no-op guard + resolve; subclasses
1036
+ * that need a provider-specific reaction (CliSession respawn, SdkSession log)
1037
+ * override the `_onModelChanged` hook instead of the whole setter (#5374).
1038
+ * Returns true if the model actually changed.
1039
+ */
1040
+ setModel(model) {
1041
+ if (this._isBusy) {
1042
+ return false
1043
+ }
1044
+ const newModel = model ? resolveModelId(model) : null
1045
+ if (newModel === this.model) {
1046
+ return false
1047
+ }
1048
+ this.model = newModel
1049
+ this._onModelChanged(this.model)
1050
+ return true
1051
+ }
1052
+
1053
+ /**
1054
+ * #5374: protected hook fired by setModel() AFTER the busy/no-op guard +
1055
+ * alias resolution (resolveModelId) and the field update, only when the model
1056
+ * actually changed. Default no-op; subclasses override with their
1057
+ * provider-specific action (and their own logging).
1058
+ */
1059
+ _onModelChanged(_model) {}
1060
+
1061
+ /**
1062
+ * Change the permission mode. Centralizes validation + the busy/no-op guard;
1063
+ * subclasses override the `_onPermissionModeChanged` hook for their
1064
+ * provider-specific action (CliSession respawn, SdkSession drain, TUI sidecar
1065
+ * write) instead of the whole setter (#5374).
1066
+ * Returns true if the mode actually changed.
1067
+ */
1068
+ setPermissionMode(mode) {
1069
+ if (!ALLOWED_PERMISSION_MODE_IDS.has(mode)) {
1070
+ return false
1071
+ }
1072
+ // 'auto' is the panic-button: a user mid-turn (i.e. _isBusy=true)
1073
+ // staring at a permission prompt should be able to flip to bypass and
1074
+ // have it actually take effect. The non-auto modes still defer until
1075
+ // the turn completes — flipping to 'plan' or 'acceptEdits' mid-turn
1076
+ // would change semantics partway through and is intentionally rejected.
1077
+ if (this._isBusy && mode !== 'auto') {
1078
+ return false
1079
+ }
1080
+ if (mode === this.permissionMode) {
1081
+ return false
1082
+ }
1083
+ this.permissionMode = mode
1084
+ this._onPermissionModeChanged(mode)
1085
+ return true
1086
+ }
1087
+
1088
+ /**
1089
+ * #5374: protected hook fired by setPermissionMode() AFTER validation + the
1090
+ * field is set, only when the mode actually changed. Default no-op;
1091
+ * subclasses override with their provider-specific action (and their own
1092
+ * logging). JsonlSubprocessSession deliberately overrides the whole setter
1093
+ * to a no-op (it suppresses the field update too), so it does not use this.
1094
+ */
1095
+ _onPermissionModeChanged(_mode) {}
1096
+
1097
+ /**
1098
+ * Toggle the per-session promptEvaluator flag (#3185). Returns `true`
1099
+ * when the value changes (so callers can decide whether to broadcast a
1100
+ * `prompt_evaluator_changed` event and persist state) and `false` when
1101
+ * the input is invalid OR the value is unchanged. Strict-boolean only —
1102
+ * a non-boolean input is rejected without mutating state, defending
1103
+ * against malformed WS payloads.
1104
+ *
1105
+ * Unlike `setPermissionMode`, this is safe to flip while the session is
1106
+ * busy: the flag is only read at the start of the next prompt, so a
1107
+ * mid-turn change has no in-flight side effects.
1108
+ *
1109
+ * @param {boolean} value
1110
+ * @returns {boolean}
1111
+ */
1112
+ setPromptEvaluator(value) {
1113
+ if (typeof value !== 'boolean') {
1114
+ return false
1115
+ }
1116
+ if (value === this.promptEvaluator) {
1117
+ return false
1118
+ }
1119
+ this.promptEvaluator = value
1120
+ return true
1121
+ }
1122
+
1123
+ /**
1124
+ * Toggle the per-session Chroxy context hint (#3805). Mirrors the
1125
+ * `setPromptEvaluator` contract: strict-boolean validation, idempotent
1126
+ * (returns `false` on a no-op set), and safe to flip mid-turn because
1127
+ * the flag is only consulted at the start of the next prompt assembly
1128
+ * via `_buildSystemPrompt()`.
1129
+ *
1130
+ * Default is OFF — when enabled, the Chroxy context paragraph is
1131
+ * prepended to the system prompt so the model can adjust output for
1132
+ * the mobile-screen client (narrower code blocks, no wide ASCII
1133
+ * diagrams). Off by default because some users explicitly want the
1134
+ * full desktop response style.
1135
+ *
1136
+ * @param {boolean} value
1137
+ * @returns {boolean}
1138
+ */
1139
+ setChroxyContextHint(value) {
1140
+ if (typeof value !== 'boolean') {
1141
+ return false
1142
+ }
1143
+ if (value === this.chroxyContextHint) {
1144
+ return false
1145
+ }
1146
+ this.chroxyContextHint = value
1147
+ return true
1148
+ }
1149
+
1150
+ /**
1151
+ * Set the per-session preamble (#4660). Accepts a string (trimmed and
1152
+ * capped to SESSION_PREAMBLE_MAX_LENGTH) or empty string (clears).
1153
+ * Returns `true` when the stored value changes, `false` for either
1154
+ * invalid input (non-string) or an idempotent no-op — same contract as
1155
+ * `setChroxyContextHint`.
1156
+ *
1157
+ * Safe to call mid-turn: the preamble is only consulted at the start
1158
+ * of the next prompt assembly via `_buildSystemPrompt()`.
1159
+ *
1160
+ * @param {string} value
1161
+ * @returns {boolean}
1162
+ */
1163
+ setSessionPreamble(value) {
1164
+ if (typeof value !== 'string') {
1165
+ return false
1166
+ }
1167
+ const next = _coerceSessionPreambleOpt(value)
1168
+ if (next === this.sessionPreamble) {
1169
+ return false
1170
+ }
1171
+ this.sessionPreamble = next
1172
+ return true
1173
+ }
1174
+
1175
+ /**
1176
+ * Set the per-session promptEvaluatorSkipPattern (#3639). Accepts a
1177
+ * regex source string (validated by attempting to compile it), null,
1178
+ * or empty string (both clear the override). Returns `true` when the
1179
+ * stored value changes and `false` for either invalid input or a
1180
+ * redundant set — same idempotent contract as `setPromptEvaluator`.
1181
+ *
1182
+ * The compiled regex itself isn't stored: `shouldSkipEvaluator` owns
1183
+ * the compile cache (LRU keyed by source string) so a stale per-session
1184
+ * pattern won't pin a closure here. The validation done here is
1185
+ * defence-in-depth — `shouldSkipEvaluator` also try/catches its own
1186
+ * compile, so a session that somehow ends up with a bad source still
1187
+ * fails-open to default-only skip rules.
1188
+ *
1189
+ * Safe to call mid-turn: the pattern is read at the start of the next
1190
+ * `user_input` handler invocation only.
1191
+ *
1192
+ * @param {string|null} value
1193
+ * @returns {boolean}
1194
+ */
1195
+ setPromptEvaluatorSkipPattern(value) {
1196
+ let next
1197
+ if (value === null || value === '') {
1198
+ next = null
1199
+ } else if (typeof value === 'string') {
1200
+ try {
1201
+ new RegExp(value, 'i')
1202
+ } catch {
1203
+ return false
1204
+ }
1205
+ next = value
1206
+ } else {
1207
+ return false
1208
+ }
1209
+ if (next === this.promptEvaluatorSkipPattern) {
1210
+ return false
1211
+ }
1212
+ this.promptEvaluatorSkipPattern = next
1213
+ return true
1214
+ }
1215
+
1216
+ /**
1217
+ * Clear per-message state. Subclasses should call super._clearMessageState()
1218
+ * and then clear their own additional state (plan mode, pending permissions, etc.).
1219
+ */
1220
+ /**
1221
+ * Parse a JSONL line from a subprocess stdout.
1222
+ * Returns the parsed object or null if the line is empty or invalid JSON.
1223
+ * @param {string} line
1224
+ * @returns {object|null}
1225
+ */
1226
+ _parseJsonLine(line) {
1227
+ if (!line || !line.trim()) return null
1228
+ try {
1229
+ return JSON.parse(line)
1230
+ } catch {
1231
+ return null
1232
+ }
1233
+ }
1234
+
1235
+ /**
1236
+ * Shared skills system MVP (#2957).
1237
+ *
1238
+ * Returns the list of active skills discovered at construction. Providers
1239
+ * that want a summary for `list_skills` can use this; providers that want
1240
+ * the injection-ready text should use `_buildSystemPrompt()`.
1241
+ *
1242
+ * @returns {Array<{ name: string, body: string, description: string }>}
1243
+ */
1244
+ _getSkills() {
1245
+ return Array.isArray(this._skills) ? this._skills : []
1246
+ }
1247
+
1248
+ /**
1249
+ * Return the set of currently-active manual-skill names (#3209).
1250
+ * The dashboard reads this to know which checkboxes to render
1251
+ * checked. Callers MUST treat the return as read-only — mutate via
1252
+ * `activateSkill()` / `deactivateSkill()` so the loader rebuild
1253
+ * fires.
1254
+ *
1255
+ * @returns {string[]}
1256
+ */
1257
+ getActiveManualSkills() {
1258
+ return Array.from(this._activeManualSkills)
1259
+ }
1260
+
1261
+ /**
1262
+ * Return the raw active-manual-skills Set (#3252).
1263
+ *
1264
+ * Same data as `getActiveManualSkills()` but as the underlying Set
1265
+ * so callers can do cheap `.has(name)` membership checks without
1266
+ * rebuilding from the array form. The returned Set is the same
1267
+ * instance held by this session — callers MUST treat it as
1268
+ * read-only and mutate via `activateSkill()` / `deactivateSkill()`
1269
+ * so the loader rebuild fires.
1270
+ *
1271
+ * @returns {Set<string>}
1272
+ */
1273
+ getActiveManualSkillsRaw() {
1274
+ return this._activeManualSkills
1275
+ }
1276
+
1277
+ /**
1278
+ * Return the wired SkillsTrustStore, or null when trust is disabled
1279
+ * (#3252).
1280
+ *
1281
+ * Trust is opt-in: the operator sets `trustMismatchMode` to 'warn'
1282
+ * or 'block' to record per-skill content hashes and surface
1283
+ * mismatch warnings. Without that opt-in, the field is null and
1284
+ * the dashboard renders the panel without hash / last-verified
1285
+ * columns rather than showing fake data.
1286
+ *
1287
+ * @returns {import('./skills-trust.js').SkillsTrustStore | null}
1288
+ */
1289
+ getTrustStore() {
1290
+ return this._trustStore
1291
+ }
1292
+
1293
+ /**
1294
+ * Return the formatted skills text for injection into the provider's
1295
+ * system prompt (Claude SDK `systemPrompt.append`, CLI
1296
+ * `--append-system-prompt`). Returns an empty string when no skills are
1297
+ * active.
1298
+ *
1299
+ * Per-skill injection mode (#3200): this returns ONLY skills whose
1300
+ * resolved `injectionMode` is `append` / `system`. Skills that asked
1301
+ * for `prepend` are returned by `_buildPrependPrompt()` instead. On
1302
+ * Claude (which has both channels available), the system-prompt path
1303
+ * is the existing v1 default; on Codex / Gemini there is no system
1304
+ * prompt so this returns '' for any skill that explicitly asked for
1305
+ * `injection: append` — those callers should fall back through
1306
+ * `_buildPrependPrompt()`.
1307
+ *
1308
+ * @returns {string}
1309
+ */
1310
+ _buildSystemPrompt() {
1311
+ const skillsText = typeof this._skillsText === 'string' ? this._skillsText : ''
1312
+ // Order (#4660 + #3805): user preamble → chroxy hint → skills text.
1313
+ // The user-authored preamble rides at the FRONT so it takes precedence
1314
+ // over the canned chroxy hint and the skills bucket — those are
1315
+ // chroxy-controlled context, the preamble is the user's voice.
1316
+ //
1317
+ // When BOTH the preamble is empty AND the chroxy hint is OFF, the
1318
+ // return value is byte-identical to pre-#3805 (skillsText only) so
1319
+ // existing users see no observable behaviour change. Each layer is
1320
+ // joined by `\n\n` so the model sees clean paragraph breaks.
1321
+ const parts = []
1322
+ if (this.sessionPreamble) parts.push(this.sessionPreamble)
1323
+ if (this.chroxyContextHint) parts.push(CHROXY_CONTEXT_HINT_TEXT)
1324
+ if (skillsText) parts.push(skillsText)
1325
+ return parts.length === 0 ? '' : parts.join('\n\n')
1326
+ }
1327
+
1328
+ /**
1329
+ * Return the formatted skills text for prepending to the first user
1330
+ * message (Codex, Gemini default; any provider when a skill declares
1331
+ * `injection: prepend`). Returns an empty string when no skills are
1332
+ * active for this channel.
1333
+ *
1334
+ * Subprocess providers that have no system-prompt channel should
1335
+ * concatenate `_buildSystemPrompt()` + `_buildPrependPrompt()` so a
1336
+ * Claude-targeted skill that nonetheless ended up loaded for a Codex
1337
+ * session still injects (rare — `providers:` filtering normally
1338
+ * prevents this — but defensive against typos in frontmatter).
1339
+ *
1340
+ * @returns {string}
1341
+ */
1342
+ _buildPrependPrompt() {
1343
+ return typeof this._prependSkillsText === 'string' ? this._prependSkillsText : ''
1344
+ }
1345
+
1346
+ /**
1347
+ * Return a single skills payload that concatenates BOTH the prepend bucket
1348
+ * and the append/system bucket with the `# User skills` header rendered
1349
+ * exactly once at the top (#3228). Used by subprocess providers (Codex,
1350
+ * Gemini) that have no system-prompt channel and must inline every loaded
1351
+ * skill into the first user message.
1352
+ *
1353
+ * Why this exists: `_buildSystemPrompt()` and `_buildPrependPrompt()` each
1354
+ * carry their own `# User skills` header so they're complete payloads when
1355
+ * routed to their natural channel. Concatenating their string outputs
1356
+ * directly produced two headers in the final user-message prefix — caught
1357
+ * in PR #3224 review. Building from the two skill lists with a single
1358
+ * call to `formatSkillsForPrompt({ includeHeader: false })` per bucket
1359
+ * sidesteps that.
1360
+ *
1361
+ * Returns an empty string when both buckets are empty so the caller can
1362
+ * branch on truthiness without null-checking.
1363
+ *
1364
+ * @returns {string}
1365
+ */
1366
+ _buildCombinedSkillsPrefix() {
1367
+ const prependList = this._skillsByMode && Array.isArray(this._skillsByMode.prepend)
1368
+ ? this._skillsByMode.prepend
1369
+ : []
1370
+ const appendList = this._skillsByMode && Array.isArray(this._skillsByMode.append)
1371
+ ? this._skillsByMode.append
1372
+ : []
1373
+
1374
+ if (prependList.length === 0 && appendList.length === 0) return ''
1375
+
1376
+ const parts = []
1377
+ const prependText = formatSkillsForPrompt(prependList, { includeHeader: false })
1378
+ if (prependText) parts.push(prependText)
1379
+ const appendText = formatSkillsForPrompt(appendList, { includeHeader: false })
1380
+ if (appendText) parts.push(appendText)
1381
+ if (parts.length === 0) return ''
1382
+
1383
+ return `${SKILLS_PROMPT_HEADER}${parts.join('\n\n---\n\n')}`
1384
+ }
1385
+
1386
+ /**
1387
+ * #4628: track that a tool_start event was emitted. Pair with
1388
+ * `_trackToolResult(toolUseId)` once the matching tool_result fires.
1389
+ * Idempotent on duplicate ids (overwrites tool/startedAt). Safe to
1390
+ * call before/after the actual emit — the tracking is decoupled.
1391
+ */
1392
+ _trackToolStart(toolUseId, tool) {
1393
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) return
1394
+ this._inFlightToolStarts.set(toolUseId, {
1395
+ tool: typeof tool === 'string' && tool.length > 0 ? tool : 'unknown',
1396
+ startedAt: Date.now(),
1397
+ })
1398
+ }
1399
+
1400
+ /**
1401
+ * #4628: mark a tool_start resolved (matching tool_result fired).
1402
+ * Idempotent — calling for an unknown id is a no-op.
1403
+ */
1404
+ _trackToolResult(toolUseId) {
1405
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) return
1406
+ this._inFlightToolStarts.delete(toolUseId)
1407
+ }
1408
+
1409
+ /**
1410
+ * #4628: sweep any tool_starts that never got their matching
1411
+ * tool_result and emit synthetic tool_result events for each.
1412
+ * Companion to SessionMessageHistory.sweepUnresolvedToolStarts (#4619)
1413
+ * — that one runs at restore-time on persisted history; this one runs
1414
+ * at turn-end on live in-memory tracking so the orphan never gets
1415
+ * persisted in the first place.
1416
+ *
1417
+ * The synthetic tool_result carries the same shape as a real one (the
1418
+ * dashboard's `handleToolResult.applyToActiveTools` only matches on
1419
+ * `toolUseId`). Extra fields (`synthetic`, `interrupted`, `reason`)
1420
+ * are diagnostic hints — the wire schema strips them on parse but
1421
+ * they stay grep-able on disk in the persisted history.
1422
+ *
1423
+ * @param {string} reason — short identifier for the sweep cause
1424
+ * @returns {number} count of sweeps emitted
1425
+ */
1426
+ _sweepUnresolvedToolStarts(reason = 'stream_completed_without_result') {
1427
+ if (this._inFlightToolStarts.size === 0) return 0
1428
+ const count = this._inFlightToolStarts.size
1429
+ for (const [toolUseId, entry] of this._inFlightToolStarts) {
1430
+ this.emit('tool_result', {
1431
+ toolUseId,
1432
+ result: `Tool ${entry.tool} did not emit a result before the turn ended (reason: ${reason}). Chroxy synthesized this result to clear the stale activeTools entry.`,
1433
+ truncated: false,
1434
+ synthetic: true,
1435
+ interrupted: true,
1436
+ isError: true,
1437
+ reason,
1438
+ })
1439
+ }
1440
+ this._inFlightToolStarts.clear()
1441
+ return count
1442
+ }
1443
+
1444
+ /**
1445
+ * #4628: emit `result` after sweeping any in-flight tool_starts. All
1446
+ * provider sessions should route through this rather than calling
1447
+ * `this.emit('result', ...)` directly, so orphan tool_starts get
1448
+ * paired with a synthetic tool_result BEFORE the result fires (and
1449
+ * BEFORE state is persisted, since session-message-history listens
1450
+ * for both events).
1451
+ *
1452
+ * @param {object} payload — the result event payload ({cost, duration, usage, sessionId})
1453
+ * @param {string} [sweepReason] — optional override for the sweep reason
1454
+ */
1455
+ _emitResult(payload, sweepReason = 'stream_completed_without_result') {
1456
+ this._sweepUnresolvedToolStarts(sweepReason)
1457
+ this.emit('result', payload)
1458
+ }
1459
+
1460
+ _clearMessageState() {
1461
+ this._isBusy = false
1462
+ this._currentMessageId = null
1463
+
1464
+ // #4307: clear the ephemeral tool_use→command lookup. NOT the
1465
+ // pending-shells map — those entries survive turn-end intentionally
1466
+ // (the whole point of #4307: a session waiting on background work
1467
+ // is distinct from an idle session). The commands map is only used
1468
+ // to recover the command text for the next tool_result of the SAME
1469
+ // turn — once the turn ends, any unmatched entries are stranded
1470
+ // and a fresh tool_use would re-populate.
1471
+ this._pendingBackgroundCommands.clear()
1472
+ // #4628: sweep any orphan tool_starts that didn't get their
1473
+ // matching tool_result this turn. Most providers route through
1474
+ // _emitResult which sweeps before broadcasting result; this is the
1475
+ // belt-and-braces for paths that call _clearMessageState directly
1476
+ // (e.g. SDK stream-stall recovery clears state BEFORE emitting the
1477
+ // synthetic result). Sweeping here ensures the orphan is paired
1478
+ // with a synthetic tool_result rather than silently dropped — so
1479
+ // the dashboard's activeTools clears whether result fires next or
1480
+ // never fires at all.
1481
+ this._sweepUnresolvedToolStarts('message_state_cleared')
1482
+
1483
+ // Emit completions for any tracked agents so the app clears badges
1484
+ if (this._activeAgents.size > 0) {
1485
+ for (const agent of this._activeAgents.values()) {
1486
+ this.emit('agent_completed', { toolUseId: agent.toolUseId })
1487
+ }
1488
+ this._activeAgents.clear()
1489
+ }
1490
+
1491
+ // #5160: turn-end reconciliation for the activity registry. Ends any
1492
+ // tool/agent/blocked node still marked running/blocked (orphans the
1493
+ // model abandoned at turn end), mirroring _sweepUnresolvedToolStarts.
1494
+ // Runs AFTER the agent_completed fan-out above so those completions
1495
+ // terminate their nodes first; reset() is the belt-and-braces sweep for
1496
+ // anything the canonical signals didn't clear. Shell nodes survive
1497
+ // turn-end (#4307) and clear via background_work_changed.
1498
+ this._activity.reset()
1499
+
1500
+ if (this._resultTimeout) {
1501
+ clearTimeout(this._resultTimeout)
1502
+ this._resultTimeout = null
1503
+ }
1504
+ // #3899: clear the hard-cap timer too. A successful turn end (or
1505
+ // explicit cancellation) means there's nothing to backstop anymore;
1506
+ // leaving the hard timer armed would fire `_handleHardTimeout` on
1507
+ // a session that's already idle, which is harmless but noisy.
1508
+ if (this._hardTimeout) {
1509
+ clearTimeout(this._hardTimeout)
1510
+ this._hardTimeout = null
1511
+ }
1512
+ // #4467: clear the stream-stall recovery timer too.
1513
+ if (this._streamStallTimeout) {
1514
+ clearTimeout(this._streamStallTimeout)
1515
+ this._streamStallTimeout = null
1516
+ }
1517
+ }
1518
+ }