@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
package/src/service.js CHANGED
@@ -1,12 +1,15 @@
1
1
  import { homedir, platform } from 'os'
2
- import { join, dirname, win32 as pathWin32 } from 'path'
3
- import { existsSync, readFileSync, mkdirSync, unlinkSync, readdirSync, writeFileSync, chmodSync } from 'fs'
2
+ import { join, dirname, resolve, win32 as pathWin32 } from 'path'
3
+ import { existsSync, readFileSync, mkdirSync, unlinkSync, readdirSync, writeFileSync, chmodSync, realpathSync, statSync } from 'fs'
4
4
  import { writeFileRestricted, isWindows } from './platform.js'
5
5
  import { execFileSync } from 'child_process'
6
6
  import { fileURLToPath } from 'url'
7
+ import { configDir, configPath } from './config-dir.js'
7
8
 
8
9
  const SERVICE_LABEL = 'com.chroxy.server'
9
- const DEFAULT_CONFIG_DIR = join(homedir(), '.chroxy')
10
+ function defaultConfigDir() {
11
+ return configDir()
12
+ }
10
13
  const WRAPPER_NAME = 'service-wrapper.sh'
11
14
  // Windows Task Scheduler autostart (#6647). The task name the daemon registers
12
15
  // under, and the .cmd wrapper it runs (the Windows analogue of WRAPPER_NAME).
@@ -41,7 +44,7 @@ function escapeXml(str) {
41
44
  * @param {string} [plat] - Override platform (defaults to process.platform)
42
45
  */
43
46
  export function getServicePaths(plat = platform()) {
44
- const logDir = join(homedir(), '.chroxy', 'logs')
47
+ const logDir = configPath('logs')
45
48
 
46
49
  if (plat === 'darwin') {
47
50
  return {
@@ -72,6 +75,28 @@ export function getServicePaths(plat = platform()) {
72
75
  /**
73
76
  * Generate a macOS launchd plist XML string.
74
77
  */
78
+ /**
79
+ * The config root to bake into a generated service definition, or null.
80
+ *
81
+ * launchd's `EnvironmentVariables` dict and systemd's `Environment=` lines are
82
+ * the daemon's ENTIRE environment — neither inherits the shell that ran
83
+ * `chroxy service install`. Since #7052 every path the installer resolves
84
+ * (logDir, service.json, the wrapper) follows CHROXY_CONFIG_DIR, so omitting it
85
+ * here would start a daemon whose logs land in the relocated root while its
86
+ * state goes to ~/.chroxy: the same split-brain #7052 exists to remove, moved
87
+ * to the service boundary, and one the operator cannot fix from their shell.
88
+ *
89
+ * Emitted only when set, so a default install produces a byte-identical
90
+ * definition to before. Injectable for tests.
91
+ *
92
+ * @param {object} config
93
+ * @returns {string|null}
94
+ */
95
+ function serviceConfigDirEnv(config) {
96
+ const raw = config?.configDirEnv !== undefined ? config.configDirEnv : process.env.CHROXY_CONFIG_DIR
97
+ return typeof raw === 'string' && raw.trim() ? raw : null
98
+ }
99
+
75
100
  export function generateLaunchdPlist(config) {
76
101
  const {
77
102
  nodePath,
@@ -80,8 +105,9 @@ export function generateLaunchdPlist(config) {
80
105
  wrapperPath,
81
106
  cwd = homedir(),
82
107
  startAtLogin = false,
83
- logDir = join(homedir(), '.chroxy', 'logs'),
108
+ logDir = configPath('logs'),
84
109
  } = config
110
+ const configDirEnv = serviceConfigDirEnv(config)
85
111
 
86
112
  // Bake a PATH that includes the node and claude bin dirs so the daemon's
87
113
  // preflight finds both under launchd's bare default PATH (#5491).
@@ -120,7 +146,9 @@ ${programArgs}
120
146
  <key>PATH</key>
121
147
  <string>${escapeXml(pathValue)}</string>
122
148
  <key>CHROXY_DAEMON</key>
123
- <string>1</string>
149
+ <string>1</string>${configDirEnv ? `
150
+ <key>CHROXY_CONFIG_DIR</key>
151
+ <string>${escapeXml(configDirEnv)}</string>` : ''}
124
152
  </dict>
125
153
  </dict>
126
154
  </plist>
@@ -137,8 +165,9 @@ export function generateSystemdUnit(config) {
137
165
  claudeBin,
138
166
  wrapperPath,
139
167
  cwd = homedir(),
140
- logDir = join(homedir(), '.chroxy', 'logs'),
168
+ logDir = configPath('logs'),
141
169
  } = config
170
+ const configDirEnv = serviceConfigDirEnv(config)
142
171
 
143
172
  // Bake a PATH that includes the node and claude bin dirs for parity with the
144
173
  // launchd plist (#5491).
@@ -160,7 +189,8 @@ WorkingDirectory=${cwd}
160
189
  Restart=on-failure
161
190
  RestartSec=5
162
191
  Environment=PATH=${pathValue}
163
- Environment=CHROXY_DAEMON=1
192
+ Environment=CHROXY_DAEMON=1${configDirEnv ? `
193
+ Environment=CHROXY_CONFIG_DIR=${configDirEnv}` : ''}
164
194
  StandardOutput=file:${join(logDir, 'chroxy-stdout.log')}
165
195
  StandardError=file:${join(logDir, 'chroxy-stderr.log')}
166
196
 
@@ -223,8 +253,9 @@ export function generateWindowsServiceWrapper(config) {
223
253
  chroxyBin,
224
254
  claudeBin,
225
255
  cwd = homedir(),
226
- logDir = join(homedir(), '.chroxy', 'logs'),
256
+ logDir = configPath('logs'),
227
257
  } = config
258
+ const configDirEnv = serviceConfigDirEnv(config)
228
259
 
229
260
  // Use Windows path semantics regardless of host so the generated batch is
230
261
  // correct even when this runs on a POSIX CI runner under test (#6647).
@@ -252,6 +283,7 @@ export function generateWindowsServiceWrapper(config) {
252
283
  'rem `service install`; edits are lost.',
253
284
  `set "PATH=${pathPrepend};%PATH%"`,
254
285
  'set "CHROXY_DAEMON=1"',
286
+ ...(configDirEnv ? [`set "CHROXY_CONFIG_DIR=${configDirEnv}"`] : []),
255
287
  `cd /d "${cwd}"`,
256
288
  rotateCapture(stdoutLog, pathWin32.join(logDir, 'chroxy-stdout.old.log')),
257
289
  rotateCapture(stderrLog, pathWin32.join(logDir, 'chroxy-stderr.old.log')),
@@ -475,6 +507,7 @@ export function buildServicePath({ nodePath, claudeBin }) {
475
507
  */
476
508
  export function generateServiceWrapper(config) {
477
509
  const { nodePath, chroxyBin, pathValue } = config
510
+ const configDirEnv = serviceConfigDirEnv(config)
478
511
 
479
512
  const sh = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`
480
513
  const keychainBlock = ({ service, account, env }) => `
@@ -492,7 +525,8 @@ fi`
492
525
  set -e
493
526
 
494
527
  export PATH=${sh(pathValue)}
495
- export CHROXY_DAEMON=1
528
+ export CHROXY_DAEMON=1${configDirEnv ? `
529
+ export CHROXY_CONFIG_DIR=${sh(configDirEnv)}` : ''}
496
530
  ${keychainBlock(KEYCHAIN_API_TOKEN)}
497
531
  ${keychainBlock(KEYCHAIN_DISCORD_WEBHOOK)}
498
532
 
@@ -505,7 +539,7 @@ exec ${sh(nodePath)} ${sh(chroxyBin)} start
505
539
  * @param {string} [configDir] - Override config directory (for testing)
506
540
  * @returns {object|null}
507
541
  */
508
- export function loadServiceState(configDir = DEFAULT_CONFIG_DIR) {
542
+ export function loadServiceState(configDir = defaultConfigDir()) {
509
543
  const statePath = join(configDir, 'service.json')
510
544
  if (!existsSync(statePath)) {
511
545
  return null
@@ -522,7 +556,7 @@ export function loadServiceState(configDir = DEFAULT_CONFIG_DIR) {
522
556
  * @param {object} state
523
557
  * @param {string} [configDir] - Override config directory (for testing)
524
558
  */
525
- export function saveServiceState(state, configDir = DEFAULT_CONFIG_DIR) {
559
+ export function saveServiceState(state, configDir = defaultConfigDir()) {
526
560
  if (!existsSync(configDir)) {
527
561
  mkdirSync(configDir, { recursive: true })
528
562
  }
@@ -530,6 +564,254 @@ export function saveServiceState(state, configDir = DEFAULT_CONFIG_DIR) {
530
564
  writeFileRestricted(statePath, JSON.stringify(state, null, 2))
531
565
  }
532
566
 
567
+ /**
568
+ * Reverse the single-quote escaping `generateServiceWrapper` applies (`sh()`):
569
+ * split a shell line into words, honouring `'...'` and the `'\''` escape.
570
+ * Handles only what the wrapper emits; anything else yields null so a caller
571
+ * treats "cannot read it back" as a failure, never as a match.
572
+ */
573
+ function splitShWords(line) {
574
+ const words = []
575
+ let i = 0
576
+ while (i < line.length) {
577
+ if (line[i] === ' ') { i++; continue }
578
+ let word = ''
579
+ while (i < line.length && line[i] !== ' ') {
580
+ if (line[i] === "'") {
581
+ const end = line.indexOf("'", i + 1)
582
+ if (end === -1) return null
583
+ word += line.slice(i + 1, end)
584
+ i = end + 1
585
+ } else if (line[i] === '\\' && line[i + 1] === "'") {
586
+ word += "'"
587
+ i += 2
588
+ } else {
589
+ word += line[i]
590
+ i++
591
+ }
592
+ }
593
+ words.push(word)
594
+ }
595
+ return words
596
+ }
597
+
598
+ /**
599
+ * Read back what a POSIX service wrapper actually execs (#7161): the last
600
+ * `exec <node> <chroxyBin> start` line. This is the ground truth for "which
601
+ * working copy does launchd run" — service.json is only a record of it.
602
+ *
603
+ * @param {string} content - Wrapper script text.
604
+ * @returns {{ nodePath: string, chroxyBin: string } | null} null when no
605
+ * recognisable exec line is present (including a Windows .cmd wrapper).
606
+ */
607
+ export function parseWrapperExecTarget(content) {
608
+ const lines = String(content).split(/\r?\n/)
609
+ for (let i = lines.length - 1; i >= 0; i--) {
610
+ if (!lines[i].startsWith('exec ')) continue
611
+ const words = splitShWords(lines[i].slice(5))
612
+ if (words && words.length === 3 && words[2] === 'start') {
613
+ return { nodePath: words[0], chroxyBin: words[1] }
614
+ }
615
+ return null
616
+ }
617
+ return null
618
+ }
619
+
620
+ /**
621
+ * Report which tree an installed service points at, from both records.
622
+ * `installed` is true when ANY artifact exists (state, wrapper, or the
623
+ * launchd/systemd file) so a deleted service.json cannot make an existing
624
+ * service look absent (#7161).
625
+ *
626
+ * @param {object} [options]
627
+ * @param {string} [options._stateDir]
628
+ * @param {string} [options._wrapperPath]
629
+ * @param {string} [options._servicePath] - launchd plist / systemd unit
630
+ * @returns {{ installed: boolean, hasState: boolean, recordedBin: string|null, wrapperBin: string|null,
631
+ * wrapperPath: string, drift: boolean }}
632
+ */
633
+ export function inspectInstalledService(options = {}) {
634
+ const stateDir = options._stateDir || defaultConfigDir()
635
+ const state = loadServiceState(stateDir)
636
+ const wrapperPath = options._wrapperPath || state?.wrapperPath || join(stateDir, WRAPPER_NAME)
637
+ let wrapperBin = null
638
+ let wrapperPresent = false
639
+ if (existsSync(wrapperPath)) {
640
+ wrapperPresent = true
641
+ try {
642
+ wrapperBin = parseWrapperExecTarget(readFileSync(wrapperPath, 'utf-8'))?.chroxyBin ?? null
643
+ } catch {
644
+ wrapperBin = null
645
+ }
646
+ }
647
+ const recordedBin = state?.chroxyBin ?? null
648
+ const servicePresent = !!options._servicePath && existsSync(options._servicePath)
649
+ return {
650
+ installed: !!state || wrapperPresent || servicePresent,
651
+ // `chroxy service uninstall` needs service.json, so it only works when this is true.
652
+ hasState: !!state,
653
+ recordedBin,
654
+ wrapperBin,
655
+ wrapperPath,
656
+ // Only a disagreement between two values we could actually read counts.
657
+ drift: recordedBin !== null && wrapperBin !== null && recordedBin !== wrapperBin,
658
+ }
659
+ }
660
+
661
+ /**
662
+ * Refuse to silently re-point an existing service at another working copy
663
+ * (#7161). `resolveChroxyBin()` resolves relative to the invoking file, so
664
+ * running `chroxy service install` from any checkout would otherwise move the
665
+ * launchd job to that checkout. Reinstalling needs an explicit `force`, and
666
+ * the message names both trees.
667
+ *
668
+ * @param {object} args
669
+ * @param {string} args.chroxyBin - The target this invocation would install.
670
+ * @param {boolean} [args.force]
671
+ * @param {object} [args.inspect] - Options for inspectInstalledService.
672
+ * @returns {{ reinstall: boolean }} reinstall=true when force overrode an existing install.
673
+ * @throws {Error} code SERVICE_ALREADY_INSTALLED when installed and not forced.
674
+ */
675
+ export function assertReinstallAllowed({ chroxyBin, force = false, inspect = {} }) {
676
+ const found = inspectInstalledService(inspect)
677
+ if (!found.installed) return { reinstall: false }
678
+ if (force) return { reinstall: true }
679
+
680
+ const lines = ['Chroxy service is already installed.']
681
+ if (found.drift) {
682
+ lines.push(
683
+ 'Its two records disagree:',
684
+ ` service.json records: ${found.recordedBin}`,
685
+ ` wrapper actually execs: ${found.wrapperBin}`,
686
+ )
687
+ }
688
+ const current = found.wrapperBin || found.recordedBin
689
+ if (current && current !== chroxyBin) {
690
+ lines.push(
691
+ 'It is pinned to:',
692
+ ` ${current}`,
693
+ 'This install would re-point it at:',
694
+ ` ${chroxyBin}`,
695
+ )
696
+ } else if (current) {
697
+ lines.push(`It is pinned to this same tree: ${current}`)
698
+ } else {
699
+ lines.push('Its target tree could not be read from service.json or the wrapper.')
700
+ }
701
+ const moves = current && current !== chroxyBin
702
+ lines.push(
703
+ moves
704
+ ? `Re-run with --force to re-point it at ${chroxyBin} (the running daemon switches to that tree).`
705
+ : 'Re-run with --force to rewrite its wrapper and service definition and reload the job (same tree, nothing moves).',
706
+ )
707
+ lines.push(
708
+ found.hasState
709
+ ? 'Or run "chroxy service uninstall" first to remove it.'
710
+ : '"chroxy service uninstall" will not work here (service.json is missing); --force is the way to recover.',
711
+ )
712
+ const err = new Error(lines.join('\n'))
713
+ err.code = 'SERVICE_ALREADY_INSTALLED'
714
+ throw err
715
+ }
716
+
717
+ /**
718
+ * Does a package's `main` resolve the way Node's CJS/ESM-legacy loader does?
719
+ * The exact file, then with .js/.json/.node appended, then as a directory
720
+ * holding index.js/.json/.node. Written with or without a leading "./".
721
+ */
722
+ function resolvesAsFile(pkgDir, main) {
723
+ const isFile = (p) => {
724
+ try { return statSync(p).isFile() } catch { return false }
725
+ }
726
+ const base = resolve(pkgDir, main)
727
+ const exts = ['.js', '.json', '.node']
728
+ return isFile(base)
729
+ || exts.some((e) => isFile(base + e))
730
+ || exts.some((e) => isFile(join(base, 'index' + e)))
731
+ }
732
+
733
+ /**
734
+ * Offline check that the tree `chroxyBin` lives in can actually start (#7161).
735
+ * KeepAlive turns one missing dependency into an infinite respawn loop under
736
+ * launchd, so this fails the install instead. Reads package.json and stats
737
+ * files only — no network, no `npm`, a few milliseconds.
738
+ *
739
+ * For each runtime `dependencies` entry it requires `node_modules/<name>/package.json`
740
+ * to resolve by Node's walk-up rule (hoisting is honoured), and, when that
741
+ * package declares a relative `main`, that file to exist (an unbuilt workspace
742
+ * package has a link but no `dist/`). A tree whose package.json cannot be found
743
+ * is a failure, never a pass: "cannot check" must not read as "nothing to check".
744
+ *
745
+ * @param {string} chroxyBin
746
+ * @returns {{ root: string|null, problems: string[] }}
747
+ */
748
+ export function checkChroxyTree(chroxyBin) {
749
+ let real
750
+ try {
751
+ real = realpathSync(chroxyBin)
752
+ } catch {
753
+ return { root: null, problems: [`${chroxyBin} does not exist`] }
754
+ }
755
+ let root = dirname(real)
756
+ while (!existsSync(join(root, 'package.json'))) {
757
+ const parent = dirname(root)
758
+ if (parent === root) {
759
+ return { root: null, problems: [`no package.json found above ${real}, so its dependencies cannot be verified`] }
760
+ }
761
+ root = parent
762
+ }
763
+ let pkg
764
+ try {
765
+ pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8'))
766
+ } catch (err) {
767
+ return { root, problems: [`${join(root, 'package.json')} is unreadable: ${err.message}`] }
768
+ }
769
+ const deps = Object.keys(pkg.dependencies || {})
770
+ const problems = []
771
+ for (const name of deps) {
772
+ let dir = root
773
+ let found = null
774
+ for (;;) {
775
+ const candidate = join(dir, 'node_modules', name)
776
+ if (existsSync(join(candidate, 'package.json'))) { found = candidate; break }
777
+ const parent = dirname(dir)
778
+ if (parent === dir) break
779
+ dir = parent
780
+ }
781
+ if (!found) {
782
+ problems.push(`${name} is not installed`)
783
+ continue
784
+ }
785
+ try {
786
+ const main = JSON.parse(readFileSync(join(found, 'package.json'), 'utf-8')).main
787
+ if (typeof main === 'string' && main !== '' && !resolvesAsFile(found, main)) {
788
+ problems.push(`${name} is linked but its entry ${main} is missing (not built?)`)
789
+ }
790
+ } catch (err) {
791
+ problems.push(`${name} has an unreadable package.json: ${err.message}`)
792
+ }
793
+ }
794
+ return { root, problems }
795
+ }
796
+
797
+ /**
798
+ * Throw an actionable error when the target tree cannot start (see checkChroxyTree).
799
+ * @param {string} chroxyBin
800
+ */
801
+ export function assertChroxyTreeReady(chroxyBin) {
802
+ const { root, problems } = checkChroxyTree(chroxyBin)
803
+ if (problems.length === 0) return
804
+ const shown = problems.slice(0, 10).map((p) => ` - ${p}`)
805
+ if (problems.length > 10) shown.push(` - ...and ${problems.length - 10} more`)
806
+ const err = new Error(
807
+ `The chroxy tree at ${root || chroxyBin} cannot start, so installing the service would make launchd/systemd crash-loop:\n` +
808
+ `${shown.join('\n')}\n` +
809
+ `Run "npm install" in ${root || 'that tree'} (and build any workspace packages), then re-run "chroxy service install".`
810
+ )
811
+ err.code = 'SERVICE_TREE_NOT_READY'
812
+ throw err
813
+ }
814
+
533
815
  /**
534
816
  * Write the service wrapper script to disk with 0700 perms (owner rwx only).
535
817
  *
@@ -568,20 +850,43 @@ export function writeServiceWrapper(wrapperPath, content) {
568
850
  * @param {string} [config._stateDir] - Override state directory (testing)
569
851
  * @param {string} [config._wrapperPath] - Override wrapper script path (testing)
570
852
  * @param {boolean} [config._skipRegister] - Skip launchctl/systemctl registration (testing)
853
+ * @param {boolean} [config.force] - Re-point an already-installed service (#7161).
854
+ * Without it an existing install is never touched.
855
+ * @param {(cmd: string, args: string[], opts: object) => void} [config._exec]
856
+ * Injectable exec for testing (defaults to execFileSync).
857
+ * @param {Function} [config._generateWrapper] - Override the wrapper generator (testing the read-back check)
571
858
  * @param {string} [config._platform] - Override platform (testing)
572
859
  */
573
860
  export function installService(config) {
574
861
  const plat = config._platform || platform()
575
862
  const paths = getServicePaths(plat)
576
863
 
864
+ // #7161: refuse to silently re-point an existing service at the invoking tree.
865
+ // Runs before anything is written so a refusal leaves the install untouched.
866
+ const stateDirForGuard = config._stateDir || defaultConfigDir()
867
+ const hadState = !!loadServiceState(stateDirForGuard)
868
+ const { reinstall } = assertReinstallAllowed({
869
+ chroxyBin: config.chroxyBin,
870
+ force: config.force === true,
871
+ inspect: {
872
+ _stateDir: stateDirForGuard,
873
+ _wrapperPath: config._wrapperPath
874
+ || (plat === 'win32' ? join(stateDirForGuard, WINDOWS_WRAPPER_NAME) : undefined),
875
+ _servicePath: plat === 'win32'
876
+ ? undefined
877
+ : config._servicePath || (plat === 'darwin' ? paths.plistPath : paths.unitPath),
878
+ },
879
+ })
880
+
577
881
  if (plat === 'win32') {
578
- return installWindowsService(config, paths)
882
+ return installWindowsService(config, paths, reinstall)
579
883
  }
580
884
 
581
885
  const servicePath = config._servicePath || (plat === 'darwin' ? paths.plistPath : paths.unitPath)
582
886
  const logDir = config._logDir || paths.logDir
583
- const stateDir = config._stateDir || DEFAULT_CONFIG_DIR
887
+ const stateDir = stateDirForGuard
584
888
  const wrapperPath = config._wrapperPath || join(stateDir, WRAPPER_NAME)
889
+ const exec = config._exec || execFileSync
585
890
 
586
891
  // Bake the resolved binary locations into the service PATH so the daemon's
587
892
  // preflight finds node + claude under the bare launchd/systemd PATH (#5491).
@@ -590,8 +895,12 @@ export function installService(config) {
590
895
  claudeBin: config.claudeBin,
591
896
  })
592
897
 
898
+ // What exists before this attempt writes anything: rollback removes only what
899
+ // this attempt created (#8890).
900
+ const preexisting = snapshotExisting([servicePath, wrapperPath])
901
+
593
902
  // Write the wrapper that resolves keychain secrets at spawn time (#5491).
594
- const wrapperContent = generateServiceWrapper({
903
+ const wrapperContent = (config._generateWrapper || generateServiceWrapper)({
595
904
  nodePath: config.nodePath,
596
905
  chroxyBin: config.chroxyBin,
597
906
  pathValue,
@@ -599,6 +908,17 @@ export function installService(config) {
599
908
  })
600
909
  writeServiceWrapper(wrapperPath, wrapperContent)
601
910
 
911
+ // #7161: service.json must record what the wrapper ACTUALLY execs. Read it back
912
+ // from the file just written rather than trusting the value we passed in, so the
913
+ // two records cannot disagree (and a wrapper we cannot parse fails the install).
914
+ const execTarget = parseWrapperExecTarget(readFileSync(wrapperPath, 'utf-8'))
915
+ if (!execTarget || execTarget.chroxyBin !== config.chroxyBin) {
916
+ throw new Error(
917
+ `The service wrapper at ${wrapperPath} does not exec ${config.chroxyBin} ` +
918
+ `(read back: ${execTarget ? execTarget.chroxyBin : 'unparseable'}); refusing to record a target it does not run.`
919
+ )
920
+ }
921
+
602
922
  // Generate service file content
603
923
  const genConfig = {
604
924
  nodePath: config.nodePath,
@@ -631,12 +951,28 @@ export function installService(config) {
631
951
  // Write service file
632
952
  writeFileRestricted(servicePath, content)
633
953
 
634
- // Register with system (unless testing)
954
+ // Register with system (unless testing). A throw here leaves the definition and
955
+ // wrapper just written; a first install rolls them back (#8890).
635
956
  if (!config._skipRegister) {
957
+ try {
636
958
  if (plat === 'darwin') {
637
- execFileSync('launchctl', ['bootstrap', `gui/${process.getuid()}`, servicePath])
959
+ if (reinstall) {
960
+ // launchd refuses to bootstrap a label that is already loaded; a forced
961
+ // re-point must unload the old definition first. Not loaded is fine.
962
+ try {
963
+ exec('launchctl', ['bootout', `gui/${process.getuid()}/${SERVICE_LABEL}`], { stdio: 'ignore' })
964
+ } catch {
965
+ // not currently loaded
966
+ }
967
+ }
968
+ exec('launchctl', ['bootstrap', `gui/${process.getuid()}`, servicePath])
638
969
  } else {
639
- execFileSync('systemctl', ['--user', 'enable', '--now', 'chroxy.service'])
970
+ if (reinstall) exec('systemctl', ['--user', 'daemon-reload'])
971
+ exec('systemctl', ['--user', 'enable', '--now', 'chroxy.service'])
972
+ }
973
+ } catch (err) {
974
+ rollbackFreshInstall({ hadState, reinstall, preexisting }, [servicePath, wrapperPath])
975
+ throw err
640
976
  }
641
977
  }
642
978
 
@@ -646,7 +982,7 @@ export function installService(config) {
646
982
  platform: plat,
647
983
  servicePath,
648
984
  nodePath: config.nodePath,
649
- chroxyBin: config.chroxyBin,
985
+ chroxyBin: execTarget.chroxyBin,
650
986
  claudeBin: config.claudeBin,
651
987
  wrapperPath,
652
988
  cwd: genConfig.cwd,
@@ -654,6 +990,38 @@ export function installService(config) {
654
990
  }, stateDir)
655
991
  }
656
992
 
993
+ /** The subset of `paths` that exist right now. */
994
+ function snapshotExisting(paths) {
995
+ return new Set(paths.filter((p) => p && existsSync(p)))
996
+ }
997
+
998
+ /**
999
+ * Undo the files a FAILED first install left behind (#8890). The service
1000
+ * definition and wrapper are written before the service manager is asked to
1001
+ * register them, and service.json only after; so a registration that throws left
1002
+ * files that look like an install (and made the desktop app wait for a service
1003
+ * that does not exist) with no service.json for `service uninstall` to work from.
1004
+ *
1005
+ * Removes only what THIS attempt created, and never on a reinstall: a recognised
1006
+ * existing install (`reinstall`, which `assertReinstallAllowed` also grants from a
1007
+ * definition or wrapper with no service.json) may still be registered and needs
1008
+ * every file it had.
1009
+ *
1010
+ * @param {{ hadState: boolean, reinstall: boolean, preexisting: Set<string> }} guard
1011
+ * @param {string[]} paths
1012
+ */
1013
+ function rollbackFreshInstall({ hadState, reinstall, preexisting }, paths) {
1014
+ if (hadState || reinstall) return
1015
+ for (const p of paths) {
1016
+ if (!p || preexisting.has(p)) continue
1017
+ try {
1018
+ if (existsSync(p)) unlinkSync(p)
1019
+ } catch {
1020
+ // best effort: the original registration error is the one to report
1021
+ }
1022
+ }
1023
+ }
1024
+
657
1025
  /**
658
1026
  * Register Chroxy as a Windows autostart via Task Scheduler (#6647).
659
1027
  *
@@ -681,13 +1049,15 @@ export function installService(config) {
681
1049
  * @param {object} paths - getServicePaths('win32') result.
682
1050
  * @returns {{ installed: true, platform: 'win32', taskName: string, wrapperPath: string }}
683
1051
  */
684
- function installWindowsService(config, paths) {
685
- const stateDir = config._stateDir || DEFAULT_CONFIG_DIR
1052
+ function installWindowsService(config, paths, reinstall = false) {
1053
+ const stateDir = config._stateDir || defaultConfigDir()
686
1054
  const logDir = config._logDir || paths.logDir
687
1055
  const wrapperPath = config._wrapperPath || join(stateDir, WINDOWS_WRAPPER_NAME)
688
1056
  const taskName = config._taskName || WINDOWS_TASK_NAME
689
1057
  const exec = config._exec || execFileSync
690
1058
  const cwd = config.cwd || homedir()
1059
+ const hadState = !!loadServiceState(stateDir)
1060
+ const preexisting = snapshotExisting([wrapperPath])
691
1061
 
692
1062
  if (!existsSync(logDir)) {
693
1063
  mkdirSync(logDir, { recursive: true })
@@ -721,6 +1091,7 @@ function installWindowsService(config, paths) {
721
1091
  // generic "Command failed" and drops the real reason. Surface schtasks'
722
1092
  // stderr, and — since creating an ONLOGON task requires elevation, so a
723
1093
  // non-elevated install fails with "Access is denied." — add the fix (#6647).
1094
+ rollbackFreshInstall({ hadState, reinstall, preexisting }, [wrapperPath])
724
1095
  const detail = String(err?.stderr || '').trim()
725
1096
  const denied = /access is denied/i.test(detail)
726
1097
  throw new Error(
@@ -784,7 +1155,7 @@ export function getWindowsTaskStatus(options = {}) {
784
1155
  * Injectable exec for testing (defaults to execFileSync).
785
1156
  */
786
1157
  export function uninstallService(options = {}) {
787
- const stateDir = options._stateDir || DEFAULT_CONFIG_DIR
1158
+ const stateDir = options._stateDir || defaultConfigDir()
788
1159
  const state = loadServiceState(stateDir)
789
1160
 
790
1161
  if (!state) {
@@ -838,7 +1209,7 @@ export function uninstallService(options = {}) {
838
1209
  export function startService(options = {}) {
839
1210
  const plat = options._platform || platform()
840
1211
  const paths = getServicePaths(plat)
841
- const stateDir = options._stateDir || DEFAULT_CONFIG_DIR
1212
+ const stateDir = options._stateDir || defaultConfigDir()
842
1213
  const exec = options._exec || execFileSync
843
1214
 
844
1215
  if (plat === 'win32') {
@@ -960,7 +1331,7 @@ export function stopService(options = {}) {
960
1331
  * @returns {{ installed: boolean, running: boolean, pid: number|null, stale: boolean }}
961
1332
  */
962
1333
  export function getServiceStatus(options = {}) {
963
- const configDir = options.configDir || DEFAULT_CONFIG_DIR
1334
+ const configDir = options.configDir || defaultConfigDir()
964
1335
  const state = loadServiceState(configDir)
965
1336
 
966
1337
  if (!state) {
@@ -1010,7 +1381,7 @@ export function getServiceStatus(options = {}) {
1010
1381
  * @returns {Promise<object>} Full status including health, connection info, etc.
1011
1382
  */
1012
1383
  export async function getFullServiceStatus(options = {}) {
1013
- const configDir = options.configDir || DEFAULT_CONFIG_DIR
1384
+ const configDir = options.configDir || defaultConfigDir()
1014
1385
  const status = getServiceStatus({ configDir })
1015
1386
  const result = { ...status }
1016
1387
 
@@ -0,0 +1,15 @@
1
+ // Limits shared by the session-archive implementation (session-archive.js) and
2
+ // the config validator (config.js). A module of its own so config.js can name
3
+ // the bound without importing the archive's runtime dependencies, and so the two
4
+ // cannot drift apart.
5
+
6
+ // The roster is one WebSocket frame and the retention pass is linear in it.
7
+ export const SESSION_ARCHIVE_MAX_ENTRIES = 1000
8
+
9
+ // Whether a persisted session entry holds any history for the archive to keep.
10
+ // The archive skips an entry without it (nothing to read), and the boot
11
+ // staleness filter keeps such an entry live instead of setting it aside (#8870),
12
+ // so the two must use one rule: every stale session is either archived or kept.
13
+ export function savedHasHistory(saved) {
14
+ return !!saved && typeof saved === 'object' && Array.isArray(saved.history) && saved.history.length > 0
15
+ }