@chroxy/server 0.11.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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  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 +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  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 +69 -5
  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 +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -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
  /**