@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,234 @@
1
+ /**
2
+ * docker-byok compose-project-id persistence (#5081).
3
+ *
4
+ * `DockerByokSession` generates `_composeProject = 'chroxy-byok-<rand-hex>'`
5
+ * lazily inside `_startComposeStack`. Held in memory only, a daemon crash /
6
+ * SIGKILL between `docker compose up` and `docker compose down` leaks the
7
+ * whole stack with no on-disk paper trail.
8
+ *
9
+ * This store mirrors EnvironmentManager's on-disk shape (`{ version, stacks }`,
10
+ * atomic restricted write) so each running compose stack leaves a durable
11
+ * record. A boot-time `sweepOrphanedComposeStacks()` then runs
12
+ * `docker compose down --remove-orphans` against every leftover project id
13
+ * before any new sessions launch.
14
+ *
15
+ * State-file shape:
16
+ * {
17
+ * "version": 1,
18
+ * "stacks": [
19
+ * { "projectId": "chroxy-byok-ab12cd", "composeFile": "/proj/docker-compose.yml",
20
+ * "cwd": "/work/proj", "createdAt": "2026-06-03T..." }
21
+ * ]
22
+ * }
23
+ */
24
+
25
+ import { existsSync, readFileSync, mkdirSync } from 'node:fs'
26
+ import { dirname, join } from 'node:path'
27
+ import { homedir } from 'node:os'
28
+
29
+ import { writeFileRestricted } from './platform.js'
30
+
31
+ const STATE_VERSION = 1
32
+
33
+ /**
34
+ * #5124 — A persisted compose file may be a single path or an array of paths
35
+ * (base + override overlay). Valid when it's a non-empty string, or a
36
+ * non-empty array of non-empty strings.
37
+ * @param {*} composeFile
38
+ * @returns {boolean}
39
+ */
40
+ function isValidComposeFile(composeFile) {
41
+ if (typeof composeFile === 'string') return composeFile.length > 0
42
+ if (Array.isArray(composeFile)) {
43
+ return composeFile.length > 0 && composeFile.every((f) => typeof f === 'string' && f.length > 0)
44
+ }
45
+ return false
46
+ }
47
+
48
+ /**
49
+ * #5124 — Defensive copy so the store never aliases a caller-provided array.
50
+ * Strings are immutable and returned as-is; arrays are shallow-cloned so a
51
+ * later mutation by the caller can't change persisted state (or what a prior
52
+ * `list()` consumer sees).
53
+ * @param {string|string[]} composeFile
54
+ * @returns {string|string[]}
55
+ */
56
+ function cloneComposeFile(composeFile) {
57
+ return Array.isArray(composeFile) ? [...composeFile] : composeFile
58
+ }
59
+
60
+ /**
61
+ * Default on-disk location, mirroring environment-manager.js's
62
+ * `~/.chroxy/environments.json`. Honors CHROXY_CONFIG_DIR like the rest of
63
+ * the docker-byok stack does.
64
+ */
65
+ export const DEFAULT_BYOK_COMPOSE_STATE_PATH = join(
66
+ process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'),
67
+ 'byok-compose-state.json',
68
+ )
69
+
70
+ /**
71
+ * Synchronous, crash-durable store of live compose project ids.
72
+ *
73
+ * Every mutation persists immediately via `writeFileRestricted` (atomic on
74
+ * POSIX + Windows, mode 0600) so a crash right after the in-memory mutation
75
+ * still leaves the durable record the boot sweep relies on.
76
+ */
77
+ export class ByokComposeStateStore {
78
+ /**
79
+ * @param {object} opts
80
+ * @param {string} [opts.statePath] - On-disk path for byok-compose-state.json.
81
+ */
82
+ constructor({ statePath } = {}) {
83
+ this._statePath = statePath || DEFAULT_BYOK_COMPOSE_STATE_PATH
84
+ // Map<projectId, entry> so record() on an existing id replaces in place
85
+ // and forget() is O(1). Insertion order is preserved by Map iteration.
86
+ this._stacks = new Map()
87
+ this._load()
88
+ }
89
+
90
+ /**
91
+ * Record (or replace) a live compose stack and persist to disk.
92
+ *
93
+ * @param {object} entry
94
+ * @param {string} entry.projectId - Compose project id (chroxy-byok-<hex>).
95
+ * @param {string|string[]} entry.composeFile - Absolute path to the compose
96
+ * file, or an ARRAY of paths for a base + override overlay (#5124). The
97
+ * boot sweep replays the same `-f` set so the merged config — and thus the
98
+ * stack torn down — matches the one brought up.
99
+ * @param {string} entry.cwd - Working directory the stack runs in.
100
+ */
101
+ record({ projectId, composeFile, cwd } = {}) {
102
+ if (!projectId || typeof projectId !== 'string') {
103
+ throw new Error('record() requires a non-empty projectId')
104
+ }
105
+ if (!isValidComposeFile(composeFile)) {
106
+ throw new Error('record() requires a non-empty composeFile (string or array of strings)')
107
+ }
108
+ if (!cwd || typeof cwd !== 'string') {
109
+ throw new Error('record() requires a non-empty cwd')
110
+ }
111
+ this._stacks.set(projectId, {
112
+ projectId,
113
+ composeFile: cloneComposeFile(composeFile),
114
+ cwd,
115
+ createdAt: new Date().toISOString(),
116
+ })
117
+ this._persist()
118
+ }
119
+
120
+ /**
121
+ * Remove a stack by project id and persist. No-op if unknown.
122
+ */
123
+ forget(projectId) {
124
+ if (this._stacks.delete(projectId)) {
125
+ this._persist()
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Snapshot of all recorded stacks (insertion order).
131
+ * @returns {Array<{projectId:string, composeFile:string|string[], cwd:string, createdAt:string}>}
132
+ */
133
+ list() {
134
+ return Array.from(this._stacks.values()).map((s) => ({ ...s, composeFile: cloneComposeFile(s.composeFile) }))
135
+ }
136
+
137
+ _persist() {
138
+ try {
139
+ const dir = dirname(this._statePath)
140
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
141
+ const data = {
142
+ version: STATE_VERSION,
143
+ stacks: Array.from(this._stacks.values()),
144
+ }
145
+ // writeFileRestricted is atomic on both POSIX and Windows and cleans
146
+ // up its intermediate `.tmp` on rename failure — no manual tmp+rename
147
+ // wrapper needed.
148
+ writeFileRestricted(this._statePath, JSON.stringify(data, null, 2))
149
+ } catch (err) {
150
+ // Persistence is best-effort: a write failure must not take down the
151
+ // session that triggered it. The worst case degrades back to the
152
+ // pre-#5081 "in-memory only" behaviour.
153
+ // eslint-disable-next-line no-console
154
+ console.warn(`[byok-compose-state] failed to persist: ${err.message}`)
155
+ }
156
+ }
157
+
158
+ _load() {
159
+ if (!existsSync(this._statePath)) return
160
+ try {
161
+ const data = JSON.parse(readFileSync(this._statePath, 'utf-8'))
162
+ if (!data || data.version !== STATE_VERSION || !Array.isArray(data.stacks)) {
163
+ // Unknown version or corrupt shape — ignore rather than crash.
164
+ return
165
+ }
166
+ for (const entry of data.stacks) {
167
+ // Drop entries missing any required field (or with non-string
168
+ // values). A half-written / hand-edited record with an undefined
169
+ // composeFile or cwd would otherwise reach the boot sweep and call
170
+ // destroyComposeEnvironment with undefined args — which fails and,
171
+ // because a failed teardown is retained for retry, would never
172
+ // clear. Skipping it here is the safe default.
173
+ if (
174
+ !entry
175
+ || typeof entry.projectId !== 'string' || !entry.projectId
176
+ || !isValidComposeFile(entry.composeFile)
177
+ || typeof entry.cwd !== 'string' || !entry.cwd
178
+ ) {
179
+ continue
180
+ }
181
+ this._stacks.set(entry.projectId, {
182
+ projectId: entry.projectId,
183
+ composeFile: entry.composeFile,
184
+ cwd: entry.cwd,
185
+ // Normalise a missing/invalid createdAt rather than persisting
186
+ // `undefined` back out on the next write.
187
+ createdAt: typeof entry.createdAt === 'string' && entry.createdAt
188
+ ? entry.createdAt
189
+ : new Date().toISOString(),
190
+ })
191
+ }
192
+ } catch {
193
+ // Corrupt / non-JSON state file — start empty rather than crash.
194
+ }
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Boot-time garbage collector. Tears down every persisted compose stack via
200
+ * the backend's `destroyComposeEnvironment`, forgetting each one only after a
201
+ * successful teardown so a transient docker-down failure is retried on the
202
+ * next boot.
203
+ *
204
+ * @param {object} args
205
+ * @param {ByokComposeStateStore} args.store - The persistence store.
206
+ * @param {object} args.backend - Object with
207
+ * `destroyComposeEnvironment({ composeFile, composeProject, cwd })`.
208
+ * @returns {Promise<{swept:number, failed:number}>}
209
+ */
210
+ export async function sweepOrphanedComposeStacks({ store, backend } = {}) {
211
+ const stacks = store.list()
212
+ let swept = 0
213
+ let failed = 0
214
+ for (const stack of stacks) {
215
+ try {
216
+ await backend.destroyComposeEnvironment({
217
+ composeFile: stack.composeFile,
218
+ composeProject: stack.projectId,
219
+ cwd: stack.cwd,
220
+ })
221
+ // Only forget after a clean teardown — a failure leaves the entry on
222
+ // disk so the next boot retries.
223
+ store.forget(stack.projectId)
224
+ swept += 1
225
+ } catch (err) {
226
+ failed += 1
227
+ // eslint-disable-next-line no-console
228
+ console.warn(
229
+ `[byok-compose-state] sweep of ${stack.projectId} failed (will retry next boot): ${err.message}`,
230
+ )
231
+ }
232
+ }
233
+ return { swept, failed }
234
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Credential sourcing for the claude-byok provider.
3
+ *
4
+ * Priority order:
5
+ * 1. process.env.ANTHROPIC_API_KEY
6
+ * 2. the canonical credential store (`credential-store.js`,
7
+ * ~/.chroxy/credentials.json, mode 0600) — decryption-aware (#5154) and
8
+ * honoring the legacy `anthropicApiKey` alias for files written by the
9
+ * pre-#5867 single-key BYOK path.
10
+ *
11
+ * #5867: writes/clears now go through `setStoredCredential` /
12
+ * `deleteStoredCredential` (merge + at-rest encryption), so a BYOK set/clear no
13
+ * longer clobbers sibling provider keys or downgrades an encrypted store to
14
+ * plaintext. This module is now read-only (resolve + status + mask); the WS
15
+ * handlers call the store directly.
16
+ *
17
+ * Never logged. The redactor at logger.js scrubs `sk-ant-` and `Bearer`
18
+ * patterns before any log line lands on disk.
19
+ */
20
+ import { existsSync } from 'fs'
21
+ import { join } from 'path'
22
+ import { homedir } from 'os'
23
+ import { resolveStoredCredentialWithMeta } from './credential-store.js'
24
+
25
+ // Lazy-resolved per call so tests that mutate process.env.HOME between
26
+ // cases pick up the new home; if this were captured at module load, the
27
+ // path would freeze at the first import.
28
+ function credentialsFilePath() {
29
+ return join(homedir(), '.chroxy', 'credentials.json')
30
+ }
31
+
32
+ /**
33
+ * Resolve the Anthropic API key for a BYOK session. Env var wins; otherwise the
34
+ * cipher-aware credential store. The `reason` (when missing) preserves the
35
+ * store's read distinctions: bad mode, keychain-locked, corrupt envelope,
36
+ * file-absent, or present-but-no-Anthropic-credential.
37
+ *
38
+ * @returns {{ key: string, source: 'env' | 'file' } | { key: null, source: 'none', reason: string }}
39
+ */
40
+ export function resolveAnthropicApiKey() {
41
+ const envKey = process.env.ANTHROPIC_API_KEY
42
+ if (typeof envKey === 'string' && envKey.length > 0) {
43
+ return { key: envKey, source: 'env' }
44
+ }
45
+
46
+ const { value, fileExists, error } = resolveStoredCredentialWithMeta('ANTHROPIC_API_KEY')
47
+ if (value) {
48
+ return { key: value, source: 'file' }
49
+ }
50
+ const CREDENTIALS_FILE = credentialsFilePath()
51
+ let reason
52
+ if (error) {
53
+ reason = error
54
+ } else if (!fileExists) {
55
+ reason = `ANTHROPIC_API_KEY not set and ${CREDENTIALS_FILE} does not exist`
56
+ } else {
57
+ reason = `ANTHROPIC_API_KEY not set and no Anthropic credential is stored in ${CREDENTIALS_FILE}`
58
+ }
59
+ return { key: null, source: 'none', reason }
60
+ }
61
+
62
+ /**
63
+ * Dashboard / status-line friendly view of the current credential state.
64
+ * Returns `{ status, source, masked?, reason? }`:
65
+ * - status: 'set' | 'missing'
66
+ * - source: 'env' | 'file' | 'none'
67
+ * - masked: when status='set', a redacted view of the key (12-char prefix max)
68
+ * - reason: when status='missing', a human-readable explanation
69
+ *
70
+ * Wraps `resolveAnthropicApiKey` so callers don't accidentally surface the
71
+ * raw key string — they only ever see the masked form.
72
+ */
73
+ export function getAnthropicApiKeyStatus() {
74
+ const r = resolveAnthropicApiKey()
75
+ // #4144: report file presence independently of which source wins. When
76
+ // the env var is set, the file is shadowed by env precedence; the
77
+ // dashboard uses this to surface "stale file on disk" UX and to keep
78
+ // the Remove button enabled even when source is 'env'.
79
+ //
80
+ // Theoretical race: the file could be (un)linked between
81
+ // resolveAnthropicApiKey() and hasStoredCredentials(). Acceptable for
82
+ // a status query — the dashboard polls on open and after every
83
+ // set/clear, so any transient inconsistency self-heals on the next
84
+ // refresh. We're not making security decisions on this flag.
85
+ const fileExists = hasStoredCredentials()
86
+ if (r.key) {
87
+ return { status: 'set', source: r.source, masked: maskApiKey(r.key), fileExists }
88
+ }
89
+ return { status: 'missing', source: 'none', reason: r.reason, fileExists }
90
+ }
91
+
92
+ /**
93
+ * Whether `~/.chroxy/credentials.json` currently exists on disk, regardless
94
+ * of mode validity, JSON shape, or whether resolveAnthropicApiKey would
95
+ * accept it. Used by the dashboard's BYOK section to surface stale-file
96
+ * UX even when an env var wins precedence (#4144).
97
+ *
98
+ * @returns {boolean}
99
+ */
100
+ export function hasStoredCredentials() {
101
+ try {
102
+ return existsSync(credentialsFilePath())
103
+ } catch {
104
+ return false
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Mask an API key for display in logs / UI / errors. Returns a string with
110
+ * a short prefix and a redaction marker. Never returns the full key —
111
+ * even for unexpectedly short inputs, where slice(0, 12) would otherwise
112
+ * echo the whole thing (caught by Copilot review on #4055).
113
+ *
114
+ * @param {string} key
115
+ * @returns {string}
116
+ */
117
+ export function maskApiKey(key) {
118
+ if (typeof key !== 'string' || key.length === 0) return '<missing>'
119
+ // For a normal Anthropic key (sk-ant-api03-… ~108 chars), show 12 + redact
120
+ // the rest. For an unexpectedly short input, show no more than the first
121
+ // 1/3 (rounded down) so we never echo more than a third of the secret,
122
+ // and always emit a redaction tail so the format stays consistent.
123
+ const visibleLen = Math.min(12, Math.floor(key.length / 3))
124
+ const visible = key.slice(0, visibleLen)
125
+ const redacted = key.length - visibleLen
126
+ return `${visible}...[${redacted} chars redacted]`
127
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Translate `@anthropic-ai/sdk` streaming events to chroxy session events.
3
+ *
4
+ * The SDK exposes `client.messages.stream(...)` whose async iterator yields
5
+ * a small set of event types per the Anthropic API SSE contract:
6
+ *
7
+ * message_start — turn opens; carries model + message id
8
+ * content_block_start — a new block (text or tool_use) starts
9
+ * content_block_delta — incremental text or tool input JSON
10
+ * content_block_stop — a block finishes
11
+ * message_delta — turn-level metadata (stop_reason, usage)
12
+ * message_stop — turn ends
13
+ *
14
+ * We map these to the small set of events chroxy's WebSocket protocol
15
+ * speaks. This module is a pure function so it's testable against recorded
16
+ * fixture streams without an Anthropic API key.
17
+ *
18
+ * Returns `null` for events the caller doesn't need to forward (pings,
19
+ * unrecognized future event types). The translator never throws on an
20
+ * unknown shape — forward as `unknown` and let the caller decide.
21
+ *
22
+ * ## Design decision: block-type tracking lives in the SESSION, not here (#4059)
23
+ *
24
+ * The `content_block_stop` event we emit carries only `{ kind, index }` — NOT
25
+ * the block type (text / tool_use / thinking). PR 2 of the BYOK epic (#4047)
26
+ * needs to know on `content_block_stop` whether the just-finished block was a
27
+ * tool_use (so it can parse the accumulated `tool_input_delta.partial` strings
28
+ * and dispatch the tool) versus a text or thinking block (no action — those
29
+ * are already streamed live via `stream_delta` / `thinking_delta`). The
30
+ * consumer (`byok-session.js`) is expected to maintain its own
31
+ * `Map<index, blockType>` populated on `content_block_start` and queried on
32
+ * `content_block_stop`.
33
+ *
34
+ * Rationale for keeping this OUT of the translator:
35
+ * - **Purity is the translator's best property.** Adding stateful tracking
36
+ * would move it from a pure function (testable against fixture streams with
37
+ * no setup) to a stateful object that needs construction + cleanup. The
38
+ * fixture-test pattern in `byok-event-translator.test.js` would either lose
39
+ * its directness or grow setup boilerplate for every test.
40
+ * - **The tracking state belongs to the consumer's turn lifecycle.** The
41
+ * session already maintains other per-turn state (active turn id, partial
42
+ * tool-input JSON accumulator); colocating the block-type map there keeps
43
+ * the lifecycle simple — one place owns "what's in flight this turn."
44
+ * - **PR 1 doesn't need it.** Pinning the choice now avoids a translator
45
+ * refactor later when PR 2's needs become concrete.
46
+ *
47
+ * If a future need genuinely requires the translator to know block types
48
+ * (e.g. emitting different translated events per type without exposing
49
+ * indices), revisit this — it's not load-bearing, just the path of least
50
+ * coupling today.
51
+ */
52
+
53
+ /**
54
+ * @typedef {object} TranslatedEvent
55
+ * @property {'stream_start'|'stream_delta'|'tool_start'|'tool_input_delta'|'thinking_delta'|'content_block_stop'|'message_delta'|'result'|'unknown'} kind
56
+ * @property {string} [model] Set on stream_start
57
+ * @property {string} [messageId] Set on stream_start
58
+ * @property {string} [text] Set on stream_delta / thinking_delta
59
+ * @property {string} [toolUseId] Set on tool_start
60
+ * @property {string} [toolName] Set on tool_start
61
+ * @property {number} [index] Block index (tool_start, content_block_stop)
62
+ * @property {string} [partial] Set on tool_input_delta — partial JSON
63
+ * @property {string} [stopReason] Set on message_delta / result
64
+ * @property {object} [usage] Token counts (input_tokens, output_tokens, cache_*)
65
+ * @property {string} [sdkType] Original SDK event type when kind === 'unknown'
66
+ */
67
+
68
+ /**
69
+ * @param {object} event - Event from @anthropic-ai/sdk async iterator
70
+ * @returns {TranslatedEvent | null}
71
+ */
72
+ export function translateSdkEvent(event) {
73
+ if (!event || typeof event !== 'object' || typeof event.type !== 'string') {
74
+ return null
75
+ }
76
+
77
+ switch (event.type) {
78
+ case 'message_start':
79
+ return {
80
+ kind: 'stream_start',
81
+ model: event.message?.model,
82
+ messageId: event.message?.id,
83
+ }
84
+
85
+ case 'content_block_start': {
86
+ const cb = event.content_block
87
+ if (cb?.type === 'tool_use') {
88
+ return {
89
+ kind: 'tool_start',
90
+ toolUseId: cb.id,
91
+ toolName: cb.name,
92
+ index: event.index,
93
+ }
94
+ }
95
+ // text / thinking blocks: nothing to emit at start — wait for the
96
+ // first delta. Returning null avoids an "empty tool_start" smell.
97
+ return null
98
+ }
99
+
100
+ case 'content_block_delta': {
101
+ const delta = event.delta
102
+ if (delta?.type === 'text_delta' && typeof delta.text === 'string') {
103
+ return { kind: 'stream_delta', text: delta.text, index: event.index }
104
+ }
105
+ if (delta?.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
106
+ return { kind: 'tool_input_delta', partial: delta.partial_json, index: event.index }
107
+ }
108
+ if (delta?.type === 'thinking_delta' && typeof delta.thinking === 'string') {
109
+ return { kind: 'thinking_delta', text: delta.thinking, index: event.index }
110
+ }
111
+ // Future delta variants — return null so callers don't error out
112
+ // on a new event type from a future SDK rev.
113
+ return null
114
+ }
115
+
116
+ case 'content_block_stop':
117
+ return { kind: 'content_block_stop', index: event.index }
118
+
119
+ case 'message_delta':
120
+ return {
121
+ kind: 'message_delta',
122
+ stopReason: event.delta?.stop_reason,
123
+ usage: event.usage,
124
+ }
125
+
126
+ case 'message_stop':
127
+ return { kind: 'result' }
128
+
129
+ // ping is for heartbeats — no chroxy event needed.
130
+ case 'ping':
131
+ return null
132
+
133
+ default:
134
+ return { kind: 'unknown', sdkType: event.type }
135
+ }
136
+ }