@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,35 @@
1
+ /**
2
+ * Render a byte count as a human-readable string with a binary-prefix unit
3
+ * (`B`, `KiB`, `MiB`, `GiB`). Used in operator log lines where a raw byte
4
+ * count is hard to scan at a glance — e.g. the `stdin_dropped` cumulative
5
+ * total at the 10 MiB error-escalation threshold reads `10485760` raw, but
6
+ * `10.0 MiB` after formatting (#3543).
7
+ *
8
+ * Conventions:
9
+ * - Below 1024: `${n} B` (no decimal — bytes are exact)
10
+ * - 1024 .. 1024^2-1: `${k.kk} KiB` (one decimal)
11
+ * - 1024^2 .. 1024^3-1: `${m.mm} MiB` (one decimal)
12
+ * - >= 1024^3: `${g.gg} GiB` (one decimal)
13
+ *
14
+ * The decimal is always one digit so threshold-cross log lines stay aligned
15
+ * and scriptable consumers can parse the suffix with a fixed-width regex.
16
+ *
17
+ * @param {number} bytes - Non-negative integer byte count.
18
+ * @returns {string} Humanised label, e.g. `"10.0 MiB"`.
19
+ */
20
+ export function formatBytes(bytes) {
21
+ // Defensive: non-finite or negative inputs fall back to a B label so the
22
+ // caller's log line stays well-formed even if it ever hands us junk.
23
+ if (!Number.isFinite(bytes) || bytes < 0) {
24
+ return `${bytes} B`
25
+ }
26
+
27
+ const KIB = 1024
28
+ const MIB = 1024 * 1024
29
+ const GIB = 1024 * 1024 * 1024
30
+
31
+ if (bytes < KIB) return `${bytes} B`
32
+ if (bytes < MIB) return `${(bytes / KIB).toFixed(1)} KiB`
33
+ if (bytes < GIB) return `${(bytes / MIB).toFixed(1)} MiB`
34
+ return `${(bytes / GIB).toFixed(1)} GiB`
35
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Pre-flight binary + credential checks for provider sessions.
3
+ *
4
+ * Runs BEFORE `new ProviderClass(...)` in SessionManager.createSession so a
5
+ * missing binary or credential surfaces as a clean, actionable error rather
6
+ * than a cryptic ENOENT at spawn time. See issue #2962.
7
+ *
8
+ * Each provider class declares its requirements via `static get preflight()`:
9
+ *
10
+ * {
11
+ * label: 'Codex',
12
+ * binary: {
13
+ * name: 'codex',
14
+ * candidates: ['/opt/homebrew/bin/codex', ...],
15
+ * installHint: 'install Codex CLI',
16
+ * },
17
+ * credentials: {
18
+ * envVars: ['OPENAI_API_KEY'],
19
+ * hint: 'set OPENAI_API_KEY',
20
+ * optional: false,
21
+ * },
22
+ * }
23
+ *
24
+ * Credentials marked `optional: true` (e.g. Claude — login subscription is a
25
+ * valid alternative to ANTHROPIC_API_KEY) do NOT throw when no env var is set.
26
+ *
27
+ * Containerised providers (`capabilities.containerized === true`) are skipped
28
+ * entirely — the binary lives inside the container and the host preflight
29
+ * cannot meaningfully check it.
30
+ */
31
+
32
+ import { existsSync, accessSync, constants } from 'fs'
33
+ import { isAbsolute } from 'path'
34
+ import { resolveBinary } from './resolve-binary.js'
35
+
36
+ /**
37
+ * Thrown when a provider's required binary cannot be located or executed.
38
+ */
39
+ export class ProviderBinaryNotFoundError extends Error {
40
+ constructor({ provider, binary, candidates, installHint }) {
41
+ const hint = installHint || `install ${binary}`
42
+ const tried = candidates && candidates.length > 0
43
+ ? ` (checked PATH and ${candidates.join(', ')})`
44
+ : ' (checked PATH)'
45
+ super(`${provider}: required binary "${binary}" not found${tried}. ${hint}.`)
46
+ this.name = 'ProviderBinaryNotFoundError'
47
+ this.code = 'PROVIDER_BINARY_NOT_FOUND'
48
+ this.provider = provider
49
+ this.binary = binary
50
+ this.candidates = candidates || []
51
+ this.installHint = hint
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Thrown when none of a provider's required credential env vars are present.
57
+ */
58
+ export class ProviderCredentialMissingError extends Error {
59
+ constructor({ provider, envVars, hint }) {
60
+ const joined = envVars.join(' or ')
61
+ const finalHint = hint || `set ${joined}`
62
+ super(`${provider}: required credential not set — ${joined}. ${finalHint}.`)
63
+ this.name = 'ProviderCredentialMissingError'
64
+ this.code = 'PROVIDER_CREDENTIAL_MISSING'
65
+ this.provider = provider
66
+ this.envVars = envVars
67
+ this.hint = finalHint
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Verify a binary path exists and is executable by the current process.
73
+ * Returns true if the resolved path is absolute, exists, and the X bit is set.
74
+ *
75
+ * @param {string} resolvedPath
76
+ * @returns {boolean}
77
+ */
78
+ function isExecutableFile(resolvedPath) {
79
+ if (!isAbsolute(resolvedPath)) return false
80
+ if (!existsSync(resolvedPath)) return false
81
+ try {
82
+ accessSync(resolvedPath, constants.X_OK)
83
+ return true
84
+ } catch {
85
+ return false
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Run binary + credential preflight for a provider class.
91
+ *
92
+ * Throws ProviderBinaryNotFoundError or ProviderCredentialMissingError if
93
+ * the spec's requirements aren't met. No-op when:
94
+ * - The provider doesn't declare a `static get preflight()`
95
+ * - The provider is containerised (binary lives inside the container)
96
+ *
97
+ * @param {Function} ProviderClass - Session class with optional `preflight` getter
98
+ * @param {object} [options]
99
+ * @param {NodeJS.ProcessEnv} [options.env=process.env] - Env source (for tests)
100
+ * @throws {ProviderBinaryNotFoundError|ProviderCredentialMissingError}
101
+ */
102
+ export function runProviderPreflight(ProviderClass, { env = process.env } = {}) {
103
+ if (!ProviderClass) return
104
+
105
+ // Containerised providers run their binary inside the container, so a host
106
+ // preflight check would always fail (or worse — silently pass against a
107
+ // wrong binary). Trust the container image / health probe instead.
108
+ if (ProviderClass.capabilities?.containerized) return
109
+
110
+ const spec = ProviderClass.preflight
111
+ if (!spec) return
112
+
113
+ const providerLabel = spec.label || ProviderClass.name || 'provider'
114
+
115
+ if (spec.binary && spec.binary.name) {
116
+ const candidates = spec.binary.candidates || []
117
+ const resolved = resolveBinary(spec.binary.name, candidates)
118
+ // resolveBinary returns the bare name when nothing on PATH or in
119
+ // candidates matched — that's the failure signal.
120
+ if (!isExecutableFile(resolved)) {
121
+ throw new ProviderBinaryNotFoundError({
122
+ provider: providerLabel,
123
+ binary: spec.binary.name,
124
+ candidates,
125
+ installHint: spec.binary.installHint,
126
+ })
127
+ }
128
+ }
129
+
130
+ if (spec.credentials && Array.isArray(spec.credentials.envVars) && spec.credentials.envVars.length > 0) {
131
+ // Optional credentials never block creation — Claude can authenticate
132
+ // via a prior `claude login` subscription instead of ANTHROPIC_API_KEY.
133
+ if (spec.credentials.optional) return
134
+ const matched = spec.credentials.envVars.find(v => env[v])
135
+ if (!matched) {
136
+ throw new ProviderCredentialMissingError({
137
+ provider: providerLabel,
138
+ envVars: spec.credentials.envVars,
139
+ hint: spec.credentials.hint,
140
+ })
141
+ }
142
+ }
143
+ }
@@ -0,0 +1,91 @@
1
+ import { execFileSync } from 'child_process'
2
+ import { existsSync } from 'fs'
3
+
4
+ const isWindows = process.platform === 'win32'
5
+
6
+ // Windows extension preference. We want a form that can be spawned DIRECTLY by
7
+ // `child_process.spawn` (no shell) AND by node-pty: `.exe`/`.com` qualify, so
8
+ // they win. The `.cmd`/`.bat` shims npm also installs work under node-pty and,
9
+ // on the plain-subprocess path, only after cmd.exe routing (see win-spawn.js) —
10
+ // so they rank below the native executables but above anything else. The bare
11
+ // extensionless entry npm installs alongside them is a POSIX shell wrapper: it
12
+ // is NOT a valid Win32 executable and BOTH spawn paths refuse it (child_process
13
+ // → ENOENT, node-pty → "error code 193"), so it is never selected.
14
+ const WIN_EXT_PRIORITY = ['.exe', '.com', '.cmd', '.bat']
15
+
16
+ // PATHEXT is the OS's authority on which extensions are "executable" on this
17
+ // host. Anything outside it (the extensionless POSIX wrapper) is not runnable.
18
+ function windowsExecutableExtensions() {
19
+ return (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD')
20
+ .split(';')
21
+ .map((s) => s.trim().toLowerCase())
22
+ .filter(Boolean)
23
+ }
24
+
25
+ function extensionOf(filePath) {
26
+ const sep = Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/'))
27
+ const base = sep >= 0 ? filePath.slice(sep + 1) : filePath
28
+ const dot = base.lastIndexOf('.')
29
+ return dot > 0 ? base.slice(dot).toLowerCase() : ''
30
+ }
31
+
32
+ // `where` prints every match on PATH, one per line and in PATH/PATHEXT order.
33
+ // Pick the best directly-runnable executable from that list (see WIN_EXT_PRIORITY).
34
+ // Exported for unit testing the selection logic independent of the host platform.
35
+ export function pickWindowsExecutable(lines) {
36
+ const pathext = windowsExecutableExtensions()
37
+ const runnable = lines.filter((p) => pathext.includes(extensionOf(p)))
38
+ for (const wanted of WIN_EXT_PRIORITY) {
39
+ const hit = runnable.find((p) => extensionOf(p) === wanted)
40
+ if (hit) return hit
41
+ }
42
+ // Some other PATHEXT-registered executable (rare for our binaries) still beats
43
+ // the extensionless wrapper, which is filtered out above.
44
+ return runnable[0] || null
45
+ }
46
+
47
+ /**
48
+ * Resolve the full path to a named binary.
49
+ *
50
+ * First tries the OS PATH lookup so any binary on the caller's PATH is found
51
+ * automatically — `which` on POSIX, `where` on Windows (`which` does not exist
52
+ * on native Windows; calling it threw ENOENT and silently dropped every
53
+ * PATH-installed binary into the candidates/bare-name fallback). On Windows
54
+ * `where` returns one match per line and may include a non-runnable POSIX shell
55
+ * wrapper, so we select the best directly-spawnable executable rather than the
56
+ * first line (see pickWindowsExecutable).
57
+ *
58
+ * If the PATH lookup fails (e.g. the process was started with a minimal PATH
59
+ * such as just the Node bin directory), each entry in `candidates` is tested
60
+ * with `existsSync`. If none exist, `name` is returned as-is so the caller gets
61
+ * a descriptive ENOENT rather than a silent failure.
62
+ *
63
+ * @param {string} name - Binary name (e.g. 'git', 'gemini', 'codex')
64
+ * @param {string[]} candidates - Ordered list of absolute fallback paths to try
65
+ * @returns {string} Resolved absolute path, or `name` if not found anywhere
66
+ */
67
+ export function resolveBinary(name, candidates) {
68
+ // Try PATH first
69
+ try {
70
+ const finder = isWindows ? 'where' : 'which'
71
+ const out = execFileSync(finder, [name], {
72
+ encoding: 'utf-8',
73
+ stdio: ['pipe', 'pipe', 'pipe'],
74
+ })
75
+ const lines = out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
76
+ if (isWindows) {
77
+ const picked = pickWindowsExecutable(lines)
78
+ if (picked) return picked
79
+ } else if (lines.length > 0) {
80
+ return lines[0]
81
+ }
82
+ } catch { /* binary not on PATH (or the finder itself is unavailable) */ }
83
+
84
+ // Fall back to well-known locations
85
+ for (const c of candidates || []) {
86
+ if (existsSync(c)) return c
87
+ }
88
+
89
+ // Last resort — return bare name and let the caller handle ENOENT
90
+ return name
91
+ }
@@ -0,0 +1,59 @@
1
+ // utils/respawn-rate-limiter.js (#5349) — a rolling-window cap on session
2
+ // respawns, shared by CliSession and ClaudeTuiSession.
3
+ //
4
+ // Both providers already bound CONSECUTIVE respawns via `_respawnCount` (max 5
5
+ // with backoff), but that counter resets to 0 on every warmup that survives
6
+ // (system.init / first output). So a session that dies a few seconds AFTER each
7
+ // successful warmup flaps forever — the consecutive cap never trips. This adds
8
+ // a SECOND, independent cap: at most `maxPerWindow` respawns per rolling
9
+ // `windowMs`, regardless of warmup success, so a persistently-flapping backend
10
+ // eventually gives up.
11
+ //
12
+ // Clock: `now` is injectable for tests and defaults to Date.now. Wall-clock can
13
+ // jump BACKWARD (NTP correction / VM suspend), which would break head-pruning
14
+ // (it assumes `_times` is non-decreasing). So record() clamps each timestamp to
15
+ // be >= the previous one: a backward step is treated as "no time passed", which
16
+ // keeps `_times` sorted and the prune correct, and is the conservative
17
+ // direction (it can only make the window advance slower, never falsely flag a
18
+ // healthy session).
19
+
20
+ const DEFAULT_MAX_PER_WINDOW = 10
21
+ const DEFAULT_WINDOW_MS = 5 * 60 * 1000
22
+
23
+ export class RespawnRateLimiter {
24
+ /**
25
+ * @param {object} [opts]
26
+ * @param {number} [opts.maxPerWindow=10] respawns allowed per window
27
+ * @param {number} [opts.windowMs=300000] rolling window length in ms
28
+ * @param {() => number} [opts.now=Date.now] clock source (injectable for tests)
29
+ */
30
+ constructor({ maxPerWindow = DEFAULT_MAX_PER_WINDOW, windowMs = DEFAULT_WINDOW_MS, now = Date.now } = {}) {
31
+ this.maxPerWindow = maxPerWindow
32
+ this.windowMs = windowMs
33
+ this._now = now
34
+ this._times = []
35
+ }
36
+
37
+ /**
38
+ * Record a respawn attempt. Returns true if still within the cap (caller may
39
+ * proceed), false if the cap is exceeded (caller should give up).
40
+ * @returns {boolean}
41
+ */
42
+ record() {
43
+ // Clamp to be non-decreasing so a backward clock step can't leave `_times`
44
+ // out of order (which would defeat the head-prune below and grow the array
45
+ // unboundedly).
46
+ const last = this._times.length ? this._times[this._times.length - 1] : -Infinity
47
+ const t = Math.max(this._now(), last)
48
+ this._times.push(t)
49
+ const cutoff = t - this.windowMs
50
+ while (this._times.length && this._times[0] < cutoff) this._times.shift()
51
+ return this._times.length <= this.maxPerWindow
52
+ }
53
+
54
+ /** Number of respawns currently inside the window (after the last record). */
55
+ get count() { return this._times.length }
56
+
57
+ /** Forget all recorded respawns (e.g. on a clean, intentional restart). */
58
+ reset() { this._times = [] }
59
+ }
@@ -0,0 +1,58 @@
1
+ // utils/sleep.js (#5371) — shared cancellable sleep + exponential-backoff calc.
2
+ //
3
+ // Replaces the hand-rolled
4
+ // new Promise((resolve, reject) => {
5
+ // const timer = setTimeout(resolve, ms)
6
+ // signal.addEventListener('abort', () => { clearTimeout(timer); reject() }, { once: true })
7
+ // })
8
+ // idiom that was copied across tunnel/base.js (start-retry + recovery loops)
9
+ // and push.js. Each copy was a chance to forget the clearTimeout or the
10
+ // listener cleanup — a hung promise / leaked listener.
11
+ //
12
+ // Scope note: supervisor.js's timers are stored-field restart timers and a
13
+ // reject-after-timeout RACE (Promise.race against a push), not this
14
+ // sleep-with-abort idiom, so they are intentionally NOT migrated here.
15
+
16
+ /**
17
+ * Resolve after `ms` milliseconds. When an AbortSignal is supplied and fires,
18
+ * the timer is cleared and the promise REJECTS with an AbortError — callers
19
+ * (the tunnel start/recovery retry loops) rely on the rejection to bail out of
20
+ * their wait rather than silently finishing the sleep.
21
+ *
22
+ * @param {number} ms delay in milliseconds
23
+ * @param {AbortSignal} [signal] optional cancellation signal
24
+ * @returns {Promise<void>}
25
+ */
26
+ export function sleep(ms, signal) {
27
+ if (signal?.aborted) return Promise.reject(abortError())
28
+ return new Promise((resolve, reject) => {
29
+ const onAbort = () => {
30
+ clearTimeout(timer)
31
+ reject(abortError())
32
+ }
33
+ const timer = setTimeout(() => {
34
+ if (signal) signal.removeEventListener('abort', onAbort)
35
+ resolve()
36
+ }, ms)
37
+ if (signal) signal.addEventListener('abort', onAbort, { once: true })
38
+ })
39
+ }
40
+
41
+ function abortError() {
42
+ const err = new Error('The operation was aborted')
43
+ err.name = 'AbortError'
44
+ return err
45
+ }
46
+
47
+ /**
48
+ * Exponential backoff for a 1-indexed attempt: `base * 2^(attempt-1)`,
49
+ * optionally capped at `max`.
50
+ *
51
+ * @param {number} attempt 1-indexed attempt number
52
+ * @param {number} base base delay in milliseconds
53
+ * @param {number} [max] optional ceiling
54
+ * @returns {number} delay in milliseconds
55
+ */
56
+ export function backoffDelay(attempt, base, max = Infinity) {
57
+ return Math.min(base * Math.pow(2, attempt - 1), max)
58
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * buildSpawnEnv — construct the environment object for a child CLI process.
3
+ *
4
+ * Each provider is either:
5
+ * - "allowlist" mode: only explicitly allowed keys are forwarded. Used for
6
+ * third-party providers (codex, gemini) so operator secrets
7
+ * (ANTHROPIC_API_KEY, CHROXY_HOOK_SECRET, arbitrary DB creds, etc.) never
8
+ * leak into their subprocess environment.
9
+ * - "denylist" mode: the full parent env is forwarded minus a small set of
10
+ * keys that would be harmful (ANTHROPIC_API_KEY, plus the chroxy-owned
11
+ * daemon secrets in CHROXY_SECRET_DENYLIST). Used for the Claude CLI where
12
+ * the user's full environment is expected to be available.
13
+ *
14
+ * Centralising the pattern here means future providers get safe-by-default
15
+ * env handling automatically.
16
+ *
17
+ * Credential-store fallback (#3855): for provider credential env vars the
18
+ * operator's shell has NOT exported, the value is sourced from the credential
19
+ * store (~/.chroxy/credentials.json, mode 0600). This is what lets a
20
+ * Tauri/launchd GUI launch (cwd=/, minimal PATH, no rc file sourced) spawn a
21
+ * working session from stored credentials alone. Process env always wins, so a
22
+ * shell export overrides the store. The Claude denylist still strips
23
+ * ANTHROPIC_API_KEY (subscription-default behaviour is preserved); only the
24
+ * non-denylisted credential keys are eligible for store injection.
25
+ */
26
+ import { resolveCredential, isKnownCredentialKey } from '../credential-store.js'
27
+
28
+ // Standard vars every child process needs for its runtime to function.
29
+ // Shell PATH, locale, TERM, TMPDIR, user/home identity.
30
+ const STANDARD_ALLOWLIST = [
31
+ 'PATH',
32
+ 'HOME',
33
+ 'USER',
34
+ 'LOGNAME',
35
+ 'SHELL',
36
+ 'TERM',
37
+ 'LANG',
38
+ 'LC_ALL',
39
+ 'LC_CTYPE',
40
+ 'LC_COLLATE',
41
+ 'LC_MESSAGES',
42
+ 'TMPDIR',
43
+ 'TMP',
44
+ 'TEMP',
45
+ 'TZ',
46
+ 'XDG_CONFIG_HOME',
47
+ 'XDG_DATA_HOME',
48
+ 'XDG_CACHE_HOME',
49
+ 'XDG_RUNTIME_DIR',
50
+ 'PWD',
51
+ 'OLDPWD',
52
+ 'COLUMNS',
53
+ 'LINES',
54
+ 'COLORTERM',
55
+ 'DISPLAY',
56
+ 'SSH_AUTH_SOCK',
57
+ 'NODE_EXTRA_CA_CERTS',
58
+ // HTTP proxy vars — needed for corporate/enterprise environments where
59
+ // outbound traffic is routed through a forward proxy. Values are typically
60
+ // infrastructure URLs; note that proxy URLs can legally embed credentials
61
+ // (http://user:pass@proxy:8080) — avoid logging these values.
62
+ 'HTTP_PROXY',
63
+ 'HTTPS_PROXY',
64
+ 'NO_PROXY',
65
+ 'ALL_PROXY',
66
+ 'http_proxy',
67
+ 'https_proxy',
68
+ 'no_proxy',
69
+ 'all_proxy',
70
+ ]
71
+
72
+ // Chroxy-owned daemon secrets that must NEVER reach any spawned child process,
73
+ // regardless of provider or mode (#6311). API_TOKEN is the full-authority
74
+ // primary bearer token (docs/security/bearer-token-authority.md §1/§3): a tool,
75
+ // MCP server, subagent, or shell command the agent runs could read it from
76
+ // process.env and gain full control of the daemon — every session's history,
77
+ // input, model switching and settings — over the WebSocket/HTTP control surface.
78
+ // The narrowly-scoped per-session CHROXY_HOOK_SECRET is passed explicitly via
79
+ // `extras` instead; it only authorises POST /permission, so it is safe to hand
80
+ // to the child.
81
+ //
82
+ // Allowlist-mode providers (codex, gemini) already exclude these by omission;
83
+ // this set is the belt-and-braces guarantee for denylist-mode providers (claude)
84
+ // and is re-used by the claude-tui PTY spawn path (claude-tui-session.js).
85
+ export const CHROXY_SECRET_DENYLIST = [
86
+ 'API_TOKEN',
87
+ ]
88
+
89
+ const PROVIDERS = {
90
+ codex: {
91
+ mode: 'allowlist',
92
+ // OpenAI credentials + endpoint overrides only. No cross-provider keys.
93
+ providerAllowlist: [
94
+ 'OPENAI_API_KEY',
95
+ 'OPENAI_BASE_URL',
96
+ 'OPENAI_ORG_ID',
97
+ 'OPENAI_ORGANIZATION',
98
+ 'OPENAI_PROJECT',
99
+ 'OPENAI_PROJECT_ID',
100
+ ],
101
+ },
102
+ gemini: {
103
+ mode: 'allowlist',
104
+ // Google/Gemini credentials only.
105
+ providerAllowlist: [
106
+ 'GEMINI_API_KEY',
107
+ 'GOOGLE_API_KEY',
108
+ 'GOOGLE_APPLICATION_CREDENTIALS',
109
+ 'GOOGLE_CLOUD_PROJECT',
110
+ 'GOOGLE_GENAI_USE_VERTEXAI',
111
+ 'GOOGLE_CLOUD_LOCATION',
112
+ ],
113
+ },
114
+ claude: {
115
+ mode: 'denylist',
116
+ // Strip the API key so the CLI uses OAuth/subscription auth instead of
117
+ // burning API credits. All other parent env keys pass through so the
118
+ // user's shell environment is available to Claude Code tools.
119
+ denylist: [
120
+ 'ANTHROPIC_API_KEY',
121
+ ],
122
+ // #3855: credential-store keys this provider may pull from the store when
123
+ // the shell hasn't exported them. Scoped to the Claude provider's OWN
124
+ // credential only — never other providers' keys (cross-provider isolation:
125
+ // an OpenAI/Gemini key stored for those providers must not leak into the
126
+ // Claude subprocess env). ANTHROPIC_API_KEY is deliberately excluded so
127
+ // the CLI keeps using subscription/OAuth auth.
128
+ storeInjectKeys: [
129
+ 'CLAUDE_CODE_OAUTH_TOKEN',
130
+ ],
131
+ },
132
+ }
133
+
134
+ /**
135
+ * Build the env object to pass to child_process.spawn().
136
+ *
137
+ * @param {'codex'|'gemini'|'claude'} provider
138
+ * @param {Record<string, string>} [extras] - provider-specific additions that
139
+ * override any env passthrough (e.g. CHROXY_HOOK_SECRET for claude,
140
+ * CI=1 for headless mode, etc.).
141
+ * @returns {Record<string, string>} env object suitable for spawn()
142
+ */
143
+ export function buildSpawnEnv(provider, extras = {}) {
144
+ const config = PROVIDERS[provider]
145
+ if (!config) {
146
+ throw new Error(`buildSpawnEnv: unknown provider "${provider}"`)
147
+ }
148
+
149
+ if (config.mode === 'allowlist') {
150
+ const env = {}
151
+ const allowed = [...STANDARD_ALLOWLIST, ...config.providerAllowlist]
152
+ for (const key of allowed) {
153
+ if (process.env[key] !== undefined) {
154
+ env[key] = process.env[key]
155
+ continue
156
+ }
157
+ // #3855: env var not exported — fall back to the credential store for
158
+ // the credential keys it manages. resolveCredential() already enforces
159
+ // env > store precedence; here process.env was undefined so a non-null
160
+ // result is necessarily store-sourced.
161
+ if (isKnownCredentialKey(key)) {
162
+ const resolved = resolveCredential(key)
163
+ if (resolved.value) env[key] = resolved.value
164
+ }
165
+ }
166
+ return { ...env, ...extras }
167
+ }
168
+
169
+ // denylist mode: start from full parent env, remove sensitive keys.
170
+ // #6311: always strip the chroxy-owned daemon secrets in addition to the
171
+ // provider's own denylist, so the full-authority API_TOKEN never reaches a
172
+ // denylist-mode child (the parent env is otherwise forwarded wholesale).
173
+ const effectiveDenylist = [...config.denylist, ...CHROXY_SECRET_DENYLIST]
174
+ const parentEnv = { ...process.env }
175
+ for (const key of effectiveDenylist) {
176
+ delete parentEnv[key]
177
+ }
178
+ // #3855: inject ONLY this provider's own credential-store keys that the
179
+ // shell did not export (e.g. CLAUDE_CODE_OAUTH_TOKEN for claude). Scoped via
180
+ // the per-provider `storeInjectKeys` allowlist so other providers' stored
181
+ // secrets (OPENAI_API_KEY, GEMINI_API_KEY) never leak into this subprocess.
182
+ // ANTHROPIC_API_KEY is excluded from storeInjectKeys AND denylisted, so the
183
+ // CLI keeps using subscription/OAuth auth.
184
+ const denySet = new Set(effectiveDenylist)
185
+ for (const key of config.storeInjectKeys || []) {
186
+ if (denySet.has(key)) continue
187
+ if (!isKnownCredentialKey(key)) continue
188
+ if (parentEnv[key] !== undefined) continue
189
+ const resolved = resolveCredential(key)
190
+ if (resolved.value) parentEnv[key] = resolved.value
191
+ }
192
+ return { ...parentEnv, ...extras }
193
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Shared validation regexes (#6201 DRY consolidation).
3
+ *
4
+ * These patterns validate untrusted string inputs and were previously copied
5
+ * verbatim across several modules — the copies even cross-referenced each other
6
+ * in comments ("same regex as docker-sdk-session.js"), the textbook DRY smell.
7
+ * Single-sourcing them keeps every call site in lockstep, so a future tightening
8
+ * (or loosening) lands everywhere at once instead of drifting silently.
9
+ */
10
+
11
+ /**
12
+ * Valid POSIX/container username: starts with a lowercase letter or underscore,
13
+ * then up to 31 more lowercase-alphanumeric, underscore, or hyphen characters
14
+ * (32 total — the traditional `useradd` limit). Refusing anything else stops a
15
+ * caller-supplied string from smuggling a `docker exec -u` flag.
16
+ */
17
+ export const VALID_USERNAME_RE = /^[a-z_][a-z0-9_-]{0,31}$/
18
+
19
+ /**
20
+ * Lower-case SHA-256 hex digest: exactly 64 hex characters. Used to validate
21
+ * trust-ledger hashes (path-hash-trust-ledger.js, skills-trust.js).
22
+ */
23
+ export const HEX64 = /^[0-9a-f]{64}$/