@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,171 @@
1
+ /**
2
+ * Is the daemon safe to restart right now? (#8324)
3
+ *
4
+ * The idle-only auto-deploy (`scripts/deploy-daemon.mjs`) restarts the owner's
5
+ * daily daemon, which kills every live session. It may only do that when
6
+ * nothing would be lost. "Idle" here is deliberately strict and means ALL of:
7
+ *
8
+ * - no session is busy (a turn is running, OR a tracked background shell
9
+ * still holds the session busy — `isBusy` merges both, #8302)
10
+ * - no session has a permission request waiting on a human
11
+ * - no session has an AskUserQuestion waiting on a human
12
+ * - no hook-routed permission request is parked on the daemon
13
+ * - nothing `getRestartBlockers()` names: work `isBusy` does not report, such
14
+ * as a background agent that outlived its turn, input accepted but not yet
15
+ * dispatched, or a TUI whose terminal is still producing output
16
+ * - no session's provider has produced output in the last
17
+ * PROVIDER_QUIET_WINDOW_MS (#8743). `isBusy` is the daemon's own turn
18
+ * bookkeeping, and when that is wrong the provider is still working while
19
+ * the session reads idle: trial run B2-cy-codex lost a 17-minute Codex run to
20
+ * a restart while codex emitted every few seconds. The window is read from
21
+ * what the provider SAID (`providerActivityAgeMs`), not from the turn state.
22
+ *
23
+ * FAIL SAFE. Every uncertainty reads as NOT idle. "Could not check" must never
24
+ * be the same observable outcome as "nothing to check" (docs/false-safety-guards.md):
25
+ * a missing session manager, a throwing accessor and a malformed row each add a
26
+ * reason and force `idle: false`. A deploy that is wrongly deferred costs a
27
+ * ten-minute wait; a deploy that is wrongly allowed kills a running turn.
28
+ */
29
+
30
+ /**
31
+ * How long every session's provider must have been silent before the daemon
32
+ * may be restarted (#8743). A working provider emits every few seconds, so the
33
+ * window holds a restart off across ordinary pauses; only a single silent
34
+ * stretch longer than the window (one long command that reports nothing) gets
35
+ * through, and then only when `isBusy` is wrong too. Shorter than the deploy
36
+ * tick, so a quiet daemon still deploys on the next tick or the one after.
37
+ */
38
+ export const PROVIDER_QUIET_WINDOW_MS = 5 * 60 * 1000
39
+
40
+ /**
41
+ * @param {object} input
42
+ * @param {object|null|undefined} input.sessionManager - exposes listSessions()
43
+ * and getSession(id).
44
+ * @param {() => number} [input.getHookPendingPermissionCount] - hook-routed
45
+ * requests parked on the daemon.
46
+ * @returns {{ idle: boolean, reasons: string[], sessions: object[], hookPendingPermissions: number }}
47
+ */
48
+ export function computeDaemonIdleState({ sessionManager, getHookPendingPermissionCount } = {}) {
49
+ const reasons = []
50
+ const sessions = []
51
+ let hookPendingPermissions = 0
52
+
53
+ if (!sessionManager || typeof sessionManager.listSessions !== 'function') {
54
+ reasons.push('idle state unavailable: no session manager')
55
+ return { idle: false, reasons, sessions, hookPendingPermissions }
56
+ }
57
+
58
+ let rows
59
+ try {
60
+ rows = sessionManager.listSessions()
61
+ if (!Array.isArray(rows)) throw new Error('listSessions() did not return an array')
62
+ } catch (err) {
63
+ reasons.push(`idle state unavailable: ${err?.message || String(err)}`)
64
+ return { idle: false, reasons, sessions, hookPendingPermissions }
65
+ }
66
+
67
+ for (const row of rows) {
68
+ const sessionId = row?.sessionId
69
+ const label = row?.name ? `"${row.name}"` : String(sessionId)
70
+ let pendingPermissions = 0
71
+ let pendingQuestions = 0
72
+ let restartBlockers = []
73
+ let providerActivityAgeMs = null
74
+ try {
75
+ const entrySession = sessionManager.getSession?.(sessionId)?.session
76
+ if (!entrySession) {
77
+ // A row with no live session behind it cannot be inspected.
78
+ throw new Error(`session ${label} not inspectable`)
79
+ }
80
+ pendingPermissions = countPending(entrySession, 'pending permission count', () => entrySession.getPendingPermissionCount())
81
+ pendingQuestions = countPending(entrySession, 'pending question count', () => entrySession.getPendingQuestions().length)
82
+ restartBlockers = readBlockers(entrySession)
83
+ providerActivityAgeMs = readActivityAge(entrySession)
84
+ } catch (err) {
85
+ reasons.push(`idle state unavailable for session ${label}: ${err?.message || String(err)}`)
86
+ pendingPermissions = 0
87
+ pendingQuestions = 0
88
+ restartBlockers = []
89
+ providerActivityAgeMs = null
90
+ }
91
+ const isBusy = row?.isBusy === true
92
+ sessions.push({
93
+ sessionId,
94
+ name: row?.name ?? null,
95
+ isBusy,
96
+ busyReason: row?.busyReason ?? null,
97
+ backgroundShellCount: Number.isSafeInteger(row?.backgroundShellCount) ? row.backgroundShellCount : 0,
98
+ pendingPermissions,
99
+ pendingQuestions,
100
+ restartBlockers,
101
+ providerActivityAgeMs,
102
+ })
103
+ if (isBusy) reasons.push(`session ${label} busy: ${row?.busyReason || 'turn'}`)
104
+ if (pendingPermissions > 0) reasons.push(`session ${label} has ${pendingPermissions} pending permission(s)`)
105
+ if (pendingQuestions > 0) reasons.push(`session ${label} has ${pendingQuestions} pending question(s)`)
106
+ for (const b of restartBlockers) reasons.push(`session ${label} restart blocked: ${b}`)
107
+ if (providerActivityAgeMs !== null && providerActivityAgeMs < PROVIDER_QUIET_WINDOW_MS) {
108
+ reasons.push(`session ${label} provider active ${Math.round(providerActivityAgeMs / 1000)}s ago (quiet window ${PROVIDER_QUIET_WINDOW_MS / 60000}m)`)
109
+ }
110
+ }
111
+
112
+ try {
113
+ const n = typeof getHookPendingPermissionCount === 'function' ? getHookPendingPermissionCount() : 0
114
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error('hook permission count is not a count')
115
+ hookPendingPermissions = n
116
+ if (n > 0) reasons.push(`${n} hook-routed permission request(s) pending`)
117
+ } catch (err) {
118
+ reasons.push(`idle state unavailable: ${err?.message || String(err)}`)
119
+ }
120
+
121
+ return { idle: reasons.length === 0, reasons, sessions, hookPendingPermissions }
122
+ }
123
+
124
+ // A provider that lacks the accessor is not "has none": it is "cannot say", and
125
+ // that reads as not idle. BaseSession carries both accessors, so a missing one
126
+ // means a stub or custom provider we cannot vouch for.
127
+ function countPending(session, what, read) {
128
+ let n
129
+ try {
130
+ n = read()
131
+ } catch (err) {
132
+ throw new Error(`${what} unavailable (${err?.message || String(err)})`)
133
+ }
134
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error(`${what} is not a count`)
135
+ return n
136
+ }
137
+
138
+ // `getRestartBlockers()` is the one accessor whose EMPTY result means "safe", so
139
+ // every shape that is not a clean array of strings is "cannot say" (fail
140
+ // closed), exactly like the counts above: a missing method, a throw, or a
141
+ // non-array. Entries are not shape-checked: any entry at all becomes a pushed
142
+ // reason string, which already forces `idle: false`, so such a check could not
143
+ // change a verdict.
144
+ function readBlockers(session) {
145
+ if (typeof session.getRestartBlockers !== 'function') {
146
+ throw new Error('restart blockers unavailable (no getRestartBlockers)')
147
+ }
148
+ let out
149
+ try {
150
+ out = session.getRestartBlockers()
151
+ } catch (err) {
152
+ throw new Error(`restart blockers unavailable (${err?.message || String(err)})`)
153
+ }
154
+ if (!Array.isArray(out)) throw new Error('restart blockers is not an array')
155
+ return out.map(String)
156
+ }
157
+
158
+ // `providerActivityAgeMs` is null for "never active", which is safe, so like the
159
+ // blockers every other shape is "cannot say": a missing getter (undefined), a
160
+ // throw, NaN, a negative or fractional number.
161
+ function readActivityAge(session) {
162
+ let age
163
+ try {
164
+ age = session.providerActivityAgeMs
165
+ } catch (err) {
166
+ throw new Error(`provider activity unavailable (${err?.message || String(err)})`)
167
+ }
168
+ if (age === null) return null
169
+ if (!Number.isSafeInteger(age) || age < 0) throw new Error('provider activity age is not a duration')
170
+ return age
171
+ }
@@ -0,0 +1,314 @@
1
+ /**
2
+ * The daily daemon's pending-update status, and the two files the dashboard
3
+ * writes to steer it (#8331, follows #8324).
4
+ *
5
+ * `scripts/deploy-daemon.mjs` (run by launchd) keeps the daemon on the latest
6
+ * `main` and restarts it only when idle. It leaves four small JSON files in the
7
+ * config dir, and this module is the daemon's side of them:
8
+ *
9
+ * pending-update.json script -> us a forward deploy is waiting (busy / unknown / postponed)
10
+ * last-deploy.json script -> us the result of the last attempt
11
+ * deploy-postpone.json us -> script "do not deploy <target> before <until>"
12
+ * deploy-request.json us -> script "restart now" (force = the owner confirmed busy sessions)
13
+ *
14
+ * What lives here: reading those files into ONE wire-shaped status
15
+ * (`daemon_update_status`), watching them so the dashboard hears about a change
16
+ * without polling, and writing the two request files. What does NOT live here:
17
+ * who may ask (handlers/daemon-update-handlers.js gates on the strict primary
18
+ * token), the idle verdict (daemon-idle-state.js, the SAME function
19
+ * /api/daemon/idle answers from), and the deploy decision itself (the script,
20
+ * which re-checks everything under its own lock).
21
+ *
22
+ * EVERY file is untrusted input. They sit in a directory other local processes
23
+ * can write, so each read is size-capped (never reads past MAX_FILE_BYTES) and
24
+ * shape-validated, and anything malformed reads as ABSENT, never as a partial
25
+ * object. A status the dashboard cannot trust is worse than no status.
26
+ */
27
+
28
+ import { EventEmitter } from 'node:events'
29
+ import { randomBytes } from 'node:crypto'
30
+ import { SMALL_FILE_CAP, readBoundedJson, writeFileAtomic } from './utils/small-file.js'
31
+ import {
32
+ REQUEST_TTL_MS, REQUEST_SKEW_MS, POSTPONE_MS, POSTPONE_MAX_MS,
33
+ isSha, isIso, canonIso, parseRequest, parsePostpone, isRequestFresh, isApplyingFresh,
34
+ } from './utils/deploy-control-files.js'
35
+ import { mkdirSync, unlinkSync, watch as fsWatch } from 'node:fs'
36
+ import { join } from 'node:path'
37
+ import { configDir } from './config-dir.js'
38
+ import { DAEMON_COMMIT } from './daemon-commit.js'
39
+ import { PROVIDER_QUIET_WINDOW_MS } from './daemon-idle-state.js'
40
+ import { createLogger } from './logger.js'
41
+
42
+ const log = createLogger('daemon-update')
43
+
44
+ // These names and the TTL are the script's contract. tests/daemon-update-status.test.js
45
+ // imports scripts/deploy-daemon.mjs and asserts they are equal, so a rename on
46
+ // one side fails a test rather than silently disconnecting the banner.
47
+ export const PENDING_FILE = 'pending-update.json'
48
+ export const LAST_DEPLOY_FILE = 'last-deploy.json'
49
+ export const POSTPONE_FILE = 'deploy-postpone.json'
50
+ export const REQUEST_FILE = 'deploy-request.json'
51
+ // The parsing rules and these bounds live in utils/deploy-control-files.js, the ONE copy the
52
+ // script imports too; re-exported so callers keep importing them from here.
53
+ export { REQUEST_TTL_MS, REQUEST_SKEW_MS, POSTPONE_MS, POSTPONE_MAX_MS }
54
+ const WATCHED = new Set([PENDING_FILE, LAST_DEPLOY_FILE, POSTPONE_FILE, REQUEST_FILE])
55
+
56
+ /** Every file here is a few hundred bytes. A bigger one is not ours. */
57
+ export const MAX_FILE_BYTES = SMALL_FILE_CAP
58
+ const SUBJECT_MAX = 200
59
+ // `applying` is the script's own state: a forward deploy has passed its gates and is building / restarting.
60
+ const PENDING_REASONS = new Set(['busy', 'unknown', 'postponed', 'applying'])
61
+
62
+ const clip = (v, n) => String(v).slice(0, n)
63
+
64
+ /**
65
+ * Read a small JSON object: bounded, regular files only, never following a
66
+ * symlink or blocking on a FIFO (see utils/small-file.js).
67
+ * -> the parsed object, or null when absent, refused, oversized, unparseable or not an object.
68
+ */
69
+ export function readCappedJson(file) {
70
+ const r = readBoundedJson(file)
71
+ return r.state === 'ok' ? r.value : null
72
+ }
73
+
74
+ function parsePending(v, now) {
75
+ if (!v || !isSha(v.target) || !isIso(v.queuedAt)) return null
76
+ return {
77
+ target: v.target.toLowerCase(),
78
+ from: isSha(v.from) ? v.from.toLowerCase() : null,
79
+ subject: typeof v.subject === 'string' ? clip(v.subject, SUBJECT_MAX) : '',
80
+ commitsAhead: Number.isSafeInteger(v.commitsAhead) && v.commitsAhead >= 0 ? v.commitsAhead : null,
81
+ queuedAt: canonIso(v.queuedAt),
82
+ // A stale `applying` (no usable applyingSince, or older than APPLYING_MAX_MS) is what a
83
+ // crashed tick leaves behind, not live work: read it as the state before it, "busy",
84
+ // so the buttons come back instead of the banner claiming a restart that is not happening.
85
+ reason: v.reason === 'applying'
86
+ ? (isApplyingFresh(v.applyingSince, now) ? 'applying' : 'busy')
87
+ : (PENDING_REASONS.has(v.reason) ? v.reason : 'unknown'),
88
+ }
89
+ }
90
+
91
+ function parseLastDeploy(v) {
92
+ if (!v || !isSha(v.to) || !isIso(v.at) || typeof v.result !== 'string' || v.result.length === 0) return null
93
+ return {
94
+ from: isSha(v.from) ? v.from.toLowerCase() : null,
95
+ to: v.to.toLowerCase(),
96
+ at: canonIso(v.at),
97
+ result: clip(v.result, 64),
98
+ subject: typeof v.subject === 'string' ? clip(v.subject, SUBJECT_MAX) : '',
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Build the `daemon_update_status` payload from the four files.
104
+ * @param {object} o
105
+ * @param {string} o.dir
106
+ * @param {string|null} o.running - the commit this process started from
107
+ * @param {number} o.now
108
+ */
109
+ export function buildDaemonUpdateStatus({ dir, running, now }) {
110
+ const queued = parsePending(readCappedJson(join(dir, PENDING_FILE)), now)
111
+ const lastDeploy = parseLastDeploy(readCappedJson(join(dir, LAST_DEPLOY_FILE)))
112
+ const postpone = parsePostpone(readCappedJson(join(dir, POSTPONE_FILE)), now)
113
+ const request = parseRequest(readCappedJson(join(dir, REQUEST_FILE)))
114
+ const runningSha = isSha(running) ? running.toLowerCase() : null
115
+ // The banner is for an update THIS daemon is waiting on: the target is not what it
116
+ // already runs, and the queued update was queued FROM what it runs. A different
117
+ // process sharing the config dir (a dev server on another commit) reads as "no
118
+ // pending update", as does a daemon that cannot say what it runs.
119
+ const pending = queued && runningSha !== null && queued.target !== runningSha && queued.from === runningSha ? queued : null
120
+ // A postpone or a request only means something for the update that is waiting.
121
+ const postponedUntil = pending && postpone && postpone.target === pending.target && Date.parse(postpone.until) > now
122
+ ? postpone.until
123
+ : null
124
+ const requestPending = Boolean(pending && request && request.target === pending.target && isRequestFresh(request, now))
125
+ return {
126
+ running: runningSha,
127
+ pending,
128
+ lastDeploy,
129
+ postponedUntil,
130
+ requestPending,
131
+ applying: pending !== null && pending.reason === 'applying',
132
+ }
133
+ }
134
+
135
+ // Atomic and race-safe: random temp name opened O_EXCL, written through the
136
+ // descriptor, renamed into place (utils/small-file.js). A reader sees the old
137
+ // file or the new one, never half of either.
138
+ const writeJsonAtomic = (file, value) => writeFileAtomic(file, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 })
139
+
140
+ /** What the confirm dialog shows: the idle verdict's own words, bounded. */
141
+ function busySummary(idle) {
142
+ const reasons = (Array.isArray(idle?.reasons) ? idle.reasons : []).slice(0, 50).map((r) => clip(r, 300))
143
+ const sessions = (Array.isArray(idle?.sessions) ? idle.sessions : [])
144
+ .filter((s) => s && (s.isBusy === true || s.pendingPermissions > 0 || s.pendingQuestions > 0 || (Array.isArray(s.restartBlockers) && s.restartBlockers.length > 0)
145
+ // #8743: a provider still producing output holds the restart off on its own
146
+ || (Number.isSafeInteger(s.providerActivityAgeMs) && s.providerActivityAgeMs >= 0 && s.providerActivityAgeMs < PROVIDER_QUIET_WINDOW_MS)))
147
+ .slice(0, 50)
148
+ .map((s) => ({
149
+ sessionId: clip(s.sessionId ?? '', 128),
150
+ name: s.name ? clip(s.name, 200) : null,
151
+ busyReason: s.busyReason ? clip(s.busyReason, 200) : null,
152
+ }))
153
+ return { reasons, sessions }
154
+ }
155
+
156
+ export class DaemonUpdateStatus extends EventEmitter {
157
+ /**
158
+ * @param {object} [o]
159
+ * @param {string} [o.dir] - the config dir (default: the server's own)
160
+ * @param {string|null} [o.running] - commit this process runs (default DAEMON_COMMIT)
161
+ * @param {() => object} [o.getIdleState] - the daemon-idle-state verdict. Missing or throwing reads as NOT idle.
162
+ * @param {() => number} [o.now]
163
+ * @param {number} [o.debounceMs]
164
+ * @param {number} [o.pollMs] - fallback poll; fs.watch drops events on some filesystems
165
+ * @param {Function} [o.watch] - fs.watch seam
166
+ */
167
+ constructor({ dir, running = DAEMON_COMMIT, getIdleState = null, now = Date.now, debounceMs = 150, pollMs = 60_000, watch = fsWatch } = {}) {
168
+ super()
169
+ this._dir = dir ?? configDir()
170
+ this._running = running
171
+ this._getIdleState = getIdleState
172
+ this._now = now
173
+ this._debounceMs = debounceMs
174
+ this._pollMs = pollMs
175
+ this._watch = watch
176
+ this._watcher = null
177
+ this._pollTimer = null
178
+ this._debounceTimer = null
179
+ this._last = null
180
+ this._closed = false
181
+ }
182
+
183
+ /** The current status, read fresh from disk. */
184
+ getStatus() {
185
+ return buildDaemonUpdateStatus({ dir: this._dir, running: this._running, now: this._now() })
186
+ }
187
+
188
+ start() {
189
+ if (this._closed || this._pollTimer) return
190
+ this._last = JSON.stringify(this.getStatus())
191
+ try {
192
+ this._watcher = this._watch(this._dir, { persistent: false }, (_event, name) => {
193
+ if (name == null || WATCHED.has(String(name))) this._schedule()
194
+ })
195
+ this._watcher.on?.('error', (err) => log.warn(`config-dir watch error: ${err?.message || err}`))
196
+ } catch (err) {
197
+ // No watch (a missing dir, an unsupported filesystem): the poll still delivers.
198
+ log.warn(`cannot watch ${this._dir}: ${err?.message || err}`)
199
+ this._watcher = null
200
+ }
201
+ this._pollTimer = setInterval(() => this._check(), this._pollMs)
202
+ this._pollTimer.unref?.()
203
+ }
204
+
205
+ close() {
206
+ this._closed = true
207
+ clearTimeout(this._debounceTimer)
208
+ clearInterval(this._pollTimer)
209
+ this._debounceTimer = null
210
+ this._pollTimer = null
211
+ try { this._watcher?.close() } catch { /* already closed */ }
212
+ this._watcher = null
213
+ this.removeAllListeners()
214
+ }
215
+
216
+ /** Re-read now and emit `change` if the status differs from the last one emitted. */
217
+ refresh() {
218
+ clearTimeout(this._debounceTimer)
219
+ this._debounceTimer = null
220
+ this._check()
221
+ }
222
+
223
+ _schedule() {
224
+ if (this._closed) return
225
+ clearTimeout(this._debounceTimer)
226
+ this._debounceTimer = setTimeout(() => this._check(), this._debounceMs)
227
+ this._debounceTimer.unref?.()
228
+ }
229
+
230
+ _check() {
231
+ if (this._closed) return
232
+ let status
233
+ try { status = this.getStatus() } catch (err) { log.warn(`status read failed: ${err?.message || err}`); return }
234
+ const key = JSON.stringify(status)
235
+ if (key === this._last) return
236
+ this._last = key
237
+ this.emit('change', status)
238
+ }
239
+
240
+ // ---- actions (the caller has ALREADY authorised the requester) ----------
241
+
242
+ _pendingFor(target) {
243
+ const { pending } = this.getStatus()
244
+ if (!pending) return { error: { ok: false, code: 'NO_PENDING_UPDATE', message: 'There is no update waiting.' } }
245
+ // Once the script is building / restarting, neither button can take effect.
246
+ if (pending.reason === 'applying') return { error: { ok: false, code: 'APPLYING', message: 'The update is already being applied.' } }
247
+ if (typeof target !== 'string' || pending.target !== target.toLowerCase()) {
248
+ return { error: { ok: false, code: 'STALE_TARGET', message: 'That update is no longer the one waiting.' } }
249
+ }
250
+ return { pending }
251
+ }
252
+
253
+ /**
254
+ * Ask the deploy script to apply the waiting update now.
255
+ *
256
+ * `force` is computed HERE from the idle verdict and never taken from the
257
+ * client: a client can say it confirmed, not that the daemon is idle. A verdict
258
+ * that is missing, throws, or is anything but exactly `idle: true` is busy.
259
+ *
260
+ * -> { ok: true, force }
261
+ * | { ok: false, confirmRequired: true, reasons, sessions }
262
+ * | { ok: false, code, message }
263
+ */
264
+ requestRestart({ target, confirmBusy = false }) {
265
+ const checked = this._pendingFor(target)
266
+ if (checked.error) return checked.error
267
+ let idle
268
+ try { idle = typeof this._getIdleState === 'function' ? this._getIdleState() : null } catch (err) {
269
+ idle = { idle: false, reasons: [`idle state unavailable: ${err?.message || String(err)}`], sessions: [] }
270
+ }
271
+ const isIdle = idle?.idle === true
272
+ if (!isIdle && confirmBusy !== true) {
273
+ return { ok: false, confirmRequired: true, target: checked.pending.target, ...busySummary(idle) }
274
+ }
275
+ const force = !isIdle
276
+ try {
277
+ mkdirSync(this._dir, { recursive: true })
278
+ writeJsonAtomic(join(this._dir, REQUEST_FILE), {
279
+ action: 'restart-now',
280
+ target: checked.pending.target,
281
+ force,
282
+ requestedAt: new Date(this._now()).toISOString(),
283
+ nonce: randomBytes(8).toString('hex'),
284
+ })
285
+ } catch (err) {
286
+ log.warn(`cannot write ${REQUEST_FILE}: ${err?.message || err}`)
287
+ return { ok: false, code: 'WRITE_FAILED', message: 'Could not write the restart request.' }
288
+ }
289
+ // A restart request outranks a postpone; remove it so the banner agrees with the script.
290
+ try { unlinkSync(join(this._dir, POSTPONE_FILE)) } catch { /* none */ }
291
+ this.refresh()
292
+ return { ok: true, force }
293
+ }
294
+
295
+ /** Hold the waiting update off for an hour. -> { ok: true, until } | { ok: false, code, message } */
296
+ postpone({ target, ms = POSTPONE_MS }) {
297
+ const checked = this._pendingFor(target)
298
+ if (checked.error) return checked.error
299
+ const until = new Date(this._now() + ms).toISOString()
300
+ try {
301
+ mkdirSync(this._dir, { recursive: true })
302
+ writeJsonAtomic(join(this._dir, POSTPONE_FILE), {
303
+ target: checked.pending.target,
304
+ until,
305
+ requestedAt: new Date(this._now()).toISOString(),
306
+ })
307
+ } catch (err) {
308
+ log.warn(`cannot write ${POSTPONE_FILE}: ${err?.message || err}`)
309
+ return { ok: false, code: 'WRITE_FAILED', message: 'Could not write the postpone.' }
310
+ }
311
+ this.refresh()
312
+ return { ok: true, until }
313
+ }
314
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The identity of the dashboard bundle this daemon serves (#8268).
3
+ *
4
+ * A long-lived dashboard tab (the desktop window, a browser tab) keeps running the
5
+ * bundle it loaded even after the daemon is updated and restarted underneath it, and
6
+ * its header reads the SERVER's version, which hides the staleness. The client needs
7
+ * something to compare its own bundle against, and the package version is not enough:
8
+ * a rebuilt `dist` at the same version (a dev rebuild, a hotfix that did not bump)
9
+ * changes the code and not the number.
10
+ *
11
+ * The id is a hash of the built `index.html`. Vite names every JS and CSS asset by
12
+ * content hash and `index.html` references the entry chunks by those names, so any
13
+ * change to the shipped code changes the file, and nothing else does.
14
+ *
15
+ * Two places use it, and they must agree byte for byte:
16
+ * - `http-routes.js` injects it into the served HTML as `<meta name="chroxy-build">`,
17
+ * which is the id of the bundle THIS page loaded;
18
+ * - `ws-history.js` sends it in `auth_ok`, which is the id of the bundle the daemon
19
+ * serves NOW.
20
+ * The client compares the two on connect.
21
+ */
22
+ import { createHash } from 'crypto'
23
+ import { existsSync, readFileSync, statSync } from 'fs'
24
+ import { dirname, join } from 'path'
25
+ import { fileURLToPath } from 'url'
26
+
27
+ const __dirname = dirname(fileURLToPath(import.meta.url))
28
+
29
+ /**
30
+ * Where the built dashboard lives: the workspace build (dev), else the copy the
31
+ * Tauri bundle ships next to the server. The same choice the HTTP route makes, so
32
+ * the id describes the files that are actually served.
33
+ */
34
+ export function resolveDashboardDist() {
35
+ const workspaceDist = join(__dirname, '..', '..', 'dashboard', 'dist')
36
+ const bundleDist = join(__dirname, 'dashboard-next', 'dist')
37
+ return existsSync(workspaceDist) ? workspaceDist : bundleDist
38
+ }
39
+
40
+ /** The build id of an `index.html` document (before any per-request injection). */
41
+ export function dashboardBuildIdOf(html) {
42
+ return createHash('sha256').update(html).digest('hex').slice(0, 16)
43
+ }
44
+
45
+ // Keyed by the file's identity so a rebuilt `dist` is picked up on the next
46
+ // auth_ok with no daemon restart, while the common case (an unchanged file)
47
+ // costs one stat and no read.
48
+ let cache = { path: null, mtimeMs: -1, size: -1, id: null }
49
+
50
+ /**
51
+ * The id of the dashboard currently on disk, or null when there is none (an
52
+ * unbuilt checkout, a headless install). Null means "cannot say", never "equal":
53
+ * the client treats it as no signal and falls back to comparing versions.
54
+ *
55
+ * @param {string} [distDir] - override for tests
56
+ */
57
+ export function getDashboardBuildId(distDir = resolveDashboardDist()) {
58
+ const indexPath = join(distDir, 'index.html')
59
+ try {
60
+ const st = statSync(indexPath)
61
+ if (cache.path === indexPath && cache.mtimeMs === st.mtimeMs && cache.size === st.size && cache.id) {
62
+ return cache.id
63
+ }
64
+ const id = dashboardBuildIdOf(readFileSync(indexPath, 'utf-8'))
65
+ cache = { path: indexPath, mtimeMs: st.mtimeMs, size: st.size, id }
66
+ return id
67
+ } catch {
68
+ return null
69
+ }
70
+ }
@@ -0,0 +1,90 @@
1
+ /** Pure extraction from one COMPLETED assistant response; never called on deltas. */
2
+ export const MAX_DECLARATION_MESSAGE_CHARS = 131072
3
+ const STATES = new Set(['running', 'idle', 'blocked', 'stalled', 'done'])
4
+ const TOKENS = { '🟢': 'running', '⚪': 'idle', '🔴': 'blocked', '🟠': 'stalled' }
5
+ const compact = (value) => value.replace(/\s+/g, ' ').trim().slice(0, 280)
6
+ // Unwrap only structural labels. Payload underscores/asterisks are literal.
7
+ const plain = (value) => value.trim()
8
+ .replace(/^(\*\*|__)(Status|Next|DECISION)\s*:\1/i, '$2:')
9
+ .replace(/^(\*\*|__)(Status|Next|DECISION)\1\s*:/i, '$2:')
10
+
11
+ function introducesExampleOrHistory(line) {
12
+ const text = line.replace(/^#{1,6}\s*/, '').trim()
13
+ return /^(?:(?:for\s+)?(?:example|sample|template|format|quoted|literal)(?:\s+(?:footer|status|output|declaration|block))?\s*:)/i.test(text)
14
+ || /^(?:here(?: is|'s)|the following is)\b.*\b(?:example|sample|quoted|literal)\b.*:\s*$/i.test(text)
15
+ || /^(?:(?:the|this|an?)\s+|here is (?:the )?)?(?:previous|earlier|old|prior|historical|last)\s+(?:assistant\s+)?(?:response|message|output|footer|status|declaration)\b[^.!?]*:\s*$/i.test(text)
16
+ || /^(?:previously|earlier)\s*:\s*$/i.test(text)
17
+ }
18
+
19
+ function nextDeclaration(line) {
20
+ const match = /^Next\s*:\s*(\S+)\s*(.*)$/i.exec(line)
21
+ if (!match) return null
22
+ // Accept the established token spelling with or without a space after glyph.
23
+ const token = /^(🟢|⚪|🔴|🟠)\s*(RUNNING|IDLE|BLOCKED|FAILED)\b\s*(?:[—–-]\s*)?(.*)$/i.exec(`${match[1]} ${match[2]}`)
24
+ if (token && TOKENS[token[1]] && ({ '🟢': 'RUNNING', '⚪': 'IDLE', '🔴': 'BLOCKED', '🟠': 'FAILED' })[token[1]] === token[2].toUpperCase()) {
25
+ return { state: TOKENS[token[1]], next: compact(token[3]) }
26
+ }
27
+ return { state: 'unknown', next: compact(`${match[1]} ${match[2]}`) }
28
+ }
29
+
30
+ export function extractDeclaredStatus(text) {
31
+ if (typeof text !== 'string' || text.length > MAX_DECLARATION_MESSAGE_CHARS) return null
32
+ const lines = text.replace(/\r\n?/g, '\n').split('\n')
33
+ let fence = null
34
+ const eligible = lines.map((line) => {
35
+ const boundary = /^\s{0,3}(`{3,}|~{3,})/.exec(line)
36
+ if (boundary) {
37
+ if (!fence) fence = boundary[1]
38
+ else if (boundary[1][0] === fence[0] && boundary[1].length >= fence.length) fence = null
39
+ return null
40
+ }
41
+ if (fence || /^\s*>|^(?: {4}|\t)/.test(line)) return null
42
+ return plain(line)
43
+ })
44
+ let end = lines.length - 1
45
+ while (end >= 0 && !lines[end].trim()) end--
46
+ if (end < 0 || !eligible[end]) return null
47
+ // Only a declaration at the tail is current. Quoted examples, explanatory
48
+ // prose after a block, and earlier declarations cannot replace live intent.
49
+ const next = nextDeclaration(eligible[end])
50
+ let start = end
51
+ while (start >= 0 && !/^Status\s*:\s*$/i.test(eligible[start] || '')) start--
52
+ const exampleBefore = (index) => {
53
+ let previous = index - 1
54
+ while (previous >= 0 && !lines[previous].trim()) previous--
55
+ return previous >= 0 && introducesExampleOrHistory(eligible[previous] || '')
56
+ }
57
+ if (next && start >= 0) {
58
+ if (exampleBefore(start)) return null
59
+ const rows = eligible.slice(start + 1, end).filter((line) => line !== '')
60
+ // In-flight enumeration child rows may be indented Markdown bullets. They
61
+ // aren't declarations themselves and may appear only after the 🔄 slot.
62
+ const slots = []
63
+ let current = -1
64
+ for (let index = start + 1; index < end; index++) {
65
+ if (!lines[index].trim()) continue
66
+ const line = eligible[index]
67
+ const slot = line && /^[-*+]\s+(✅|🔄|⛔|🔶)\s+(.+)$/.exec(line)
68
+ if (slot) { slots.push(slot); current++ }
69
+ else if (!(current === 1 && /^\s{2,}[-*+]\s+\S/.test(lines[index]))) return null
70
+ }
71
+ if (rows.length < 4 || slots.map((slot) => slot[1]).join('') !== '✅🔄⛔🔶') return null
72
+ const decision = /^DECISION\s*:\s*(.+)$/i.exec(plain(slots[3][2]))
73
+ if (!decision || !decision[1].trim() || !next.next) return null
74
+ return {
75
+ state: next.state,
76
+ summary: compact(slots[0][2]),
77
+ next: next.next,
78
+ ...(!/^none$/i.test(slots[2][2]) ? { blockedOn: compact(slots[2][2]) } : {}),
79
+ decision: compact(decision[1]),
80
+ }
81
+ }
82
+ if (next) {
83
+ if (exampleBefore(end) || !next.next) return null
84
+ return { ...next, summary: next.next }
85
+ }
86
+ const marker = /^\[chroxy-status\]\s+(running|idle|blocked|stalled|done)\s*:\s*(\S.*)$/i.exec(eligible[end])
87
+ if (!marker || exampleBefore(end)) return null
88
+ const state = marker[1].toLowerCase()
89
+ return STATES.has(state) ? { state, summary: compact(marker[2]) } : null
90
+ }
@@ -19,15 +19,14 @@
19
19
  * DeepSeek `sk-` prefix overlaps with many other key formats so it isn't
20
20
  * special-cased there — masking at the use site is the defense.
21
21
  */
22
- import { join } from 'path'
23
- import { homedir } from 'os'
24
22
  import { maskApiKey } from './byok-credentials.js'
25
23
  import { readCredentialJsonField } from './credentials-file.js'
24
+ import { configPath } from './config-dir.js'
26
25
 
27
26
  // Lazy-resolved per call so tests that mutate process.env.HOME between
28
27
  // cases pick up the new home (same rationale as byok-credentials.js).
29
28
  function credentialsFilePath() {
30
- return join(homedir(), '.chroxy', 'credentials.json')
29
+ return configPath('credentials.json')
31
30
  }
32
31
 
33
32
  /**