@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Build an unambiguous Map key from several string parts (#7103).
3
+ *
4
+ * Two aggregates key their in-memory Maps on `(source, sessionId)`
5
+ * ({@link TurnTracker}, {@link ExternalSessionRegistry}). Both used to flatten
6
+ * the pair with a single separator, and both wrote that separator as a LITERAL
7
+ * NUL byte in the source file. That was wrong twice over:
8
+ *
9
+ * 1. **Search visibility.** A raw NUL makes the whole file invisible to any
10
+ * code search that passes grep's `-I` or otherwise sniffs for NUL — and
11
+ * it fails SILENTLY, returning an empty result indistinguishable from
12
+ * "the string isn't there". `scripts/lint-no-nul-bytes.sh` now guards it.
13
+ *
14
+ * 2. **Aliasing.** `a + SEP + b` is only injective while no part can contain
15
+ * SEP. That held for these two callers by accident — `IngestEventSchema`
16
+ * charset-restricts `source` to `[a-zA-Z0-9._-]` — but it is a
17
+ * CALLER-side invariant neither aggregate can enforce, and `sessionId` is
18
+ * NOT charset-restricted. Under a bare separator, `('a<SEP>b', 'c')` and
19
+ * `('a', 'b<SEP>c')` collapse onto one entry: one session's stop clears
20
+ * another's turn, and one `session_end` evicts the wrong registry row.
21
+ *
22
+ * The encoding is length-prefixed — `<len>:<part>` per part, joined with `|`:
23
+ *
24
+ * compositeKey('claude-hooks', 'abc') -> '12:claude-hooks|3:abc'
25
+ *
26
+ * Decoding is deterministic (read the digit run, take exactly that many chars,
27
+ * expect `|` or end-of-string), so the encoding is injective for ANY part
28
+ * contents — including parts that contain `:`, `|`, digits, or a NUL. The
29
+ * delimiters are plain ASCII, so the key is also readable in a log line or a
30
+ * debugger, which a control-character separator never was.
31
+ *
32
+ * Keys are in-memory only and never persisted or sent on the wire, so the
33
+ * format is free to change; nothing decodes it today.
34
+ *
35
+ * @param {...unknown} parts - Key components, coerced to string.
36
+ * @returns {string} Collision-free key for the ordered part list.
37
+ */
38
+ export function compositeKey(...parts) {
39
+ return parts
40
+ .map((part) => {
41
+ const s = String(part)
42
+ return `${s.length}:${s}`
43
+ })
44
+ .join('|')
45
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The ONE copy of the parsing rules for the files the dashboard's update banner
3
+ * exchanges with the idle-only auto-deploy script (#8331), imported by both
4
+ * `daemon-update-status.js` (the daemon) and `scripts/deploy-daemon.mjs`. What counts
5
+ * as a valid request or postpone, how old a request may be, and what a timestamp may
6
+ * look like are decided here and nowhere else, so the two sides cannot drift.
7
+ *
8
+ * Next to `small-file.js`, which decides how the files are READ and WRITTEN; this
9
+ * module decides what a parsed value MEANS.
10
+ */
11
+
12
+ const SHA = /^[0-9a-f]{40}$/i
13
+ const NONCE = /^[A-Za-z0-9._-]{1,64}$/
14
+
15
+ /** A request older than this is ignored: a click from an hour ago must not restart the daemon now. At least twice the 600 s launchd StartInterval, so one missed tick does not lose a click. */
16
+ export const REQUEST_TTL_MS = 20 * 60 * 1000
17
+ /** How far in the future a `requestedAt` may be (clock skew between the writer and the reader). */
18
+ export const REQUEST_SKEW_MS = 5 * 60 * 1000
19
+ /**
20
+ * How long an `applying` marker (written by the script when a forward deploy starts
21
+ * building) is believed. The build timeout is 20 minutes, so 30 covers it plus slack;
22
+ * past that the marker is the leftover of a crashed tick, not live work.
23
+ */
24
+ export const APPLYING_MAX_MS = 30 * 60 * 1000
25
+ /** What the daemon's Postpone writes. */
26
+ export const POSTPONE_MS = 60 * 60 * 1000
27
+ /** A postpone is honoured only for at most this long from its own `requestedAt`: the hour, plus a minute of slack. */
28
+ export const POSTPONE_MAX_MS = POSTPONE_MS + 60 * 1000
29
+
30
+ export const isSha = (v) => typeof v === 'string' && SHA.test(v)
31
+
32
+ /**
33
+ * A timestamp both sides can safely use: a string that parses, with a year in
34
+ * 1970..9999. A year outside that range would make `toISOString()` emit the
35
+ * extended `+275760-…` form, which the wire schema's `datetime()` rejects and
36
+ * which would then fail a client's whole-frame parse.
37
+ */
38
+ export function isIso(v) {
39
+ if (typeof v !== 'string' || v.length > 40) return false
40
+ const t = Date.parse(v)
41
+ if (!Number.isFinite(t)) return false
42
+ const year = new Date(t).getUTCFullYear()
43
+ return year >= 1970 && year <= 9999
44
+ }
45
+
46
+ /** Canonical UTC ISO for a timestamp `isIso` accepted. */
47
+ export const canonIso = (v) => new Date(Date.parse(v)).toISOString()
48
+
49
+ /** -> a valid restart request, or null. The server writes exactly this shape. */
50
+ export function parseRequest(v) {
51
+ if (!v || typeof v !== 'object' || v.action !== 'restart-now') return null
52
+ if (!isSha(v.target)) return null
53
+ if (typeof v.force !== 'boolean') return null
54
+ if (!isIso(v.requestedAt)) return null
55
+ if (typeof v.nonce !== 'string' || !NONCE.test(v.nonce)) return null
56
+ return { target: v.target.toLowerCase(), force: v.force, requestedAt: canonIso(v.requestedAt), nonce: v.nonce }
57
+ }
58
+
59
+ /** A request is fresh while it is no older than the TTL and not meaningfully from the future. */
60
+ export function isRequestFresh(req, nowMs) {
61
+ const age = nowMs - Date.parse(req.requestedAt)
62
+ return age <= REQUEST_TTL_MS && age >= -60 * 1000
63
+ }
64
+
65
+ /**
66
+ * -> `{ target, until }` for a postpone that is well-formed AND internally sane, else
67
+ * null. It needs a valid `requestedAt` that is not more than REQUEST_SKEW_MS in the
68
+ * future, and a hold of at most POSTPONE_MAX_MS from that timestamp, so a hand-written
69
+ * far-future deadline is not a postpone.
70
+ */
71
+ export function parsePostpone(v, nowMs) {
72
+ if (!v || typeof v !== 'object' || !isSha(v.target) || !isIso(v.until) || !isIso(v.requestedAt)) return null
73
+ const asked = Date.parse(v.requestedAt)
74
+ if (asked - nowMs > REQUEST_SKEW_MS) return null
75
+ if (Date.parse(v.until) - asked > POSTPONE_MAX_MS) return null
76
+ return { target: v.target.toLowerCase(), until: canonIso(v.until) }
77
+ }
78
+
79
+ /**
80
+ * Is an `applying` marker's `applyingSince` recent enough to be live? Missing, invalid,
81
+ * older than APPLYING_MAX_MS, or meaningfully from the future: no.
82
+ */
83
+ export function isApplyingFresh(applyingSince, nowMs) {
84
+ // A missing or unparseable value is NaN, which fails both comparisons: not fresh.
85
+ const age = nowMs - Date.parse(applyingSince)
86
+ return age <= APPLYING_MAX_MS && age >= -REQUEST_SKEW_MS
87
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Build a human-legible degradation reason from a rejected `execFile` promise.
3
+ *
4
+ * Every CLI-backed survey in the daemon degrades a failed probe to a `reason`
5
+ * string rather than throwing (absence is signal, never an error), and they all
6
+ * want the same thing out of the rejection: the CLI's own first line of stderr
7
+ * when it produced one, else the Error's message. This was defined privately in
8
+ * `control-room/integrations.js` and is now shared, so the session PR/CI survey
9
+ * (#7344) does not become a second copy that drifts from it.
10
+ *
11
+ * @param {unknown} err - the rejection from a promisified `execFile`.
12
+ * @param {string} [label] - the command being described, e.g. 'gh pr list'.
13
+ * @returns {string} `<label> failed: <first stderr line | error message>`
14
+ */
15
+ export function execFailureReason(err, label = 'command') {
16
+ const stderr = err && typeof err === 'object' && typeof err.stderr === 'string' ? err.stderr : ''
17
+ const firstLine = stderr.split('\n').map(l => l.trim()).find(l => l.length > 0)
18
+ if (firstLine) return `${label} failed: ${firstLine}`
19
+ const message = err && typeof err === 'object' && typeof err.message === 'string' ? err.message : 'unknown error'
20
+ return `${label} failed: ${message}`
21
+ }
@@ -0,0 +1,42 @@
1
+ import { execFileSync, execFile } from 'child_process'
2
+ import { promisify } from 'util'
3
+ import { GIT } from '../git.js'
4
+
5
+ const execFileAsync = promisify(execFile)
6
+
7
+ /**
8
+ * The one "is this directory inside a git repository?" probe. Both the
9
+ * worktree-create path (`SessionManager._addDetachedWorktree`) and the
10
+ * New Session dialog's up-front `check_git_repo` query use it, so the two
11
+ * agree on what a repo is (#8972). They can still disagree at the margins
12
+ * (timeouts, transient failures, the filesystem changing between the check and
13
+ * Create); the create-time refusal is the backstop.
14
+ *
15
+ * `git -C <dir> rev-parse --git-dir` succeeds for the repo root and for any
16
+ * subdirectory of a repo or worktree. `dir` is the argument of `-C`, so it is
17
+ * never parsed as an option. The argv is written out as a literal at each call
18
+ * so the argv-sink lint can resolve it.
19
+ */
20
+
21
+ /** Synchronous probe. Never throws: any failure reads as "not a repo". */
22
+ export function isGitRepoSync(dir) {
23
+ try {
24
+ execFileSync(GIT, ['-C', dir, 'rev-parse', '--git-dir'], {
25
+ stdio: ['pipe', 'pipe', 'pipe'],
26
+ encoding: 'utf-8',
27
+ })
28
+ return true
29
+ } catch {
30
+ return false
31
+ }
32
+ }
33
+
34
+ /** Async probe for request handlers (does not block the event loop). */
35
+ export async function isGitRepo(dir) {
36
+ try {
37
+ await execFileAsync(GIT, ['-C', dir, 'rev-parse', '--git-dir'], { encoding: 'utf-8', timeout: 5000 })
38
+ return true
39
+ } catch {
40
+ return false
41
+ }
42
+ }
@@ -0,0 +1,137 @@
1
+ // is-entry-point.js — "was this module run directly, or imported?"
2
+ //
3
+ // Every hand-rolled version of this check in the repo was wrong the same way,
4
+ // so there is one implementation per reachable scope now (#7213, after #7198).
5
+ // Two other copies exist and cannot import this one:
6
+ //
7
+ // scripts/lib/is-entry-point.mjs — `scripts/` is outside every workspace
8
+ // package and reaches into none of them
9
+ // packages/server/sidecar/agent.js — a standalone in-pod bundle; the
10
+ // Dockerfile COPYs only agent.js and its
11
+ // package.json, so src/ is unreachable
12
+ //
13
+ // This file and scripts/lib/is-entry-point.mjs are byte-identical from the
14
+ // `if (!process.argv[1])` line down. sidecar/agent.js runs the same code as an
15
+ // inline IIFE, so it reads `import.meta.url` directly instead of taking it as a
16
+ // parameter and its comments are pod-specific — everything else matches.
17
+ //
18
+ // That is not a convention anyone has to remember: the drift gate in
19
+ // scripts/__tests__/is-entry-point.test.mjs extracts the guard from all three
20
+ // files, strips comments, and fails if they diverge. Change one, change the
21
+ // others, and the test will tell you if you missed one (#7222).
22
+ //
23
+ // Why this is not `import.meta.main`. Node 22.18.0 shipped that as a native,
24
+ // symlink-correct replacement that would delete all three copies. It is
25
+ // unusable here: the declared floor is `"node": ">=22"`, and on Node
26
+ // 22.0–22.17 `import.meta.main` is plain `undefined`. A falsy guard on an
27
+ // older-but-supported runtime is exactly the silent exit-0 no-op this module
28
+ // exists to prevent, reintroduced as a version skew no CI job pinned to
29
+ // `node-version: 22` would ever show. Revisit when the floor moves to >=22.18.
30
+ //
31
+ // The trap: Node's ESM loader RESOLVES SYMLINKS in `import.meta.url`, but
32
+ // `process.argv[1]` is whatever the caller typed. Neither `resolve()` nor
33
+ // `pathToFileURL()` follows symlinks, so every one of these compares a
34
+ // realpath against a non-realpath:
35
+ //
36
+ // resolve(fileURLToPath(import.meta.url)) === resolve(process.argv[1])
37
+ // import.meta.url === pathToFileURL(process.argv[1]).href
38
+ // process.argv[1] === fileURLToPath(import.meta.url)
39
+ //
40
+ // On macOS /tmp is a symlink to /private/tmp, so running a script by a /tmp
41
+ // path gives 'file:///private/tmp/x.mjs' on one side and 'file:///tmp/x.mjs'
42
+ // on the other. The guard reads false, main() never runs, and the process
43
+ // exits 0 having done nothing — the failure is silence, which is why it
44
+ // survived in four separate files.
45
+ //
46
+ // Demonstrated:
47
+ // import.meta.url : file:///private/tmp/ptfu/probe.mjs
48
+ // pathToFileURL(argv[1]) : file:///tmp/ptfu/probe.mjs
49
+ // guard would be : false
50
+ //
51
+ // Usage:
52
+ // import { isEntryPoint } from './utils/is-entry-point.js'
53
+ // if (isEntryPoint(import.meta.url)) { main() }
54
+
55
+ import { realpathSync } from 'node:fs'
56
+ import { basename, resolve } from 'node:path'
57
+ import { fileURLToPath } from 'node:url'
58
+
59
+ /**
60
+ * True when `importMetaUrl`'s module is the script node was invoked with.
61
+ *
62
+ * Order matters. The plain (non-realpath) comparison runs FIRST and is
63
+ * conclusive on its own: if the two paths are already identical, this module
64
+ * is the entry point and no filesystem access is needed to say so. Only when
65
+ * they differ is realpath consulted, because the sole reason they can differ
66
+ * while still naming the same file is a symlink somewhere in the invocation
67
+ * path.
68
+ *
69
+ * That ordering is the point, not an optimisation. Reaching for realpath
70
+ * first and treating a failure as `false` recreates the very bug this module
71
+ * exists to remove: an `EACCES` on some parent directory, or a script
72
+ * unlinked after launch, would make a direct `node foo.js` evaluate false,
73
+ * `main()` would never run, and the process would exit 0 having done nothing
74
+ * (#7217 review). Doing the cheap comparison first means no filesystem error
75
+ * can reach the common case at all.
76
+ *
77
+ * The one genuinely undecidable case is left: paths that differ AND cannot be
78
+ * realpath'd. Whether a symlink joins them is unknowable without the
79
+ * filesystem call that just failed, and `false` is the only defensible answer
80
+ * — it is also strictly better than the pre-#7213 behaviour, which got that
81
+ * case wrong even when realpath would have succeeded. Undecidable does not
82
+ * have to mean quiet, though — that combination is what made #7198 and #7214
83
+ * expensive to find — so that branch warns on stderr before returning (#7226).
84
+ * The ordinary "this module was imported" answer stays silent; only the branch
85
+ * that could not tell says anything.
86
+ *
87
+ * argv[1] absent (an `-e` eval, a REPL) means there is no invoked script, so
88
+ * nothing can be the entry point.
89
+ *
90
+ * @param {string} importMetaUrl - the calling module's `import.meta.url`
91
+ * @returns {boolean}
92
+ */
93
+ export function isEntryPoint(importMetaUrl) {
94
+ if (!process.argv[1]) return false
95
+
96
+ const self = fileURLToPath(importMetaUrl)
97
+ const invoked = resolve(process.argv[1])
98
+ if (self === invoked) return true
99
+
100
+ // Paths differ — a symlink is the only thing that still makes them the same
101
+ // file, so this is where realpath earns its keep.
102
+ const failures = []
103
+ const real = (p) => {
104
+ try {
105
+ return realpathSync(p)
106
+ } catch (err) {
107
+ failures.push({ path: p, code: err.code || err.message })
108
+ return null
109
+ }
110
+ }
111
+ const realSelf = real(self)
112
+ const realInvoked = real(invoked)
113
+ if (realSelf !== null && realInvoked !== null) return realSelf === realInvoked
114
+
115
+ // Reaching here means realpath could not answer for at least one side, so
116
+ // whether a symlink still joins the two paths is unknowable and `false` is
117
+ // the only defensible return. It is not, however, an excuse for silence —
118
+ // that combination is what made #7198 and #7214 expensive (#7226).
119
+ //
120
+ // An earlier version of this warned only when the errno was something other
121
+ // than ENOENT, on the theory that a non-existent argv[1] was a DECIDED false
122
+ // and warning on it would cry wolf during ordinary imports. Both halves were
123
+ // wrong. An ordinary import never reaches this line at all — argv[1] is the
124
+ // script node is running, so it exists, both realpaths succeed, and the
125
+ // comparison above returns. And ENOENT is not decided: argv[1] existed at
126
+ // exec time by construction, so ENOENT means it was REMOVED SINCE. Swap a
127
+ // `current -> releases-v1` symlink mid-run and you get exactly that — self
128
+ // resolves, invoked is ENOENT, and the module genuinely IS the entry point.
129
+ // The carve-out bought nothing and hid that case.
130
+ const why = failures.map(({ path, code }) => `${path}: ${code}`).join('; ')
131
+ console.warn(
132
+ `[is-entry-point] ${basename(self)}: cannot determine whether this module was run ` +
133
+ `directly — realpath failed (${why}). Assuming it was imported, so its command-line ` +
134
+ 'behaviour did NOT run. If you invoked it directly, it did nothing.',
135
+ )
136
+ return false
137
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * #7081 — epoch-ms → wire-legal ISO 8601, or null.
3
+ *
4
+ * Several outbound fields are `z.string().datetime()` in @chroxy/protocol
5
+ * (`skills.ts` `lastUsed`, control-room `RepoMemoryCache.lastModified`, …) and are
6
+ * produced by `new Date(ms).toISOString()` from a number read off disk. Those
7
+ * loaders guarded the number for TYPE (finite, positive) while the schema
8
+ * constrains RANGE, which leaves a band where `toISOString()` succeeds but emits
9
+ * something the wire rejects:
10
+ *
11
+ * 253402300799999 -> '9999-12-31T23:59:59.999Z' accepted
12
+ * 253402300800000 -> '+010000-01-01T00:00:00.000Z' REJECTED by .datetime()
13
+ * 8640000000000000 -> '+275760-09-13T00:00:00.000Z' REJECTED by .datetime()
14
+ * 8640000000000001 -> RangeError
15
+ *
16
+ * ES2015+ requires the expanded-year form (`±YYYYYY`) once the year leaves
17
+ * [0, 9999], and `z.string().datetime()` only accepts a 4-digit year. So the
18
+ * usable ceiling is the last instant of year 9999 — NOT `Date`'s ±8.64e15 limit,
19
+ * which is the bound `scheduled-task-store.js` uses for a different purpose
20
+ * (representable-as-a-Date, not representable-on-the-wire). Do not conflate them.
21
+ *
22
+ * Returns `null` rather than clamping. Every consuming field is `.nullable()`, and
23
+ * a clamped timestamp is a LIE rendered to the operator: "last used in the year
24
+ * 9999" is not more truthful than "never recorded", it is just harder to notice.
25
+ */
26
+
27
+ /** Last epoch-ms whose ISO form keeps a 4-digit year (`9999-12-31T23:59:59.999Z`). */
28
+ export const MAX_WIRE_DATETIME_MS = 253402300799999
29
+
30
+ /**
31
+ * Convert an epoch-ms value to an ISO string the wire can carry.
32
+ *
33
+ * @param {unknown} ms - candidate epoch-ms; anything non-numeric yields null
34
+ * @param {{ allowEpoch?: boolean }} [opts] - `allowEpoch` permits 0 (the Unix
35
+ * epoch). Off by default because the existing callers treat 0 as "never
36
+ * recorded" rather than as 1970-01-01.
37
+ * @returns {string|null} an ISO 8601 string with a 4-digit year, or null
38
+ */
39
+ export function isoFromEpochMs(ms, { allowEpoch = false } = {}) {
40
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return null
41
+ if (allowEpoch ? ms < 0 : ms <= 0) return null
42
+ if (ms > MAX_WIRE_DATETIME_MS) return null
43
+ // Defensive: a fractional value is legal here (Date accepts it and truncates),
44
+ // so this cannot throw after the range check above — but a future caller
45
+ // passing something exotic should degrade to null rather than crash a snapshot.
46
+ try {
47
+ return new Date(ms).toISOString()
48
+ } catch {
49
+ return null
50
+ }
51
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * node-pty-probe.js (#8151 C3) — a cached, one-shot answer to "can node-pty's
3
+ * native binding actually load in THIS process?", so `listProviders()` can
4
+ * mark `claude-tui` unavailable in an environment (the official Docker image)
5
+ * where it never will, rather than letting a client discover that only after
6
+ * a session create fails and is immediately torn down.
7
+ *
8
+ * `import('node-pty')` is a real dynamic import — it rejects, it does NOT
9
+ * throw synchronously. `listProviders()` is called on every dashboard/app
10
+ * connect (`list_providers` request + every `auth_bootstrap` burst), and
11
+ * awaiting a promise on every one of those calls doesn't fit
12
+ * `listProviders()`'s existing synchronous contract (see below) — so this
13
+ * module probes ONCE, at boot, and caches a plain boolean `listProviders()`
14
+ * can read without awaiting anything.
15
+ *
16
+ * #8151 round-2 review (S4): an earlier version of this comment justified
17
+ * the cache by claiming Node does NOT cache a rejected dynamic import, so a
18
+ * second `import('node-pty')` would repeat the full resolution/load attempt.
19
+ * That claim is wrong, and the correction matters because it was the stated
20
+ * REASON for caching, not just a background detail: Node's module graph
21
+ * records an evaluation failure against the resolved module record, and
22
+ * replays the SAME cached rejection on every subsequent `import()` of the
23
+ * same specifier — measured directly (a throwing stand-in module's body
24
+ * executes exactly once across four repeated `import()` calls in the same
25
+ * process, evaluation-failure or not). node-pty's real failure mode is
26
+ * exactly this shape: its JS entry module is found and starts evaluating,
27
+ * and a `require()`/native-binding load INSIDE that evaluation throws — so
28
+ * Node's own cache already makes a second `import('node-pty')` cheap. The
29
+ * reason this module still probes once and caches a boolean is simply that
30
+ * `listProviders()` is synchronous and cannot `await` a promise on every
31
+ * call — not a missing Node-level cache. node-pty's native binding also
32
+ * cannot appear or disappear mid-process either way (it is either built into
33
+ * the image at build time, or it never will be), so a process-lifetime
34
+ * cache — Node's or this module's — cannot go stale.
35
+ *
36
+ * `listProviders()` itself stays synchronous (existing contract, existing
37
+ * callers): `probeNodePtyAvailable()` is awaited ONCE at server boot
38
+ * (server-cli.js, before the WS server starts accepting real connections),
39
+ * and `listProviders()` reads the cached result synchronously via
40
+ * `cachedNodePtyAvailable()`, injectable per-call for tests.
41
+ *
42
+ * #8151 round-2 review (S5, nit, corrected) — node-pty ships PREBUILT
43
+ * native addons for win32 (`win32-x64`, `win32-arm64`) AND darwin
44
+ * (`darwin-x64`, `darwin-arm64`) — checked directly against the installed
45
+ * package's own `prebuilds/` directory — but for NEITHER does a successful
46
+ * `import('node-pty')` prove the binding actually WORKS: a corrupt
47
+ * install, or an ABI mismatch the loader doesn't surface at require()
48
+ * time, could still fail later, at spawn time. The probe's "available"
49
+ * result is a necessary, not sufficient, signal on BOTH of those
50
+ * platforms. Linux is the one case where it IS sufficient in practice,
51
+ * because node-pty ships no Linux prebuild at all (the reason this image
52
+ * is unsupported for claude-tui in the first place) — there, "the import
53
+ * resolved" means a real native build actually happened and linked, not
54
+ * that a vendored binary merely loaded.
55
+ */
56
+
57
+ let _cached = null
58
+
59
+ /**
60
+ * Run the probe if it hasn't run yet, and cache the result. Safe to call
61
+ * more than once — later calls return the cached value without re-probing.
62
+ *
63
+ * @returns {Promise<boolean>} true iff `import('node-pty')` resolves here.
64
+ */
65
+ export async function probeNodePtyAvailable() {
66
+ if (_cached !== null) return _cached
67
+ try {
68
+ await import('node-pty')
69
+ _cached = true
70
+ } catch {
71
+ _cached = false
72
+ }
73
+ return _cached
74
+ }
75
+
76
+ /**
77
+ * Synchronous read of the cached result.
78
+ *
79
+ * @returns {boolean|null} true/false once probed, `null` if
80
+ * `probeNodePtyAvailable()` has never been called (production always calls
81
+ * it once at boot; callers that might run before boot, or in a test that
82
+ * never probes, should treat `null` as "unknown" and decide their own
83
+ * fallback rather than this module guessing for them).
84
+ */
85
+ export function cachedNodePtyAvailable() {
86
+ return _cached
87
+ }
88
+
89
+ /**
90
+ * Test-only: reset the cache so a probe re-runs. Never called by production
91
+ * code — node-pty's availability cannot change mid-process (see module doc).
92
+ */
93
+ export function resetNodePtyProbeForTest() {
94
+ _cached = null
95
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * node-pty-support.js (#8151) — one shared message for "node-pty failed to
3
+ * load", used by every provider that dynamically `import('node-pty')`s.
4
+ *
5
+ * `claude-tui-session.js` and `user-shell-session.js` both do:
6
+ *
7
+ * let ptyMod
8
+ * try {
9
+ * ptyMod = await import('node-pty')
10
+ * } catch (err) {
11
+ * // ... surface err somehow ...
12
+ * }
13
+ *
14
+ * node-pty is a REGULAR (non-optional) server dependency, so its JS wrapper
15
+ * is always present, but its native addon is not: the official Docker image
16
+ * runs `npm ci --ignore-scripts` (no build-essential/python3 either), which
17
+ * skips the node-gyp rebuild / prebuilt-binary fetch that would normally
18
+ * produce `build/Release/pty.node`. Importing node-pty there throws — often
19
+ * a bare `Cannot find module '.../build/Release/pty.node'`, which is a true
20
+ * statement but not an ACTIONABLE one: it doesn't say the embedded terminal
21
+ * and the claude-tui provider are simply unsupported in this environment, or
22
+ * what to use instead. Before #8151 both catch blocks reported that raw
23
+ * message verbatim (still not a crash — see session-manager.js's
24
+ * `_handleAsyncStartFailure` / claude-tui's own `error` emit — just an
25
+ * unhelpful one).
26
+ *
27
+ * This is deliberately NOT Docker-specific: node-pty can just as validly fail
28
+ * to load on a bare-metal host with no native build toolchain, or after a
29
+ * Node ABI bump with no matching prebuild. The message names the Docker image
30
+ * as the expected case (since that's the one shipped, deliberately, without a
31
+ * build toolchain) while staying correct for any other cause.
32
+ */
33
+
34
+ import { getErrorMessage } from './error-message.js'
35
+
36
+ /**
37
+ * A stable, greppable marker independent of the human-readable wording in
38
+ * `describeNodePtyUnavailable()` below.
39
+ *
40
+ * #8151 round-2 review (Critical 4): `scripts/docker-image-smoke.sh`'s check
41
+ * 3 asserts that a healthy container's logs contain NEITHER this failure
42
+ * signature NOR "Destroyed session" — the fingerprint of a PTY-based
43
+ * provider failing silently behind a healthy HTTP server. That assertion
44
+ * used to `grep -qF 'node-pty unavailable'`, a SUBSTRING of the prose
45
+ * message below — S8 reworded that prose ("node-pty unavailable" →
46
+ * "node-pty is unavailable here"), which silently broke the match: the
47
+ * negative assertion could no longer fire on a real failure, so a
48
+ * regression that reintroduced claude-tui as the Default provider would
49
+ * have passed checks 1-6 clean. A hardcoded prose fragment beside wording
50
+ * that's free to change is exactly the "guard whose comment describes a
51
+ * stronger check than its code performs" class in
52
+ * docs/false-safety-guards.md. This constant is the ONE literal both the
53
+ * message below and the smoke script's needle are built from — reworded
54
+ * prose can't desync the two, because there's only one string to reword.
55
+ *
56
+ * It doubles as this failure's `.code` (see `claude-tui-session.js` /
57
+ * `user-shell-session.js`), so a client-side error handler and a bash grep
58
+ * key off literally the same token.
59
+ */
60
+ export const NODE_PTY_UNAVAILABLE_CODE = 'PTY_UNAVAILABLE'
61
+
62
+ /**
63
+ * Build the user-visible error message for a failed `import('node-pty')`.
64
+ *
65
+ * #8151 review (S8): the ACTIONABLE sentence leads — a client showing only
66
+ * the first N characters of a toast still shows the fix, not just a fact.
67
+ * The cause is appended LAST, and only its FIRST LINE: node-pty's own
68
+ * "Cannot find module '.../build/Release/pty.node'" is one line, but some
69
+ * native-addon load failures (a segfault backtrace, an N-API ABI-mismatch
70
+ * dump) are many, and a multi-line cause buried in the middle of an already
71
+ * long message is unreadable in a one-line toast.
72
+ *
73
+ * #8151 round-2 review (S4): "reinstall it" undersold the fix — `npm rebuild
74
+ * node-pty` only rebuilds the native addon for the CURRENT process's already
75
+ * -loaded module graph; the already-running daemon must actually restart to
76
+ * pick up the rebuilt binding. Worded as a two-step instruction.
77
+ *
78
+ * @param {unknown} err - the caught import rejection
79
+ * @returns {string}
80
+ */
81
+ export function describeNodePtyUnavailable(err) {
82
+ const cause = getErrorMessage(err, 'unknown error').split('\n')[0]
83
+ return (
84
+ `node-pty is unavailable here [${NODE_PTY_UNAVAILABLE_CODE}] — use the ` +
85
+ `claude-sdk provider instead. The embedded terminal and the claude-tui ` +
86
+ `provider both require a native PTY binding that failed to load. This is ` +
87
+ `expected inside the official chroxy Docker image, which ships without a ` +
88
+ `native build toolchain (node-pty has no linux prebuild). Outside ` +
89
+ `Docker, run \`npm rebuild node-pty\` and restart the chroxy daemon — on ` +
90
+ `Linux the rebuild needs python3, make and a C++ compiler. ` +
91
+ `Cause: ${cause}`
92
+ )
93
+ }
94
+
95
+ /**
96
+ * Build the Error to throw/latch for a failed `import('node-pty')` — the
97
+ * ONE catch body both providers' two import-invocation shapes (the real
98
+ * `await import('node-pty')` and a test's function-shaped `_ptyModOverride`
99
+ * override) share.
100
+ *
101
+ * #8151 round-2 review (Critical 1): before this, `claude-tui-session.js`'s
102
+ * `_spawnPty` and `user-shell-session.js`'s `start()` each duplicated this
103
+ * exact `describeNodePtyUnavailable` + `Object.assign(..., { code })`
104
+ * construction across TWO catch blocks per file (one per import shape) —
105
+ * correct duplication at the time (each catch body was too small to be
106
+ * worth a shared helper on its own), but it meant a future edit to one
107
+ * copy silently not reaching the other three. Factored out here so there
108
+ * is exactly one place that builds this error; the two `try`/`await
109
+ * import(...)` call sites stay separate (not wrapped in a shared function)
110
+ * so `lint-argv-sinks.mjs`'s AST recognition of the literal `ptyMod = await
111
+ * import('node-pty')` shape keeps seeing the real spawn sink.
112
+ *
113
+ * @param {unknown} err - the caught import rejection
114
+ * @returns {Error & { code: 'PTY_UNAVAILABLE' }}
115
+ */
116
+ export function nodePtyImportFailureError(err) {
117
+ return Object.assign(new Error(describeNodePtyUnavailable(err)), { code: NODE_PTY_UNAVAILABLE_CODE })
118
+ }