@chroxy/server 0.11.10 → 0.11.11

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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -0,0 +1,114 @@
1
+ // #8610 — a human-readable message for a Codex request error.
2
+ //
3
+ // The backend's error often arrives with its message JSON-encoded inside another
4
+ // message, e.g. { message: '{"type":"error","status":400,"error":{"type":
5
+ // "invalid_request_error","message":"The model is not supported ..."}}' }. Showing
6
+ // JSON.stringify(...) of that, cut at 200 characters, prints escaped JSON and can lose
7
+ // the message entirely.
8
+ //
9
+ // Rules:
10
+ // - Only the `error` and `message` keys are followed, never other object values.
11
+ // - Precedence at each object: the DEEPER source wins. `error` (an object, or a
12
+ // JSON-encoded object) is tried first; only if it yields no readable message is the
13
+ // object's own `message` used. So a wrapper's generic message ("Request failed") does
14
+ // not hide the nested error's real one. A plain-text (non-JSON) `error` string is used
15
+ // only as a LAST resort, when neither of those yields a message, and only when it reads
16
+ // as prose: a bare code-shaped token (e.g. invalid_request_error) is never a message.
17
+ // - A string that looks like JSON (starts with `{` or `[`) is never shown as text. One
18
+ // starting with `{` is decoded only when it is at most MAX_CODEX_ERROR_PARSE characters
19
+ // (checked BEFORE parsing) and parses to an object; one starting with `[` (an array,
20
+ // well-formed or not) is never a message source. Either way, otherwise unreadable.
21
+ // - The walk is bounded: at most MAX_CODEX_ERROR_DEPTH levels, two branches per level.
22
+ // - `status` is kept only as an integer HTTP status 100-599; `type` only as a short
23
+ // identifier. The deepest valid value wins.
24
+ // - The final formatted text is at most MAX_CODEX_ERROR_TEXT characters.
25
+ // - When nothing readable is found, callers show UNREADABLE_CODEX_ERROR: no raw
26
+ // payload, escaped JSON or other metadata is ever shown.
27
+
28
+ import { redactBounded } from './redaction.js'
29
+
30
+ export const MAX_CODEX_ERROR_DEPTH = 6
31
+ export const MAX_CODEX_ERROR_PARSE = 16 * 1024
32
+ export const MAX_CODEX_ERROR_TEXT = 2000
33
+ export const MAX_CODEX_ERROR_LOG = 4096
34
+ const LOG_TRUNCATION_MARKER = '... [truncated]'
35
+ export const UNREADABLE_CODEX_ERROR = 'Codex error: the request failed and returned no readable message.'
36
+
37
+ const PREFIX = 'Codex error: '
38
+ const TYPE_RE = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/
39
+ // A single code-like token, with no whitespace: not prose, so not a last-resort message.
40
+ const CODE_RE = /^[A-Za-z0-9_.:/-]+$/
41
+
42
+ function statusOf(v) {
43
+ return typeof v === 'number' && Number.isInteger(v) && v >= 100 && v <= 599 ? v : null
44
+ }
45
+
46
+ function typeOf(v) {
47
+ return typeof v === 'string' && v !== 'error' && TYPE_RE.test(v) ? v : null
48
+ }
49
+
50
+ function read(node, depth) {
51
+ if (depth >= MAX_CODEX_ERROR_DEPTH || node == null) return null
52
+ if (typeof node === 'string') {
53
+ const t = node.trim()
54
+ if (!t) return null
55
+ if (t.startsWith('[')) return null // array or array-like text: never a message, never shown
56
+ if (t.startsWith('{')) {
57
+ if (t.length > MAX_CODEX_ERROR_PARSE) return null
58
+ let parsed
59
+ try { parsed = JSON.parse(t) } catch { return null }
60
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? read(parsed, depth + 1) : null
61
+ }
62
+ return { message: t, status: null, type: null }
63
+ }
64
+ if (typeof node !== 'object' || Array.isArray(node)) return null
65
+ // `error` is a message source only when it is an object or a JSON-encoded object;
66
+ // a plain-text `error` (often just a code) must not outrank a real `message`.
67
+ const e = node.error
68
+ const nested = (e && typeof e === 'object') || (typeof e === 'string' && e.trim().startsWith('{'))
69
+ const prose = typeof e === 'string' && !nested && !CODE_RE.test(e.trim())
70
+ const found = (nested ? read(e, depth + 1) : null)
71
+ ?? (typeof node.message === 'string' ? read(node.message, depth + 1) : null)
72
+ ?? (prose ? read(e, depth + 1) : null) // last resort; `[` text stays unreadable
73
+ if (!found) return null
74
+ return {
75
+ message: found.message,
76
+ status: found.status ?? statusOf(node.status),
77
+ type: found.type ?? typeOf(node.type),
78
+ }
79
+ }
80
+
81
+ /**
82
+ * @param {unknown} err - the error object (usually `params.error`) or a string
83
+ * @returns {{ message: string, status: number|null, type: string|null }|null}
84
+ */
85
+ export function describeCodexError(err) {
86
+ return read(err, 0)
87
+ }
88
+
89
+ /**
90
+ * `Codex error: <message> (status 400, invalid_request_error)`, at most MAX_CODEX_ERROR_TEXT chars.
91
+ * Takes ONLY the validated output of describeCodexError (a non-JSON message, an integer
92
+ * HTTP status or null, a short identifier type or null); it does not re-validate.
93
+ */
94
+ export function formatCodexError({ message, status, type }) {
95
+ const detail = [status != null ? `status ${status}` : null, type].filter(Boolean).join(', ')
96
+ const suffix = detail ? ` (${detail})` : ''
97
+ const room = MAX_CODEX_ERROR_TEXT - PREFIX.length - suffix.length
98
+ const body = message.length > room ? `${message.slice(0, room - 1)}…` : message
99
+ return `${PREFIX}${body}${suffix}`
100
+ }
101
+
102
+ /**
103
+ * The raw payload of a terminal error, for ONE server log line (never the chat card): the
104
+ * whole payload is serialized and redacted FIRST, then cut at MAX_CODEX_ERROR_LOG
105
+ * characters with a truncation marker, so a credential straddling the cut is already masked.
106
+ * A payload that cannot be serialized says so instead of throwing.
107
+ */
108
+ export function rawCodexErrorForLog(raw) {
109
+ let text
110
+ try { text = typeof raw === 'string' ? raw : JSON.stringify(raw) } catch { return '[unserializable payload]' }
111
+ if (typeof text !== 'string') return '[no payload]'
112
+ const redacted = redactBounded(text)
113
+ return redacted.length > MAX_CODEX_ERROR_LOG ? redacted.slice(0, MAX_CODEX_ERROR_LOG) + LOG_TRUNCATION_MARKER : redacted
114
+ }
@@ -71,11 +71,16 @@ export const HIGH_CONSEQUENCE_ENTRIES = ['config.json', 'server-identity.json',
71
71
  *
72
72
  * Windows reports `ino` as 0 on some filesystems, so fall back to a normalized
73
73
  * (case-insensitive there) path compare when either inode is unusable.
74
+ *
75
+ * The stat is `{ bigint: true }` on purpose: an NTFS file ID is 64 bits, and a
76
+ * plain stat hands it back as a double that loses everything above 2^53, so two
77
+ * different directories created back to back can round to the same Number and
78
+ * read as one (#8750). BigInt `dev`/`ino` are exact.
74
79
  */
75
- function sameDir(a, b) {
80
+ function sameDir(a, b, statImpl = statSync) {
76
81
  try {
77
- const sa = statSync(a)
78
- const sb = statSync(b)
82
+ const sa = statImpl(a, { bigint: true })
83
+ const sb = statImpl(b, { bigint: true })
79
84
  if (sa.ino && sb.ino) return sa.dev === sb.dev && sa.ino === sb.ino
80
85
  } catch {
81
86
  // One side is missing or unreadable — fall through to the path compare,
@@ -102,10 +107,10 @@ function sameDir(a, b) {
102
107
  * Never throws: an unreadable source is reported via `unreadable` so callers on
103
108
  * the boot path can degrade rather than fail.
104
109
  *
105
- * @param {{ source?: string, target?: string }} [opts] Injection seams for tests.
110
+ * @param {{ source?: string, target?: string, statImpl?: typeof statSync }} [opts] Injection seams for tests.
106
111
  * @returns {StrandedState}
107
112
  */
108
- export function detectStrandedState({ source = defaultConfigDir(), target = configDir() } = {}) {
113
+ export function detectStrandedState({ source = defaultConfigDir(), target = configDir(), statImpl } = {}) {
109
114
  const result = {
110
115
  relocated: false,
111
116
  source,
@@ -118,7 +123,7 @@ export function detectStrandedState({ source = defaultConfigDir(), target = conf
118
123
  // Covers every not-relocated case at once: the variable unset, set empty, set
119
124
  // to a relative path (config-dir.js refuses those back to the default), or set
120
125
  // to `~/.chroxy` itself by a different spelling or through a symlink.
121
- if (sameDir(source, target)) return result
126
+ if (sameDir(source, target, statImpl)) return result
122
127
  result.relocated = true
123
128
 
124
129
  if (!existsSync(source)) return result
package/src/config.js CHANGED
@@ -210,7 +210,8 @@ const CONFIG_SCHEMA = {
210
210
  sessionArchive: 'object',
211
211
  // #7424: the session CI-completion watcher. `{ watch?: boolean, wakeAgent?:
212
212
  // boolean, intervalMs?: number, discoveryIntervalMs?: number,
213
- // maxSurveysPerTick?: number }` (#7436 added the per-tick cap). `watch`
213
+ // maxSurveysPerTick?: number, maxConsecutiveWakes?: number }` (#7436 added
214
+ // the per-tick cap). `watch`
214
215
  // defaults ON — the daemon periodically surveys each session's PR through the
215
216
  // user's own `gh` and, when a run settles, notifies (`ci_complete`) and wakes
216
217
  // the agent with one daemon-authored line: typed into a claude-tui prompt, or
@@ -218,6 +219,9 @@ const CONFIG_SCHEMA = {
218
219
  // `capabilities.daemonTurnInput` — claude-sdk included (#8301). Set
219
220
  // `watch: false` on a host that should make no background GitHub calls;
220
221
  // `wakeAgent: false` keeps the notification but never wakes a session.
222
+ // `maxConsecutiveWakes` (#8326, default 3) bounds the wake -> push -> CI ->
223
+ // wake loop: after that many daemon wakes with no user-typed input between,
224
+ // the next is refused (`wake-cap`) while the notification still goes out.
221
225
  sessionCi: 'object',
222
226
  sandbox: 'object',
223
227
  // Optional allowlist of absolute directory paths that sessions may use
@@ -236,6 +240,12 @@ const CONFIG_SCHEMA = {
236
240
  // config file on the dev machine (physical-access proxy for real
237
241
  // user confirmation). Added in the 2026-04-11 audit Adversary A5 fix.
238
242
  allowAutoPermissionMode: 'boolean',
243
+ // How a session created WITHOUT a name is named: 'project' (default) gives
244
+ // "<project> <n>" ("chroxy 7", numbers kept per project in a durable store next
245
+ // to session-state.json), 'legacy' keeps "Session <n>". An explicit name always
246
+ // wins; a project that cannot be determined, or a store that cannot be trusted,
247
+ // falls back to the legacy name. See resolveSessionNaming().
248
+ sessionNaming: 'string',
239
249
  // #5985 (epic #5982): gate for the embedded user-shell terminal — a
240
250
  // `user-shell` session spawns the operator's `$SHELL` (arbitrary code
241
251
  // execution on the dev machine, reachable through the tunnel). Nested object
@@ -575,7 +585,7 @@ export const SESSION_ARCHIVE_SUPPORTED_KEYS = new Set([
575
585
  'enabled', 'maxEntries', 'maxAgeDays', 'maxMegabytes',
576
586
  ])
577
587
  export const SESSION_CI_SUPPORTED_KEYS = new Set([
578
- 'watch', 'wakeAgent', 'intervalMs', 'discoveryIntervalMs', 'maxSurveysPerTick',
588
+ 'watch', 'wakeAgent', 'intervalMs', 'discoveryIntervalMs', 'maxSurveysPerTick', 'maxConsecutiveWakes',
579
589
  ])
580
590
  export const RANCHER_SUPPORTED_KEYS = new Set([
581
591
  'rancherUrl', 'clusterId', 'token', 'tokenEnv', 'tokenFile', 'caData', 'skipTLSVerify', 'defaultProjectId',
@@ -921,6 +931,12 @@ export function isSchedulerEnabled(config) {
921
931
  return config?.features?.scheduler === true
922
932
  }
923
933
 
934
+ // Session naming mode. Anything but an explicit 'legacy' is 'project' (the default);
935
+ // validateConfig warns about an unrecognised value.
936
+ export function resolveSessionNaming(config) {
937
+ return config?.sessionNaming === 'legacy' ? 'legacy' : 'project'
938
+ }
939
+
924
940
  // #6858 — resolve the opt-in provider-binary provenance PIN-LEDGER mode. One of
925
941
  // 'off' | 'warn' | 'block'. Fail-closed to 'off' (behaviour identical to the
926
942
  // pre-#6858 spawn path) for anything but an explicit 'warn' / 'block'. Precedence:
@@ -1294,6 +1310,10 @@ export function validateConfig(config, verbose = false) {
1294
1310
  }
1295
1311
  }
1296
1312
 
1313
+ if (typeof config.sessionNaming === 'string' && config.sessionNaming !== 'project' && config.sessionNaming !== 'legacy') {
1314
+ warnings.push(`Invalid value for 'sessionNaming': '${config.sessionNaming}' (expected 'project' or 'legacy'); using 'project'`)
1315
+ }
1316
+
1297
1317
  // Range validation for the simple numeric fields (audit P2-6) — declarative
1298
1318
  // table + shared validateRange; the Number.isFinite guard skips fields whose
1299
1319
  // type the loop above already flagged. Duration/cross-field/map cases below
@@ -1589,7 +1609,7 @@ export function validateConfig(config, verbose = false) {
1589
1609
  warnings.push(`Invalid type for 'sessionCi.${key}': expected boolean, got ${typeof config.sessionCi[key]}`)
1590
1610
  }
1591
1611
  }
1592
- for (const key of ['intervalMs', 'discoveryIntervalMs', 'maxSurveysPerTick']) {
1612
+ for (const key of ['intervalMs', 'discoveryIntervalMs', 'maxSurveysPerTick', 'maxConsecutiveWakes']) {
1593
1613
  if (!Object.prototype.hasOwnProperty.call(config.sessionCi, key)) continue
1594
1614
  const v = config.sessionCi[key]
1595
1615
  if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) {
@@ -2,6 +2,7 @@ import { join } from 'path'
2
2
  import { existsSync, readFileSync, unlinkSync, mkdirSync } from 'fs'
3
3
  import { writeFileRestricted } from './platform.js'
4
4
  import { configDir, configPath } from './config-dir.js'
5
+ import { probePidLiveness, PID_ALIVE, PID_DEAD } from './utils/pid-liveness.js'
5
6
 
6
7
  export function getConnectionInfoPath() {
7
8
  return configPath('connection.json')
@@ -13,24 +14,82 @@ export function writeConnectionInfo(info) {
13
14
  writeFileRestricted(join(dir, 'connection.json'), JSON.stringify(info, null, 2))
14
15
  }
15
16
 
16
- export function readConnectionInfo() {
17
+ /**
18
+ * The daemon's discovery record, returned ONLY when its recorded PID is verified
19
+ * alive (#9074). Every other outcome returns null:
20
+ * - no file, or an unreadable file;
21
+ * - a record with a missing or malformed pid;
22
+ * - a dead pid (ESRCH);
23
+ * - an unverified pid (EPERM under a sandbox, or any other probe error; see
24
+ * utils/pid-liveness.js).
25
+ *
26
+ * Callers use the record to send the daemon's primary bearer to a loopback port, so
27
+ * "could not verify" fails closed exactly like "not running". "Alive" is the probe's
28
+ * claim only: some process with that PID exists. It is not proof that the process
29
+ * is the daemon, or that the daemon listens on the recorded port.
30
+ *
31
+ * Deletion: before #9074 this read deleted the record on ANY probe error. The existing
32
+ * cleanup for a pid proven dead (ESRCH) is retained. Every other failure (EPERM, any
33
+ * other probe error, a missing or malformed pid) now preserves the record: "could not
34
+ * verify" is not "dead".
35
+ *
36
+ * Known, pre-existing race (documented, not introduced here): a reader can probe the
37
+ * old record's dead PID, a restarting daemon can then write its own record, and this
38
+ * unlink removes the new one. What this call does in that case: it returns null and
39
+ * transmits no credential. No claim is made here about what callers do next. Until
40
+ * the daemon writes its record again, readers find none.
41
+ *
42
+ * This reader still collapses "unverified" and "not running" into null. A caller that
43
+ * must word them differently uses `readConnectionState()` below (#9229).
44
+ *
45
+ * @param {{ probePidLiveness?: (pid: unknown) => 'alive' | 'dead' | 'unverified' }} [deps]
46
+ * @returns {object|null}
47
+ */
48
+ export function readConnectionInfo(deps = {}) {
49
+ return readConnectionState(deps).info
50
+ }
51
+
52
+ /**
53
+ * Why `readConnectionState()` returned no record (#9229). `info` is non-null only
54
+ * for `CONNECTION_ALIVE`.
55
+ */
56
+ export const CONNECTION_ALIVE = 'alive'
57
+ /** No file, an unreadable or unparseable file, or a non-object record. */
58
+ export const CONNECTION_NO_RECORD = 'no_record'
59
+ /** The recorded pid is proven gone (ESRCH); the stale record was removed. */
60
+ export const CONNECTION_DEAD = 'dead'
61
+ /** Liveness could not be established (EPERM, other probe error, missing/malformed pid). The record is kept. */
62
+ export const CONNECTION_LIVENESS_UNVERIFIED = 'liveness_unverified'
63
+
64
+ /**
65
+ * `readConnectionInfo()` plus the reason, so a CLI can word "no daemon" and "could not
66
+ * verify the daemon is running" differently. This is the ONE implementation:
67
+ * `readConnectionInfo()` returns `.info` of this, so the two cannot disagree about
68
+ * when a record (and with it the bearer token) is handed out. `info` is non-null ONLY
69
+ * when the probe says `alive`; `dead` and `unverified` both carry `info: null`.
70
+ * Deletion is unchanged: only `dead` unlinks.
71
+ *
72
+ * @param {{ probePidLiveness?: (pid: unknown) => 'alive' | 'dead' | 'unverified' }} [deps]
73
+ * @returns {{ info: object, reason: 'alive' } | { info: null, reason: 'no_record'|'dead'|'liveness_unverified' }}
74
+ */
75
+ export function readConnectionState(deps = {}) {
76
+ const probe = typeof deps.probePidLiveness === 'function' ? deps.probePidLiveness : probePidLiveness
17
77
  const connFile = getConnectionInfoPath()
18
- if (!existsSync(connFile)) return null
78
+ if (!existsSync(connFile)) return { info: null, reason: CONNECTION_NO_RECORD }
79
+ let info
19
80
  try {
20
- const info = JSON.parse(readFileSync(connFile, 'utf-8'))
21
- if (info && info.pid) {
22
- try {
23
- process.kill(info.pid, 0) // signal 0 = existence check
24
- } catch {
25
- // Process is dead — stale file
26
- removeConnectionInfo()
27
- return null
28
- }
29
- }
30
- return info
81
+ info = JSON.parse(readFileSync(connFile, 'utf-8'))
31
82
  } catch {
32
- return null
83
+ return { info: null, reason: CONNECTION_NO_RECORD }
84
+ }
85
+ if (!info || typeof info !== 'object') return { info: null, reason: CONNECTION_NO_RECORD }
86
+ const liveness = probe(info.pid)
87
+ if (liveness === PID_DEAD) {
88
+ removeConnectionInfo() // the existing ESRCH cleanup, retained (see above)
89
+ return { info: null, reason: CONNECTION_DEAD }
33
90
  }
91
+ if (liveness === PID_ALIVE) return { info, reason: CONNECTION_ALIVE }
92
+ return { info: null, reason: CONNECTION_LIVENESS_UNVERIFIED }
34
93
  }
35
94
 
36
95
  export function removeConnectionInfo() {
@@ -6,14 +6,58 @@ import { fileURLToPath } from 'node:url'
6
6
  export const CONTINUATION_TTL_MS = 30 * 60_000
7
7
  const MAX_CONTINUATIONS = 50
8
8
 
9
+ /** Longest from an announcement to its baseline probe FINISHING. A queued entry
10
+ * whose remaining budget cannot fit the baseline deadline fails closed without a
11
+ * probe, so the window in which an unannounced replacement could be adopted is at
12
+ * most this. */
13
+ export const BASELINE_MAX_WAIT_MS = 10_000
14
+ const DEFAULT_BASELINE_DEADLINE_MS = 5000
15
+ /** Slack past a batch's budget before the loop stops waiting on a probe that
16
+ * never answers (for example a child stuck in an uninterruptible stat). */
17
+ const BATCH_CAP_GRACE_MS = 250
18
+ /** How long a list request waits for baseline work already in flight. */
19
+ export const LIST_BASELINE_WAIT_MS = 1000
20
+
9
21
  /** One killable worker globally; a stuck syscall cannot fill libuv's pool or
10
- * create an unbounded process queue. Keep the slot until child close. The worker
11
- * path seam is direct-test-only, never populated from HTTP input. */
12
- export function createContinuationProbe({ workerPath = fileURLToPath(new URL('./continuation-metadata-worker.js', import.meta.url)), timeoutMs = 1000 } = {}) {
22
+ * create an unbounded process queue. Keep the slot until child close. Refresh
23
+ * calls get `timeoutMs` and return null at once while the slot is held. Baseline
24
+ * calls (`{ baseline: true, waitMs }`) get the longer `baselineTimeoutMs` and wait
25
+ * at most `waitMs` for the slot (a killed child frees it on close); a slot that
26
+ * is not free in time yields null, so a child that cannot be killed cannot park
27
+ * the caller. The worker path seam
28
+ * is direct-test-only, never populated from HTTP input. */
29
+ export function createContinuationProbe({
30
+ workerPath = fileURLToPath(new URL('./continuation-metadata-worker.js', import.meta.url)),
31
+ timeoutMs = 1000,
32
+ baselineTimeoutMs = Math.max(timeoutMs, 5000),
33
+ } = {}) {
13
34
  let active = false
14
- return (entries) => {
15
- if (active || entries.length === 0) return Promise.resolve(null)
35
+ let waiters = []
36
+ const release = () => {
37
+ active = false
38
+ const queued = waiters
39
+ waiters = []
40
+ for (const wake of queued) wake()
41
+ }
42
+ const waitForSlot = (ms) => new Promise((resolve) => {
43
+ const wake = () => { clearTimeout(timer); resolve(true) }
44
+ const timer = setTimeout(() => { waiters = waiters.filter((w) => w !== wake); resolve(false) }, ms)
45
+ waiters.push(wake)
46
+ })
47
+ const probe = async (entries, { baseline = false, waitMs = baselineTimeoutMs } = {}) => {
48
+ if (entries.length === 0) return null
49
+ const until = Date.now() + waitMs
50
+ while (active) {
51
+ if (!baseline) return null
52
+ const left = until - Date.now()
53
+ if (left <= 0 || !(await waitForSlot(left))) return null
54
+ }
16
55
  active = true
56
+ // A slot is released at most once per spawn: a late 'close' after 'error'
57
+ // (or the reverse) must never free a slot a newer probe now holds.
58
+ let released = false
59
+ const releaseOnce = () => { if (released) return; released = true; release() }
60
+ const deadline = baseline ? baselineTimeoutMs : timeoutMs
17
61
  return new Promise((resolve) => {
18
62
  let child, timer, settled = false, output = ''
19
63
  const finish = (result) => {
@@ -24,10 +68,10 @@ export function createContinuationProbe({ workerPath = fileURLToPath(new URL('./
24
68
  }
25
69
  try {
26
70
  child = spawn(process.execPath, ['--', workerPath], { stdio: ['pipe', 'pipe', 'ignore'] })
27
- timer = setTimeout(() => { finish(null); child.kill('SIGKILL') }, timeoutMs)
28
- child.on('error', () => { active = false; finish(null) })
71
+ timer = setTimeout(() => { finish(null); child.kill('SIGKILL') }, deadline)
72
+ child.on('error', () => { releaseOnce(); finish(null) })
29
73
  child.on('close', (code) => {
30
- active = false
74
+ releaseOnce()
31
75
  let result = null
32
76
  if (code === 0) {
33
77
  try { result = JSON.parse(output) } catch { /* unavailable */ }
@@ -42,11 +86,13 @@ export function createContinuationProbe({ workerPath = fileURLToPath(new URL('./
42
86
  child.stdin.end(JSON.stringify(entries.map(({ id, seedPath, cwd }) => ({ id, seedPath, cwd }))))
43
87
  } catch {
44
88
  if (child) child.kill('SIGKILL')
45
- else active = false
89
+ else releaseOnce()
46
90
  finish(null)
47
91
  }
48
92
  })
49
93
  }
94
+ probe.baselineTimeoutMs = baselineTimeoutMs
95
+ return probe
50
96
  }
51
97
 
52
98
  const probeMetadata = createContinuationProbe()
@@ -54,61 +100,128 @@ function expired(entry, now) {
54
100
  return now - entry.ts > CONTINUATION_TTL_MS || entry.ts > now + 60_000
55
101
  }
56
102
 
57
- async function refreshMetadata(server, now, probe) {
103
+ function failBaseline(entry) {
104
+ entry.fingerprint = null
105
+ entry.baselineFailed = true
106
+ entry.unavailable = 'metadata timeout'
107
+ }
108
+
109
+ const pendingBaseline = (entry, now) => entry.fingerprint === undefined && !entry.baselineFailed && !expired(entry, now)
110
+
111
+ /** Baseline queue. A baseline is adopted ONLY from a probe batch started for the
112
+ * announcement itself, never from a list/poll refresh and never from a batch the
113
+ * announcement was not part of. One loop runs at a time; an announcement that
114
+ * arrives mid-batch is picked up by the next iteration with its own probe. */
115
+ function startBaselines(server) {
58
116
  if (server._continuationRefresh) return server._continuationRefresh
59
- const entries = [...(server._continuations?.values() || [])].filter((entry) => !expired(entry, now) && !entry.baselineFailed)
117
+ const holder = {}
118
+ holder.promise = (async () => {
119
+ try {
120
+ for (;;) {
121
+ const probe = server._continuationBaselineProbe
122
+ const now = Date.now()
123
+ const batch = [...(server._continuations?.values() || [])].filter((entry) => pendingBaseline(entry, now))
124
+ if (batch.length === 0) return
125
+ const deadline = probe.baselineTimeoutMs ?? DEFAULT_BASELINE_DEADLINE_MS
126
+ // A probe that starts must also finish inside the bound.
127
+ // `_continuationBaselineMaxWaitMs` is a test injection point only (like
128
+ // `_continuationProbe`): nothing in src sets it, so production always uses
129
+ // BASELINE_MAX_WAIT_MS.
130
+ const maxWait = server._continuationBaselineMaxWaitMs ?? BASELINE_MAX_WAIT_MS
131
+ const waiting = batch.filter((entry) => now - entry.receivedAt + deadline > maxWait)
132
+ for (const entry of waiting) failBaseline(entry)
133
+ const live = batch.filter((entry) => !waiting.includes(entry))
134
+ if (live.length === 0) continue
135
+ const waitMs = Math.min(...live.map((entry) => maxWait - deadline - (now - entry.receivedAt)))
136
+ // The probe is raced against the batch budget: a child that never closes
137
+ // cannot park the loop, and a late answer is never read.
138
+ let results = null, cap
139
+ try {
140
+ results = await Promise.race([
141
+ probe(live, { baseline: true, waitMs }),
142
+ new Promise((resolve) => { cap = setTimeout(() => resolve(null), waitMs + deadline + BATCH_CAP_GRACE_MS) }),
143
+ ])
144
+ } catch { /* unavailable */ } finally { clearTimeout(cap) }
145
+ for (const entry of live) {
146
+ if (server._continuations?.get(entry.id) !== entry) continue
147
+ if (!results || !Object.hasOwn(results, entry.id)) {
148
+ // Without the announcement's own initial snapshot we cannot tell
149
+ // whether a later check sees the original file or a replacement.
150
+ failBaseline(entry)
151
+ continue
152
+ }
153
+ entry.fingerprint = results[entry.id]
154
+ entry.unavailable = entry.fingerprint ? null : 'missing'
155
+ }
156
+ }
157
+ } finally {
158
+ holder.done = true
159
+ if (server._continuationRefresh === holder.promise) server._continuationRefresh = null
160
+ }
161
+ })()
162
+ if (!holder.done) server._continuationRefresh = holder.promise
163
+ return holder.promise
164
+ }
165
+
166
+ /** Re-checks entries that already have a baseline. Never adopts one. */
167
+ async function refreshEstablished(server, now, probe) {
168
+ if (server._continuationListRefresh) return server._continuationListRefresh
169
+ const entries = [...(server._continuations?.values() || [])]
170
+ .filter((entry) => entry.fingerprint !== undefined && !entry.baselineFailed && !expired(entry, now))
60
171
  if (entries.length === 0) return
61
172
  const refresh = (async () => {
62
173
  const results = await probe(entries)
63
174
  for (const entry of entries) {
64
175
  if (server._continuations?.get(entry.id) !== entry) continue
65
- if (!results || !Object.hasOwn(results, entry.id)) {
66
- // Without the announcement's initial snapshot we cannot tell whether a
67
- // later successful check sees the original file or a replacement. Only
68
- // a newer announcement may establish another baseline in that case.
69
- if (entry.fingerprint === undefined) {
70
- entry.fingerprint = null
71
- entry.baselineFailed = true
72
- }
73
- entry.unavailable = 'metadata timeout'
74
- continue
75
- }
176
+ if (!results || !Object.hasOwn(results, entry.id)) { entry.unavailable = 'metadata timeout'; continue }
76
177
  const current = results[entry.id]
77
- if (entry.fingerprint === undefined) entry.fingerprint = current
78
178
  entry.unavailable = !current || !entry.fingerprint ? 'missing' : current !== entry.fingerprint ? 'changed' : null
79
179
  }
80
180
  })()
81
- server._continuationRefresh = refresh
82
- try { await refresh } finally { if (server._continuationRefresh === refresh) server._continuationRefresh = null }
181
+ server._continuationListRefresh = refresh
182
+ try { await refresh } finally { if (server._continuationListRefresh === refresh) server._continuationListRefresh = null }
183
+ }
184
+
185
+ async function waitBounded(promise, ms) {
186
+ let timer
187
+ try {
188
+ await Promise.race([promise.catch(() => {}), new Promise((resolve) => { timer = setTimeout(resolve, ms) })])
189
+ } finally { clearTimeout(timer) }
83
190
  }
84
191
 
85
- export function recordContinuation(server, event, now = Date.now(), probe = probeMetadata) {
192
+ // `server._continuationProbe` is a test injection point only: nothing on the
193
+ // HTTP path ever sets it, so production always uses the isolated child probe.
194
+ // It serves tests/continuations.test.js, which pins both defaults below.
195
+ export function recordContinuation(server, event, now = Date.now(), probe = server._continuationProbe ?? probeMetadata) {
86
196
  const { seedPath, cwd } = event.data
87
197
  const id = createHash('sha256').update(JSON.stringify([cwd, seedPath])).digest('hex')
88
198
  if (!server._continuations) server._continuations = new Map()
89
199
  const previous = server._continuations.get(id)
90
200
  if (previous && event.ts <= previous.ts) return { opportunity: previous, duplicate: true }
91
- const opportunity = { id, seedPath, cwd, ts: event.ts, fingerprint: undefined, unavailable: 'checking metadata' }
201
+ const opportunity = { id, seedPath, cwd, ts: event.ts, receivedAt: now, fingerprint: undefined, unavailable: 'checking metadata' }
92
202
  server._continuations.delete(id)
93
203
  server._continuations.set(id, opportunity)
94
204
  while (server._continuations.size > MAX_CONTINUATIONS) server._continuations.delete(server._continuations.keys().next().value)
95
- // The isolated probe never delays the ingest acknowledgement.
96
- if (server._continuationRefresh) {
97
- // That batch already captured its entries. Joining its promise would leave
98
- // this announcement unexamined until a later refresh could adopt a new file.
99
- opportunity.fingerprint = null
100
- opportunity.baselineFailed = true
101
- opportunity.unavailable = 'metadata timeout'
102
- } else {
103
- void refreshMetadata(server, now, probe).catch(() => {})
104
- }
205
+ // The isolated probe never delays the ingest acknowledgement. An announcement
206
+ // that lands while a batch is running is queued behind it and gets its own.
207
+ server._continuationBaselineProbe = probe
208
+ void startBaselines(server).catch(() => {})
105
209
  return { opportunity, duplicate: false }
106
210
  }
107
211
 
108
- export async function listContinuations(server, now = Date.now(), probe = probeMetadata) {
109
- await refreshMetadata(server, now, probe)
212
+ export async function listContinuations(server, now = Date.now(), probe = server._continuationProbe ?? probeMetadata) {
213
+ // Bounded wait for baseline work; a still-pending entry reads 'checking metadata'.
214
+ if (server._continuationRefresh) await waitBounded(server._continuationRefresh, server._continuationListWaitMs ?? LIST_BASELINE_WAIT_MS)
215
+ // The one probe worker may still be busy with a baseline: do not probe, and do
216
+ // not turn that busy answer into a spurious 'metadata timeout'.
217
+ const busy = Boolean(server._continuationRefresh)
218
+ if (!busy) await refreshEstablished(server, now, probe)
110
219
  return [...(server._continuations?.values() || [])].reverse().map((entry) => {
111
- const unavailable = expired(entry, now) ? 'expired' : entry.unavailable
220
+ // An established entry that could not be re-verified (baseline work holds
221
+ // the worker) must not keep reading 'available'. Response only: state is
222
+ // untouched, so it re-verifies normally once the worker is free.
223
+ const stale = busy && entry.unavailable === null && entry.fingerprint !== undefined && !entry.baselineFailed
224
+ const unavailable = expired(entry, now) ? 'expired' : stale ? 'checking metadata' : entry.unavailable
112
225
  return { id: entry.id, seedPath: entry.seedPath, cwd: entry.cwd, ts: entry.ts, available: unavailable === null, unavailable }
113
226
  })
114
227
  }
@@ -2,7 +2,7 @@ import { readdir, stat, realpath } from 'fs/promises'
2
2
  import { readContainedBytes } from './utils/regular-file.js'
3
3
  import { join, basename } from 'path'
4
4
  import { claudeProjectsDir } from './utils/claude-config-dir.js'
5
- import { decodeProjectPath } from './jsonl-reader.js'
5
+ import { decodeProjectPath, promptPreview } from './jsonl-reader.js'
6
6
  import { runWithConcurrency } from './utils/concurrency.js'
7
7
 
8
8
  const PREVIEW_BYTES = 32 * 1024 // read first 32KB for preview extraction
@@ -68,26 +68,7 @@ async function extractMetadata(filePath, root) {
68
68
  }
69
69
 
70
70
  // Extract preview from first real user message
71
- if (!preview && entry.type === 'user') {
72
- const content = entry.message?.content
73
-
74
- // Handle string content (older format)
75
- if (typeof content === 'string') {
76
- preview = content.slice(0, 200)
77
- } else if (Array.isArray(content)) {
78
- const hasToolResult = content.some((b) => b.type === 'tool_result')
79
- if (!hasToolResult) {
80
- const textParts = content
81
- .filter((b) => b.type === 'text')
82
- .map((b) => b.text)
83
- .join('\n')
84
-
85
- if (textParts) {
86
- preview = textParts.slice(0, 200)
87
- }
88
- }
89
- }
90
- }
71
+ if (!preview) preview = promptPreview(entry)
91
72
 
92
73
  if (preview && cwd) break
93
74
  }