@chroxy/server 0.10.0

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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Skills usage log (#5554 Phase 2) — a bounded, server-side record of which
3
+ * skills have actually ACTIVATED in sessions, powering the Skills tab's
4
+ * "previously used" surface (last used, use count, which repos).
5
+ *
6
+ * Until now the only usage signal was the dashboard's client-only localStorage
7
+ * MRU of command IDs (store/commands.ts); the server tracked skill TRUST events
8
+ * (`skill_changed` / `skill_trust_*`) but never skill USE. This module closes
9
+ * that gap with a small persistent log.
10
+ *
11
+ * On-disk shape (~/.chroxy/skills-usage.json, mode 0600):
12
+ *
13
+ * {
14
+ * "version": 1,
15
+ * "entries": [ // ring buffer, newest LAST, bounded
16
+ * { "skill": "batch-merge", "sessionId": "ab…", "repo": "/p/chroxy", "ts": 1718000000000 },
17
+ * …
18
+ * ],
19
+ * "aggregates": { // per-skill rollup, kept in sync on record
20
+ * "batch-merge": { "count": 12, "lastUsed": 1718000000000, "repos": ["/p/chroxy", "/p/foo"] }
21
+ * }
22
+ * }
23
+ *
24
+ * Bounding (pruned like the Discord webhook state):
25
+ * - `entries` is capped at MAX_ENTRIES (default 500); the oldest are dropped
26
+ * when the cap is exceeded.
27
+ * - `aggregates` is the durable rollup so per-skill count / lastUsed / repos
28
+ * survive even after a skill's individual entries age out of the ring. Its
29
+ * per-skill `repos` list is capped at MAX_REPOS_PER_SKILL so a skill used
30
+ * across a huge number of repos can't grow an entry unbounded.
31
+ * - `aggregates` itself is capped at MAX_SKILLS distinct skills (least-
32
+ * recently-used eviction) so a churn of one-off skill names can't grow the
33
+ * file without limit.
34
+ *
35
+ * Atomic writes: temp + rename + cleanup-on-failure, mirroring
36
+ * `notification-prefs.js` / `byok-mcp-trust.js`. A single process owns the file
37
+ * so no mutex is needed, but rename failures still clean up the .tmp file.
38
+ *
39
+ * SECURITY: this store records only skill NAMES, the session id, the repo path,
40
+ * and a timestamp — never any skill body. The Skills-tab snapshot surfaces the
41
+ * aggregates (count / lastUsed / repos); the raw entries never cross the wire.
42
+ */
43
+
44
+ import { homedir } from 'node:os'
45
+ import { join } from 'node:path'
46
+ import { createLogger } from './logger.js'
47
+ import { loadJsonState, saveJsonState } from './json-state-file.js'
48
+ import { getErrorMessage } from './utils/error-message.js'
49
+
50
+ const log = createLogger('skills-usage')
51
+
52
+ /** Default on-disk location for the usage log. */
53
+ export function defaultSkillsUsagePath() {
54
+ return join(homedir(), '.chroxy', 'skills-usage.json')
55
+ }
56
+
57
+ /** Ring-buffer cap on the raw entries kept on disk. */
58
+ export const MAX_ENTRIES = 500
59
+ /** Cap on distinct skills tracked in the durable aggregates rollup. */
60
+ export const MAX_SKILLS = 1000
61
+ /** Cap on distinct repos remembered per skill in the aggregates. */
62
+ export const MAX_REPOS_PER_SKILL = 25
63
+
64
+ /**
65
+ * A fresh, empty store object.
66
+ * @returns {{ version: number, entries: object[], aggregates: object }}
67
+ */
68
+ function emptyStore() {
69
+ return { version: 1, entries: [], aggregates: {} }
70
+ }
71
+
72
+ /**
73
+ * Coerce an arbitrary parsed JSON value into a well-formed store. Tolerant —
74
+ * a corrupt/partial file degrades to whatever fields are usable rather than
75
+ * throwing (a usage log is best-effort telemetry, never load-bearing).
76
+ *
77
+ * @param {unknown} parsed
78
+ * @returns {{ version: number, entries: object[], aggregates: object }}
79
+ */
80
+ function normalizeStore(parsed) {
81
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return emptyStore()
82
+ const out = emptyStore()
83
+ if (Array.isArray(parsed.entries)) {
84
+ for (const e of parsed.entries) {
85
+ const norm = normalizeEntry(e)
86
+ if (norm) out.entries.push(norm)
87
+ }
88
+ }
89
+ if (parsed.aggregates && typeof parsed.aggregates === 'object' && !Array.isArray(parsed.aggregates)) {
90
+ for (const [skill, agg] of Object.entries(parsed.aggregates)) {
91
+ const norm = normalizeAggregate(agg)
92
+ if (typeof skill === 'string' && skill.length > 0 && norm) out.aggregates[skill] = norm
93
+ }
94
+ }
95
+ return out
96
+ }
97
+
98
+ /** Validate + coerce one raw entry; returns null when unusable. */
99
+ function normalizeEntry(e) {
100
+ if (!e || typeof e !== 'object') return null
101
+ const skill = typeof e.skill === 'string' && e.skill.length > 0 ? e.skill : null
102
+ const ts = typeof e.ts === 'number' && Number.isFinite(e.ts) && e.ts > 0 ? e.ts : null
103
+ if (!skill || !ts) return null
104
+ return {
105
+ skill,
106
+ sessionId: typeof e.sessionId === 'string' && e.sessionId.length > 0 ? e.sessionId : null,
107
+ repo: typeof e.repo === 'string' && e.repo.length > 0 ? e.repo : null,
108
+ ts,
109
+ }
110
+ }
111
+
112
+ /** Validate + coerce one aggregate; returns null when unusable. */
113
+ function normalizeAggregate(agg) {
114
+ if (!agg || typeof agg !== 'object') return null
115
+ const count = typeof agg.count === 'number' && Number.isFinite(agg.count) && agg.count >= 0
116
+ ? Math.trunc(agg.count)
117
+ : 0
118
+ const lastUsed = typeof agg.lastUsed === 'number' && Number.isFinite(agg.lastUsed) && agg.lastUsed > 0
119
+ ? agg.lastUsed
120
+ : null
121
+ const repos = []
122
+ if (Array.isArray(agg.repos)) {
123
+ for (const r of agg.repos) {
124
+ if (typeof r === 'string' && r.length > 0 && !repos.includes(r)) repos.push(r)
125
+ if (repos.length >= MAX_REPOS_PER_SKILL) break
126
+ }
127
+ }
128
+ return { count, lastUsed, repos }
129
+ }
130
+
131
+ /**
132
+ * Load the usage store from disk. Missing file → empty store; unparseable file
133
+ * → empty store with a debug log (never throws — best-effort telemetry).
134
+ *
135
+ * @param {string} [filePath]
136
+ * @returns {{ version: number, entries: object[], aggregates: object }}
137
+ */
138
+ export function loadUsageStore(filePath = defaultSkillsUsagePath()) {
139
+ // #5580: fail-open read+parse via the shared JsonStateFile seam. A missing or
140
+ // unparseable file degrades to an empty store (best-effort telemetry, never
141
+ // load-bearing). `requireObject: false` so normalizeStore — not the loader —
142
+ // owns the "non-object → empty" coercion, preserving the prior tolerant shape.
143
+ // Telemetry corruption is expected/benign — keep the prior debug-level
144
+ // logging by shimming warn→debug for this call site (the shared seam warns
145
+ // by default, which is right for load-bearing stores but noisy here).
146
+ const usageLog = { ...log, warn: (...args) => log.debug?.(...args) }
147
+ const parsed = loadJsonState(filePath, () => null, { requireObject: false, log: usageLog })
148
+ return normalizeStore(parsed)
149
+ }
150
+
151
+ /**
152
+ * Persist a store object to disk. Atomic temp+rename so a crashed write cannot
153
+ * corrupt the file; on POSIX the file ends up at mode 0600.
154
+ *
155
+ * #5579: the temp sidecar carries a per-pid suffix (`.tmp-<pid>`), mirroring
156
+ * the #5309 convention in `session-state-persistence.js`. A fixed `.tmp` meant
157
+ * two daemons writing concurrently (e.g. an old process still flushing while a
158
+ * restart spins up) shared one intermediate path and could clobber each other
159
+ * mid-write, tearing the file. The per-pid suffix gives each writer its own
160
+ * sidecar so the rename — the atomic step — is the only point of contention.
161
+ * Delegates to `writeFileRestricted` (platform.js), which also unlinks the
162
+ * orphaned sidecar on rename failure and warns on a non-ENOENT cleanup miss so
163
+ * a stale `.tmp-<pid>` can't go silently undeleted.
164
+ *
165
+ * @param {object} store
166
+ * @param {string} [filePath]
167
+ */
168
+ export function saveUsageStore(store, filePath = defaultSkillsUsagePath()) {
169
+ // #5580: atomic 0600 save via the shared JsonStateFile seam (which delegates
170
+ // to writeFileRestricted — same per-pid tmp suffix per #5579, same mkdir +
171
+ // rename-failure cleanup). Suffix kept byte-identical to the prior `.tmp-<pid>`.
172
+ saveJsonState(filePath, store, { tmpSuffix: `.tmp-${process.pid}` })
173
+ }
174
+
175
+ /**
176
+ * Apply one usage record to an in-memory store, enforcing all bounds. Pure —
177
+ * mutates and returns the passed store so callers can batch multiple records
178
+ * before a single save.
179
+ *
180
+ * @param {object} store - a normalized store (see {@link loadUsageStore}).
181
+ * @param {{ skill: string, sessionId?: string|null, repo?: string|null, ts?: number }} record
182
+ * @returns {object} the same store, mutated.
183
+ */
184
+ export function applyUsage(store, record) {
185
+ const skill = record && typeof record.skill === 'string' && record.skill.length > 0 ? record.skill : null
186
+ if (!skill) return store
187
+ const ts = typeof record.ts === 'number' && Number.isFinite(record.ts) && record.ts > 0 ? record.ts : Date.now()
188
+ const sessionId = typeof record.sessionId === 'string' && record.sessionId.length > 0 ? record.sessionId : null
189
+ const repo = typeof record.repo === 'string' && record.repo.length > 0 ? record.repo : null
190
+
191
+ // 1. Append to the ring buffer, then prune the oldest past the cap.
192
+ store.entries.push({ skill, sessionId, repo, ts })
193
+ if (store.entries.length > MAX_ENTRIES) {
194
+ store.entries.splice(0, store.entries.length - MAX_ENTRIES)
195
+ }
196
+
197
+ // 2. Update the durable per-skill aggregate.
198
+ let agg = store.aggregates[skill]
199
+ if (!agg) agg = store.aggregates[skill] = { count: 0, lastUsed: null, repos: [] }
200
+ agg.count += 1
201
+ // lastUsed only advances — an out-of-order (older) record never rolls it back.
202
+ if (agg.lastUsed === null || ts > agg.lastUsed) agg.lastUsed = ts
203
+ if (repo && !agg.repos.includes(repo)) {
204
+ agg.repos.push(repo)
205
+ if (agg.repos.length > MAX_REPOS_PER_SKILL) {
206
+ // Drop the oldest-remembered repo (front of the list) past the cap.
207
+ agg.repos.splice(0, agg.repos.length - MAX_REPOS_PER_SKILL)
208
+ }
209
+ }
210
+
211
+ // 3. Cap distinct tracked skills — evict the least-recently-used aggregate(s).
212
+ const skillNames = Object.keys(store.aggregates)
213
+ if (skillNames.length > MAX_SKILLS) {
214
+ skillNames
215
+ .sort((a, b) => (store.aggregates[a].lastUsed ?? 0) - (store.aggregates[b].lastUsed ?? 0))
216
+ .slice(0, skillNames.length - MAX_SKILLS)
217
+ .forEach((name) => { delete store.aggregates[name] })
218
+ }
219
+
220
+ return store
221
+ }
222
+
223
+ /**
224
+ * SkillsUsageRecorder — load-once, record-many, debounced-save wrapper around
225
+ * the on-disk store. One instance is created per daemon (by SessionManager) and
226
+ * its `record` callback is handed to each session at creation time.
227
+ *
228
+ * Saves are debounced (DEFAULT_SAVE_DEBOUNCE_MS) so a burst of activations on
229
+ * session creation collapses into a single write. A best-effort synchronous
230
+ * `flush()` lets the daemon persist on shutdown.
231
+ */
232
+ export const DEFAULT_SAVE_DEBOUNCE_MS = 1000
233
+
234
+ export class SkillsUsageRecorder {
235
+ /**
236
+ * @param {{ filePath?: string, saveDebounceMs?: number, now?: () => number,
237
+ * _load?: typeof loadUsageStore, _save?: typeof saveUsageStore }} [opts]
238
+ */
239
+ constructor(opts = {}) {
240
+ this._filePath = typeof opts.filePath === 'string' && opts.filePath.length > 0
241
+ ? opts.filePath
242
+ : defaultSkillsUsagePath()
243
+ this._saveDebounceMs = Number.isFinite(opts.saveDebounceMs) && opts.saveDebounceMs >= 0
244
+ ? opts.saveDebounceMs
245
+ : DEFAULT_SAVE_DEBOUNCE_MS
246
+ this._now = typeof opts.now === 'function' ? opts.now : () => Date.now()
247
+ this._load = typeof opts._load === 'function' ? opts._load : loadUsageStore
248
+ this._save = typeof opts._save === 'function' ? opts._save : saveUsageStore
249
+ this._store = this._load(this._filePath)
250
+ this._saveTimer = null
251
+ this._dirty = false
252
+ }
253
+
254
+ /**
255
+ * Record one or more skill activations for a session. `skills` is an array of
256
+ * skill names (the active set the session loaded). Repo + sessionId are shared
257
+ * across the batch. Never throws — a usage-log failure must never break
258
+ * session creation.
259
+ *
260
+ * @param {{ sessionId?: string|null, repo?: string|null, skills: string[], ts?: number }} batch
261
+ */
262
+ record(batch) {
263
+ try {
264
+ const skills = Array.isArray(batch?.skills) ? batch.skills : []
265
+ if (skills.length === 0) return
266
+ const ts = typeof batch?.ts === 'number' && Number.isFinite(batch.ts) ? batch.ts : this._now()
267
+ const sessionId = batch?.sessionId ?? null
268
+ const repo = batch?.repo ?? null
269
+ let changed = false
270
+ const seen = new Set()
271
+ for (const skill of skills) {
272
+ if (typeof skill !== 'string' || skill.length === 0) continue
273
+ // De-dupe within a single activation batch — one session loading the
274
+ // same skill name twice (global + repo overlay collapsed) is one use.
275
+ if (seen.has(skill)) continue
276
+ seen.add(skill)
277
+ applyUsage(this._store, { skill, sessionId, repo, ts })
278
+ changed = true
279
+ }
280
+ if (changed) this._scheduleSave()
281
+ } catch (err) {
282
+ log.debug(`skills-usage: record failed (non-fatal): ${getErrorMessage(err, err)}`)
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Per-skill aggregate snapshot for the inventory join. Returns a Map keyed by
288
+ * skill name → { lastUsed, count, repos } (a copy, so callers can't mutate
289
+ * the live store).
290
+ *
291
+ * @returns {Map<string, { lastUsed: number|null, count: number, repos: string[] }>}
292
+ */
293
+ aggregatesByName() {
294
+ const out = new Map()
295
+ for (const [name, agg] of Object.entries(this._store.aggregates)) {
296
+ out.set(name, {
297
+ lastUsed: agg.lastUsed ?? null,
298
+ count: agg.count ?? 0,
299
+ repos: Array.isArray(agg.repos) ? agg.repos.slice() : [],
300
+ })
301
+ }
302
+ return out
303
+ }
304
+
305
+ /** Schedule a debounced save; coalesces a burst into one write. */
306
+ _scheduleSave() {
307
+ this._dirty = true
308
+ if (this._saveDebounceMs === 0) {
309
+ this.flush()
310
+ return
311
+ }
312
+ if (this._saveTimer) return
313
+ this._saveTimer = setTimeout(() => {
314
+ this._saveTimer = null
315
+ this.flush()
316
+ }, this._saveDebounceMs)
317
+ // Don't keep the event loop alive for a pending usage flush.
318
+ if (this._saveTimer && typeof this._saveTimer.unref === 'function') this._saveTimer.unref()
319
+ }
320
+
321
+ /** Persist synchronously if dirty. Best-effort — never throws to callers. */
322
+ flush() {
323
+ if (this._saveTimer) {
324
+ clearTimeout(this._saveTimer)
325
+ this._saveTimer = null
326
+ }
327
+ if (!this._dirty) return
328
+ try {
329
+ this._save(this._store, this._filePath)
330
+ this._dirty = false
331
+ } catch (err) {
332
+ log.warn(`skills-usage: save failed: ${getErrorMessage(err, err)}`)
333
+ }
334
+ }
335
+ }
@@ -0,0 +1,345 @@
1
+ /**
2
+ * snapshots-store — list and delete docker-byok snapshot metadata sidecars.
3
+ *
4
+ * Snapshots produced by `DockerByokSession.snapshot()` (#5023 / #5071) write a
5
+ * JSON sidecar to `${CHROXY_CONFIG_DIR ?? ~/.chroxy}/snapshots/<slug>.json`
6
+ * shaped like:
7
+ *
8
+ * { tag, name, createdAt, sourceCwd, sourceImage, sourceSessionId }
9
+ *
10
+ * This module gives the HTTP layer a thin read/delete API over that
11
+ * directory so the dashboard can render a list and trigger removal
12
+ * without re-implementing the directory contract. See #5074.
13
+ *
14
+ * Listing tolerates partial corruption: unreadable, malformed, or
15
+ * non-object files are skipped with a warn line rather than failing the
16
+ * entire request, so a single bad sidecar can't take the panel offline.
17
+ *
18
+ * Delete is two-step:
19
+ * 1. `docker rmi <tag>` via the injected `removeImage` callback (the
20
+ * DockerBackend's helper in production, a stub in tests).
21
+ * 2. `unlink` the sidecar.
22
+ *
23
+ * Step 1 best-effort: if rmi fails (image already gone, daemon down) we
24
+ * still drop the sidecar so the dashboard stops listing a ghost entry.
25
+ * The caller learns about the rmi failure via the returned `imageRemoved`
26
+ * flag.
27
+ *
28
+ * Reconciliation (#5075) closes the drift gap left by the snapshot/restore
29
+ * landings (#5100 / #5092 / #5098): a snapshot is the pair (image tag,
30
+ * sidecar JSON), and either side can outlive the other —
31
+ *
32
+ * - User runs `docker rmi chroxy-byok-snap:foo` directly: the image is
33
+ * gone but the sidecar lingers, so the dashboard lists a ghost entry
34
+ * whose DELETE just re-fails. Also covers the existing best-effort
35
+ * `imageRemoved: false` case in `deleteSnapshot` above — by the next
36
+ * reconcile pass the image truly is gone, so we drop the sidecar.
37
+ * - Sidecar corrupted or manually deleted: the image still sits on the
38
+ * host eating disk. We log a warning so the operator can decide to
39
+ * `docker rmi` it themselves, but we DO NOT auto-rm — a user may have
40
+ * intentionally retagged something into the `chroxy-byok-snap` prefix.
41
+ *
42
+ * `reconcileOrphans()` is the surface for both. It is a pure function over
43
+ * an injected `listImages(): Promise<string[]>` callback (filtered to the
44
+ * `chroxy-byok-snap:` prefix at the docker shell level so we never touch
45
+ * an image outside our scope) and the on-disk sidecar directory.
46
+ */
47
+
48
+ import { readdirSync, readFileSync, existsSync, unlinkSync } from 'fs'
49
+ import { join } from 'path'
50
+ import { homedir } from 'os'
51
+ import { createLogger } from './logger.js'
52
+
53
+ const log = createLogger('snapshots')
54
+
55
+ /**
56
+ * Resolve the snapshots metadata directory.
57
+ *
58
+ * Lazy (no caching): tests that mutate `CHROXY_CONFIG_DIR` between
59
+ * cases see the new value, matching the pattern used by models.js /
60
+ * device-preferences.js / connection-info.js.
61
+ *
62
+ * @returns {string}
63
+ */
64
+ export function getSnapshotsDir() {
65
+ const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
66
+ return join(configDir, 'snapshots')
67
+ }
68
+
69
+ /**
70
+ * Filename-safe characters per the sidecar slug convention in
71
+ * docker-byok-session.js `_persistSnapshotMetadata`. Defence-in-depth
72
+ * against path traversal in the DELETE handler: the URL slug must
73
+ * match this charset before it's joined to the directory.
74
+ */
75
+ const SLUG_RE = /^[A-Za-z0-9_.-]+$/
76
+
77
+ /**
78
+ * @typedef {Object} SnapshotMetadata
79
+ * @property {string} tag Image tag (`chroxy-byok-snap:<rand>-<ts>`)
80
+ * @property {string} name Human-readable name (falls back to tag slug)
81
+ * @property {string} createdAt ISO-8601 timestamp
82
+ * @property {string} sourceCwd Host cwd the session ran in
83
+ * @property {string} sourceImage Base image the snapshot derives from
84
+ * @property {string|null} sourceSessionId
85
+ * @property {string} slug Sidecar filename without `.json`
86
+ */
87
+
88
+ /**
89
+ * List all snapshots currently present in the metadata directory.
90
+ *
91
+ * Returns an empty array when the directory does not exist (no snapshots
92
+ * have ever been taken) — that's the documented happy-path for a fresh
93
+ * install, not an error.
94
+ *
95
+ * Each entry carries a `slug` field — the sidecar filename without its
96
+ * `.json` extension — so the dashboard can pass it back to the DELETE
97
+ * endpoint without re-deriving it from the tag.
98
+ *
99
+ * Files that fail to parse are skipped with a warn line. Sort order is
100
+ * newest-first by `createdAt` so the dashboard can render the most
101
+ * recent snapshot at the top; entries without a parseable createdAt
102
+ * sink to the end.
103
+ *
104
+ * @param {object} [opts]
105
+ * @param {string} [opts.dir] Override the snapshots dir (tests).
106
+ * @returns {SnapshotMetadata[]}
107
+ */
108
+ export function listSnapshots({ dir } = {}) {
109
+ const snapshotsDir = dir || getSnapshotsDir()
110
+ if (!existsSync(snapshotsDir)) return []
111
+
112
+ let entries
113
+ try {
114
+ entries = readdirSync(snapshotsDir, { withFileTypes: true })
115
+ } catch (err) {
116
+ log.warn(`Could not read snapshots dir ${snapshotsDir}: ${err.message}`)
117
+ return []
118
+ }
119
+
120
+ const out = []
121
+ for (const ent of entries) {
122
+ if (!ent.isFile()) continue
123
+ if (!ent.name.endsWith('.json')) continue
124
+ const filePath = join(snapshotsDir, ent.name)
125
+ let raw
126
+ try {
127
+ raw = readFileSync(filePath, 'utf-8')
128
+ } catch (err) {
129
+ log.warn(`Skipping unreadable snapshot sidecar ${ent.name}: ${err.message}`)
130
+ continue
131
+ }
132
+ let parsed
133
+ try {
134
+ parsed = JSON.parse(raw)
135
+ } catch (err) {
136
+ log.warn(`Skipping malformed snapshot sidecar ${ent.name}: ${err.message}`)
137
+ continue
138
+ }
139
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.tag !== 'string') {
140
+ log.warn(`Skipping snapshot sidecar ${ent.name}: missing required "tag" field`)
141
+ continue
142
+ }
143
+ out.push({
144
+ tag: parsed.tag,
145
+ name: typeof parsed.name === 'string' ? parsed.name : '',
146
+ createdAt: typeof parsed.createdAt === 'string' ? parsed.createdAt : '',
147
+ sourceCwd: typeof parsed.sourceCwd === 'string' ? parsed.sourceCwd : '',
148
+ sourceImage: typeof parsed.sourceImage === 'string' ? parsed.sourceImage : '',
149
+ sourceSessionId: parsed.sourceSessionId == null ? null : String(parsed.sourceSessionId),
150
+ slug: ent.name.slice(0, -'.json'.length),
151
+ })
152
+ }
153
+
154
+ out.sort((a, b) => {
155
+ const ta = Date.parse(a.createdAt)
156
+ const tb = Date.parse(b.createdAt)
157
+ const va = Number.isFinite(ta) ? ta : -Infinity
158
+ const vb = Number.isFinite(tb) ? tb : -Infinity
159
+ return vb - va
160
+ })
161
+ return out
162
+ }
163
+
164
+ /**
165
+ * Delete a snapshot by slug — removes the docker image then drops the
166
+ * sidecar JSON.
167
+ *
168
+ * The `removeImage` callback is injected (the DockerBackend helper in
169
+ * production, a stub in tests) so this module doesn't take a hard
170
+ * dependency on the docker backend. If `removeImage` rejects, the
171
+ * sidecar is STILL deleted (image-rm is best-effort — a ghost sidecar
172
+ * is worse UX than a leaked image, since the dashboard re-lists ghosts
173
+ * forever) and the failure surfaces via the returned `imageRemoved`
174
+ * flag.
175
+ *
176
+ * Returns:
177
+ * - { ok: false, status: 400, error: 'invalid slug' } — slug fails charset check
178
+ * - { ok: false, status: 404, error: 'not found' } — sidecar missing
179
+ * - { ok: true, tag, imageRemoved } — sidecar dropped (and image-rm attempted)
180
+ *
181
+ * @param {string} slug
182
+ * @param {object} opts
183
+ * @param {(tag: string) => Promise<void>} opts.removeImage
184
+ * @param {string} [opts.dir] Override the snapshots dir (tests).
185
+ * @returns {Promise<{ok:true, tag:string, imageRemoved:boolean} | {ok:false, status:number, error:string}>}
186
+ */
187
+ export async function deleteSnapshot(slug, { removeImage, dir } = {}) {
188
+ if (typeof slug !== 'string' || slug.length === 0 || !SLUG_RE.test(slug)) {
189
+ return { ok: false, status: 400, error: 'invalid slug' }
190
+ }
191
+ if (typeof removeImage !== 'function') {
192
+ throw new Error('deleteSnapshot: removeImage callback required')
193
+ }
194
+ const snapshotsDir = dir || getSnapshotsDir()
195
+ const filePath = join(snapshotsDir, `${slug}.json`)
196
+ if (!existsSync(filePath)) {
197
+ return { ok: false, status: 404, error: 'not found' }
198
+ }
199
+ let metadata
200
+ try {
201
+ metadata = JSON.parse(readFileSync(filePath, 'utf-8'))
202
+ } catch (err) {
203
+ log.warn(`deleteSnapshot: malformed sidecar ${slug}.json: ${err.message}`)
204
+ metadata = null
205
+ }
206
+ const tag = metadata && typeof metadata.tag === 'string' ? metadata.tag : null
207
+
208
+ let imageRemoved = true
209
+ if (tag) {
210
+ try {
211
+ await removeImage(tag)
212
+ } catch (err) {
213
+ log.warn(`deleteSnapshot: docker rmi ${tag} failed: ${err.message}`)
214
+ imageRemoved = false
215
+ }
216
+ } else {
217
+ // No tag to remove — the sidecar was already corrupt. Treat the
218
+ // image as "removed" in the response since there's nothing to do.
219
+ imageRemoved = true
220
+ }
221
+
222
+ try {
223
+ unlinkSync(filePath)
224
+ } catch (err) {
225
+ log.warn(`deleteSnapshot: failed to unlink ${filePath}: ${err.message}`)
226
+ return { ok: false, status: 500, error: 'sidecar unlink failed' }
227
+ }
228
+
229
+ return { ok: true, tag: tag || '', imageRemoved }
230
+ }
231
+
232
+ /**
233
+ * Image-tag prefix every docker-byok snapshot is published under. The
234
+ * reconciler only ever reasons about images in this namespace so it can
235
+ * never touch (or even consider an orphan) an unrelated image on the host.
236
+ */
237
+ const SNAPSHOT_TAG_PREFIX = 'chroxy-byok-snap:'
238
+
239
+ /**
240
+ * @typedef {Object} ReconcileResult
241
+ * @property {number} sidecarsScanned Count of valid (taggable) sidecars considered.
242
+ * @property {number} imagesScanned Count of `chroxy-byok-snap:` images on the host.
243
+ * @property {string[]} orphanedSidecarsRemoved Slugs of sidecars unlinked (tag gone from daemon).
244
+ * @property {string[]} orphanedImagesLogged Snapshot image tags with no sidecar (logged, NOT removed).
245
+ */
246
+
247
+ /**
248
+ * Reconcile the two halves of a docker-byok snapshot — the image tag in
249
+ * the local daemon and the JSON sidecar on disk — and repair drift.
250
+ *
251
+ * Strategy (documented in the module header, #5075):
252
+ *
253
+ * - sidecar WITHOUT a matching image tag → the image was deleted out
254
+ * from under us (`docker rmi` by hand, or a best-effort
255
+ * `deleteSnapshot` that left `imageRemoved: false`). The sidecar is a
256
+ * ghost the dashboard would re-list forever, so we UNLINK it.
257
+ * - image tag WITHOUT a matching sidecar → an image sits on the host
258
+ * eating disk but nothing tracks it. We LOG it for the operator and
259
+ * deliberately do NOT `docker rmi` — a user may have intentionally
260
+ * retagged something into the `chroxy-byok-snap:` namespace, and a
261
+ * reconciler must never destroy data it didn't create.
262
+ *
263
+ * `listImages` is treated as the source of truth for what exists in the
264
+ * daemon. If it rejects (daemon down, docker missing) we propagate the
265
+ * error and take NO destructive action — reconciling against a partial or
266
+ * empty image list would wrongly delete every live sidecar. This keeps the
267
+ * pass idempotent and safe to run on a schedule.
268
+ *
269
+ * Pairing is by exact image tag: a sidecar's `tag` field is matched against
270
+ * the set of `chroxy-byok-snap:`-prefixed tags returned by `listImages`.
271
+ * Non-snapshot images returned by `listImages` are filtered out up front so
272
+ * they neither count toward `imagesScanned` nor surface as orphans.
273
+ *
274
+ * @param {object} opts
275
+ * @param {() => Promise<string[]>} opts.listImages Returns docker image tags (any namespace; filtered here).
276
+ * @param {string} [opts.dir] Override the snapshots dir (tests).
277
+ * @returns {Promise<ReconcileResult>}
278
+ */
279
+ export async function reconcileOrphans({ listImages, dir } = {}) {
280
+ if (typeof listImages !== 'function') {
281
+ throw new Error('reconcileOrphans: listImages callback required')
282
+ }
283
+
284
+ // Source of truth first. A rejection here is fatal BY DESIGN — we must
285
+ // never act on a partial/empty image list (it would nuke live sidecars).
286
+ // A non-array return is treated the same way: fail loud rather than
287
+ // coerce to [] and silently delete every sidecar (fail-destructive).
288
+ const rawImages = await listImages()
289
+ if (!Array.isArray(rawImages)) {
290
+ throw new Error('reconcileOrphans: listImages must resolve to an array')
291
+ }
292
+ const snapshotImages = rawImages.filter(
293
+ (tag) => typeof tag === 'string' && tag.startsWith(SNAPSHOT_TAG_PREFIX),
294
+ )
295
+ const imageSet = new Set(snapshotImages)
296
+
297
+ // listSnapshots already skips unreadable/malformed/tag-less sidecars and
298
+ // hands back a slug per entry, so reconcile only ever reasons about
299
+ // sidecars it can pair by tag.
300
+ const snapshotsDir = dir || getSnapshotsDir()
301
+ const sidecars = listSnapshots({ dir: snapshotsDir })
302
+
303
+ const orphanedSidecarsRemoved = []
304
+ const trackedTags = new Set()
305
+
306
+ for (const entry of sidecars) {
307
+ // Only reconcile sidecars that reference an image in OUR namespace. A
308
+ // sidecar whose tag was corrupted (or written by a future format) into
309
+ // a non-snapshot namespace is outside our authority — `listImages` only
310
+ // returns `chroxy-byok-snap:` tags, so such an entry would never match
311
+ // and we'd wrongly unlink it. Leave it untouched.
312
+ if (!entry.tag.startsWith(SNAPSHOT_TAG_PREFIX)) continue
313
+ trackedTags.add(entry.tag)
314
+ if (imageSet.has(entry.tag)) continue
315
+ // Sidecar's image is gone from the daemon — drop the ghost.
316
+ const filePath = join(snapshotsDir, `${entry.slug}.json`)
317
+ try {
318
+ unlinkSync(filePath)
319
+ orphanedSidecarsRemoved.push(entry.slug)
320
+ log.info(
321
+ `reconcileOrphans: removed orphaned sidecar ${entry.slug}.json (image ${entry.tag} no longer present)`,
322
+ )
323
+ } catch (err) {
324
+ log.warn(`reconcileOrphans: failed to unlink orphaned sidecar ${filePath}: ${err.message}`)
325
+ }
326
+ }
327
+
328
+ const orphanedImagesLogged = []
329
+ for (const tag of snapshotImages) {
330
+ if (trackedTags.has(tag)) continue
331
+ // Image with no sidecar — log only, never auto-rm.
332
+ orphanedImagesLogged.push(tag)
333
+ log.warn(
334
+ `reconcileOrphans: snapshot image ${tag} has no metadata sidecar; ` +
335
+ `leaving in place (run "docker rmi ${tag}" to reclaim disk if unwanted)`,
336
+ )
337
+ }
338
+
339
+ return {
340
+ sidecarsScanned: sidecars.length,
341
+ imagesScanned: snapshotImages.length,
342
+ orphanedSidecarsRemoved,
343
+ orphanedImagesLogged,
344
+ }
345
+ }