@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,167 @@
1
+ /**
2
+ * Run a shell command in a child process, capture stdout/stderr, enforce
3
+ * a timeout and an output size cap. Used by the claude-byok provider's
4
+ * Bash tool — chroxy is the agent, so the BYOK provider runs tools
5
+ * locally rather than letting the claude binary do it.
6
+ *
7
+ * Design notes:
8
+ * - Uses `spawn('bash', ['-c', command])` rather than `exec()` so we get
9
+ * streaming output + AbortSignal support, and the user's full shell
10
+ * syntax (pipes, redirection, heredocs) just works.
11
+ * - Output is captured incrementally and capped at `maxOutputBytes` to
12
+ * keep a runaway producer from OOMing chroxy. When the cap is hit, the
13
+ * stream is truncated with a clear marker; the child is sent SIGTERM
14
+ * followed by SIGKILL after a 2s grace.
15
+ * - Timeout sends SIGTERM first, SIGKILL after 2s if the child ignores
16
+ * the term. Returns `timedOut: true` so the caller can surface that
17
+ * distinctly from an exit-code failure.
18
+ * - Aborting via the optional signal does the same as a timeout — clean
19
+ * SIGTERM, SIGKILL after grace. The returned `aborted: true` flag
20
+ * distinguishes it from a timeout for caller telemetry.
21
+ *
22
+ * Returns:
23
+ * {
24
+ * stdout: string,
25
+ * stderr: string,
26
+ * exitCode: number | null, // null when killed before exit
27
+ * signal: string | null, // signal that killed the process
28
+ * timedOut: boolean,
29
+ * aborted: boolean,
30
+ * truncated: boolean, // true if output cap was hit
31
+ * durationMs: number,
32
+ * }
33
+ */
34
+
35
+ import { spawn } from 'node:child_process'
36
+
37
+ export const DEFAULT_BASH_TIMEOUT_MS = 30_000
38
+ export const DEFAULT_BASH_MAX_OUTPUT_BYTES = 1_000_000 // 1 MB
39
+ export const HARD_KILL_GRACE_MS = 2_000
40
+
41
+ export async function executeBash({
42
+ command,
43
+ cwd = process.cwd(),
44
+ timeoutMs = DEFAULT_BASH_TIMEOUT_MS,
45
+ maxOutputBytes = DEFAULT_BASH_MAX_OUTPUT_BYTES,
46
+ env,
47
+ signal,
48
+ } = {}) {
49
+ if (typeof command !== 'string' || command.length === 0) {
50
+ throw new TypeError('executeBash: command must be a non-empty string')
51
+ }
52
+ if (typeof timeoutMs !== 'number' || timeoutMs <= 0) {
53
+ throw new TypeError('executeBash: timeoutMs must be a positive number')
54
+ }
55
+
56
+ const startedAt = Date.now()
57
+ let stdout = ''
58
+ let stderr = ''
59
+ // Single counter shared across both streams. Pre-fix, stdout and
60
+ // stderr each had their own counter so total captured output could
61
+ // be up to ~2×maxOutputBytes — Copilot review on #4060. Now the cap
62
+ // is a true total cap, counting actual UTF-8 BYTES of the chunk
63
+ // buffer (chunk.length), not JS string code units (text.length)
64
+ // which is UTF-16 and undercounts non-ASCII output.
65
+ let totalBytes = 0
66
+ let truncated = false
67
+ let timedOut = false
68
+ let aborted = false
69
+
70
+ const child = spawn('bash', ['-c', command], {
71
+ cwd,
72
+ env: env || process.env,
73
+ stdio: ['ignore', 'pipe', 'pipe'],
74
+ })
75
+
76
+ const capture = (chunk, which) => {
77
+ if (totalBytes >= maxOutputBytes) return
78
+ const chunkBytes = chunk.length
79
+ const remaining = maxOutputBytes - totalBytes
80
+ if (chunkBytes > remaining) {
81
+ // Slice the BUFFER (byte-accurate), then decode. Slicing the
82
+ // decoded string would be UTF-16 indexed and could split a
83
+ // surrogate pair, producing replacement chars.
84
+ const sliced = chunk.subarray(0, remaining).toString('utf8')
85
+ if (which === 'stdout') stdout += sliced
86
+ else stderr += sliced
87
+ totalBytes += remaining
88
+ truncated = true
89
+ killChild('SIGTERM', 'output_cap')
90
+ } else {
91
+ const text = chunk.toString('utf8')
92
+ if (which === 'stdout') stdout += text
93
+ else stderr += text
94
+ totalBytes += chunkBytes
95
+ }
96
+ }
97
+
98
+ const appendOut = (chunk) => capture(chunk, 'stdout')
99
+ const appendErr = (chunk) => capture(chunk, 'stderr')
100
+
101
+ child.stdout.on('data', appendOut)
102
+ child.stderr.on('data', appendErr)
103
+
104
+ let hardKillTimer = null
105
+ const killChild = (sig, _reason) => {
106
+ if (child.killed || child.exitCode !== null) return
107
+ try {
108
+ child.kill(sig)
109
+ } catch {
110
+ // ignore — process already gone
111
+ }
112
+ if (sig === 'SIGTERM' && hardKillTimer === null) {
113
+ hardKillTimer = setTimeout(() => {
114
+ try {
115
+ // #4067: `child.killed` is set when WE called child.kill(SIGTERM)
116
+ // above — it does NOT indicate process liveness. To actually
117
+ // skip the redundant SIGKILL when the child cleanly exited
118
+ // under SIGTERM within the grace window, test for an actual
119
+ // exit signal: exitCode set (normal exit) or signalCode set
120
+ // (received a signal). Either means the process is gone.
121
+ if (child.exitCode === null && child.signalCode === null) {
122
+ child.kill('SIGKILL')
123
+ }
124
+ } catch {}
125
+ }, HARD_KILL_GRACE_MS)
126
+ }
127
+ }
128
+
129
+ const timeoutHandle = setTimeout(() => {
130
+ timedOut = true
131
+ killChild('SIGTERM', 'timeout')
132
+ }, timeoutMs)
133
+
134
+ let abortListener = null
135
+ if (signal) {
136
+ if (signal.aborted) {
137
+ aborted = true
138
+ killChild('SIGTERM', 'aborted_at_start')
139
+ } else {
140
+ abortListener = () => {
141
+ aborted = true
142
+ killChild('SIGTERM', 'aborted')
143
+ }
144
+ signal.addEventListener('abort', abortListener, { once: true })
145
+ }
146
+ }
147
+
148
+ const { code, sig } = await new Promise((resolve) => {
149
+ child.on('exit', (code, signalName) => resolve({ code, sig: signalName }))
150
+ child.on('error', () => resolve({ code: null, sig: null }))
151
+ })
152
+
153
+ clearTimeout(timeoutHandle)
154
+ if (hardKillTimer !== null) clearTimeout(hardKillTimer)
155
+ if (signal && abortListener) signal.removeEventListener('abort', abortListener)
156
+
157
+ return {
158
+ stdout,
159
+ stderr,
160
+ exitCode: code,
161
+ signal: sig,
162
+ timedOut,
163
+ aborted,
164
+ truncated,
165
+ durationMs: Date.now() - startedAt,
166
+ }
167
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Local file operations used by the claude-byok provider's Read, Write,
3
+ * and Edit tools. Mirrors Claude Code's documented semantics:
4
+ *
5
+ * Read — line-numbered output with optional offset/limit + byte cap
6
+ * Write — full-file write, truncate, mode 0644 by default
7
+ * Edit — string-replace with strict-uniqueness check unless `replaceAll`
8
+ *
9
+ * Path-safety is the caller's responsibility — by the time we reach here
10
+ * the BYOK tool executor has already run validatePathWithinCwd() from
11
+ * ws-file-ops/common.js to defeat symlink escape attempts. These helpers
12
+ * receive realpaths that are known to be inside the session cwd.
13
+ *
14
+ * Each function returns `{ ok: true, ... }` on success or
15
+ * `{ ok: false, code, message }` on a recoverable error (file not found,
16
+ * uniqueness violation, etc.). Unexpected errors throw — the executor
17
+ * catches and surfaces them as tool errors to the model.
18
+ */
19
+
20
+ import { readFile, writeFile, stat, mkdir } from 'node:fs/promises'
21
+ import { dirname } from 'node:path'
22
+ import { applyEdit, formatNumberedLines } from './tool-transforms.js'
23
+
24
+ export const DEFAULT_READ_MAX_BYTES = 256_000
25
+ // Single-sourced in tool-transforms.js (shared with the container Read); kept
26
+ // as a re-export for back-compat.
27
+ export { DEFAULT_READ_LINE_LIMIT } from './tool-transforms.js'
28
+
29
+ /**
30
+ * Read a file, optionally with a line range. Lines are 1-indexed in
31
+ * Claude Code's Read semantics, so `offset=1, limit=100` means "lines
32
+ * 1..100". The output is line-numbered (`<5-digit>→<content>`) matching
33
+ * what Claude Code's Read tool produces, so the model sees a consistent
34
+ * shape across providers.
35
+ *
36
+ * On a binary file (NUL byte detected in the first 8KB) we refuse and
37
+ * return ok:false with a clear code — the model should use a different
38
+ * tool for binary inspection.
39
+ */
40
+ export async function readFileTool({
41
+ filePath,
42
+ offset,
43
+ limit,
44
+ maxBytes = DEFAULT_READ_MAX_BYTES,
45
+ } = {}) {
46
+ if (typeof filePath !== 'string' || filePath.length === 0) {
47
+ return { ok: false, code: 'EINVAL', message: 'filePath is required' }
48
+ }
49
+
50
+ let st
51
+ try {
52
+ st = await stat(filePath)
53
+ } catch (err) {
54
+ if (err.code === 'ENOENT') {
55
+ return { ok: false, code: 'ENOENT', message: `file not found: ${filePath}` }
56
+ }
57
+ throw err
58
+ }
59
+ if (!st.isFile()) {
60
+ return { ok: false, code: 'ENOTFILE', message: `not a regular file: ${filePath}` }
61
+ }
62
+ // Always enforce the byte cap, even when a `limit` is provided.
63
+ // Pre-fix, the cap was skipped when limit was set, so a multi-GB file
64
+ // could still get fully read into memory if the caller passed a limit
65
+ // (Copilot review on #4060). The slice-by-line approach below still
66
+ // reads the whole file via readFile(), so the cap is the only thing
67
+ // keeping us from OOMing on a giant input. If the file is too big,
68
+ // refuse — model can re-request with offset to walk it in chunks.
69
+ if (st.size > maxBytes) {
70
+ return {
71
+ ok: false,
72
+ code: 'TOO_LARGE',
73
+ message: `file is ${st.size} bytes (cap ${maxBytes}); read a slice with an explicit offset against a smaller file or split it first`,
74
+ }
75
+ }
76
+
77
+ const raw = await readFile(filePath)
78
+ // Binary sniff on the first 8KB. NUL bytes are the cheapest reliable
79
+ // signal; UTF-8 valid text rarely contains them.
80
+ const sniff = raw.subarray(0, 8192)
81
+ if (sniff.includes(0)) {
82
+ return { ok: false, code: 'BINARY', message: `binary content in ${filePath}; Read is text-only` }
83
+ }
84
+
85
+ // Slice + line-number via the shared transform (same shape the container
86
+ // produces via its in-container awk). Match Claude Code's tabular format:
87
+ // 5-space-padded 1-indexed line number, then arrow, then the line.
88
+ const text = raw.toString('utf8')
89
+ const { content, totalLines, linesReturned, truncatedByLimit } = formatNumberedLines(text, { offset, limit })
90
+ return { ok: true, content, totalLines, linesReturned, truncatedByLimit }
91
+ }
92
+
93
+ /**
94
+ * Write a file, truncating any existing content. Creates the file and
95
+ * any missing parent directories. Returns `created: true` when the
96
+ * path did not exist before.
97
+ *
98
+ * The mkdir-recursive call is necessary because Node's writeFile does
99
+ * NOT create parent dirs on its own — pre-fix, the doc comment claimed
100
+ * the behavior but the code would ENOENT on a missing parent (Copilot
101
+ * review on #4060).
102
+ */
103
+ export async function writeFileTool({ filePath, content, mode = 0o644 } = {}) {
104
+ if (typeof filePath !== 'string' || filePath.length === 0) {
105
+ return { ok: false, code: 'EINVAL', message: 'filePath is required' }
106
+ }
107
+ if (typeof content !== 'string') {
108
+ return { ok: false, code: 'EINVAL', message: 'content must be a string' }
109
+ }
110
+
111
+ let existedBefore = true
112
+ try {
113
+ await stat(filePath)
114
+ } catch (err) {
115
+ if (err.code === 'ENOENT') existedBefore = false
116
+ else throw err
117
+ }
118
+
119
+ // Ensure parent directory exists. recursive:true is a no-op when the
120
+ // directory already exists, so this is safe to call unconditionally.
121
+ // Path safety was already enforced by the caller (validatePathWithinCwd
122
+ // in byok-tool-executor.js), so the dirname is guaranteed to be
123
+ // inside the workspace cwd.
124
+ if (!existedBefore) {
125
+ await mkdir(dirname(filePath), { recursive: true })
126
+ }
127
+
128
+ await writeFile(filePath, content, { mode })
129
+ return {
130
+ ok: true,
131
+ bytesWritten: Buffer.byteLength(content, 'utf8'),
132
+ created: !existedBefore,
133
+ }
134
+ }
135
+
136
+ /**
137
+ * String-replace edit matching Claude Code's semantics:
138
+ * - Without `replaceAll`: refuses if `oldString` appears more than
139
+ * once. This avoids the very common LLM mistake of asking for an
140
+ * "edit" that accidentally touches more than one site.
141
+ * - Without `replaceAll`: refuses if `oldString` is not found at all.
142
+ * - With `replaceAll: true`: replaces every occurrence; the count is
143
+ * reported back so the model can sanity-check.
144
+ *
145
+ * Errors are returned as ok:false so the model gets a clear feedback
146
+ * loop instead of an exception bubbling up as "internal error".
147
+ */
148
+ export async function editFileTool({
149
+ filePath,
150
+ oldString,
151
+ newString,
152
+ replaceAll = false,
153
+ } = {}) {
154
+ if (typeof filePath !== 'string' || filePath.length === 0) {
155
+ return { ok: false, code: 'EINVAL', message: 'filePath is required' }
156
+ }
157
+ if (typeof oldString !== 'string' || oldString.length === 0) {
158
+ return { ok: false, code: 'EINVAL', message: 'oldString is required and must be non-empty' }
159
+ }
160
+ if (typeof newString !== 'string') {
161
+ return { ok: false, code: 'EINVAL', message: 'newString must be a string' }
162
+ }
163
+ if (oldString === newString) {
164
+ return { ok: false, code: 'NO_CHANGE', message: 'oldString and newString are identical' }
165
+ }
166
+
167
+ let content
168
+ try {
169
+ content = await readFile(filePath, 'utf8')
170
+ } catch (err) {
171
+ if (err.code === 'ENOENT') {
172
+ return { ok: false, code: 'ENOENT', message: `file not found: ${filePath}` }
173
+ }
174
+ throw err
175
+ }
176
+
177
+ // Count + strict-uniqueness + LITERAL replacement via the shared transform
178
+ // (also drives the docker-byok container Edit, so the semantics can't drift).
179
+ // Type + NO_CHANGE were already handled above; map the remaining codes to the
180
+ // path-ful messages this tool has always returned.
181
+ const result = applyEdit(content, { oldString, newString, replaceAll })
182
+ if (!result.ok) {
183
+ if (result.code === 'NOT_FOUND') {
184
+ return { ok: false, code: 'NOT_FOUND', message: `oldString not found in ${filePath}` }
185
+ }
186
+ if (result.code === 'NOT_UNIQUE') {
187
+ return {
188
+ ok: false,
189
+ code: 'NOT_UNIQUE',
190
+ message: `oldString matched ${result.matchCount} sites in ${filePath}; pass replaceAll=true or add surrounding context to make it unique`,
191
+ }
192
+ }
193
+ return { ok: false, code: result.code, message: result.message }
194
+ }
195
+
196
+ await writeFile(filePath, result.next)
197
+ return { ok: true, replacements: result.replacements, bytesWritten: Buffer.byteLength(result.next, 'utf8') }
198
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * FS-agnostic / shell-agnostic PURE transforms for the built-in tools, shared
3
+ * by the host implementations (file-ops.js, byok-tool-executor.js) and the
4
+ * container re-encodings (docker-byok-session.js) so the tool SEMANTICS have a
5
+ * single source of truth and can't drift (audit P2-9 / #5882).
6
+ *
7
+ * Byte I/O stays provider-specific: the host reads/writes via node:fs; the
8
+ * container shells out via `docker exec`. Only the pure string/command shaping
9
+ * lives here.
10
+ */
11
+
12
+ /**
13
+ * Quote a string for inclusion in a `bash -c` command via single-quote shell
14
+ * escaping (no expansion at all inside); embedded single quotes become `'\''`.
15
+ * Identical output to the per-file copies for string inputs.
16
+ */
17
+ function shellQuote(s) {
18
+ if (typeof s !== 'string') return "''"
19
+ return `'${s.replace(/'/g, `'\\''`)}'`
20
+ }
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Edit — strict-unique-match string replacement
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /**
27
+ * Apply Claude Code's Edit semantics to an in-memory string. PURE — the caller
28
+ * does the byte I/O (host fs read/write, or `cat`/`tee` via docker exec).
29
+ *
30
+ * Contract:
31
+ * - non-string / empty oldString → { ok:false, code:'EINVAL' }
32
+ * - non-string newString → { ok:false, code:'EINVAL' }
33
+ * - oldString === newString → { ok:false, code:'NO_CHANGE' }
34
+ * - oldString not present → { ok:false, code:'NOT_FOUND' }
35
+ * - >1 match without replaceAll → { ok:false, code:'NOT_UNIQUE', matchCount }
36
+ * - otherwise → { ok:true, next, replacements }
37
+ *
38
+ * Replacement is LITERAL in both the single and replaceAll paths (split/join
39
+ * and slice), so a newString containing `$&`/`$1`/`$\`` is inserted verbatim —
40
+ * unlike `String.prototype.replace`, whose `$`-pattern interpretation was a
41
+ * latent footgun in the old host single-edit path. Each `code` carries a default
42
+ * `message`, but callers may map the code to their own (path-ful) wording.
43
+ *
44
+ * @param {string} content
45
+ * @param {{ oldString?: string, newString?: string, replaceAll?: boolean }} opts
46
+ */
47
+ export function applyEdit(content, { oldString, newString, replaceAll = false } = {}) {
48
+ if (typeof oldString !== 'string' || oldString.length === 0) {
49
+ return { ok: false, code: 'EINVAL', message: 'oldString is required and must be non-empty' }
50
+ }
51
+ if (typeof newString !== 'string') {
52
+ return { ok: false, code: 'EINVAL', message: 'newString must be a string' }
53
+ }
54
+ if (oldString === newString) {
55
+ return { ok: false, code: 'NO_CHANGE', message: 'oldString and newString are identical' }
56
+ }
57
+
58
+ // Count occurrences without allocating a full split for huge files — an
59
+ // indexOf walk is O(n) and predictable. Advance by oldString.length so the
60
+ // count is NON-overlapping, matching what `split(oldString).join(...)`
61
+ // actually replaces (so `replacements` and the NOT_UNIQUE guard agree with
62
+ // the replaceAll path — e.g. 'aa' in 'aaaa' is 2, not the overlapping 3).
63
+ let matchCount = 0
64
+ let from = 0
65
+ let at
66
+ while ((at = content.indexOf(oldString, from)) !== -1) {
67
+ matchCount++
68
+ from = at + oldString.length
69
+ }
70
+
71
+ if (matchCount === 0) {
72
+ return { ok: false, code: 'NOT_FOUND', message: 'oldString not found' }
73
+ }
74
+ if (matchCount > 1 && !replaceAll) {
75
+ return {
76
+ ok: false,
77
+ code: 'NOT_UNIQUE',
78
+ matchCount,
79
+ message: `oldString matched ${matchCount} sites; pass replaceAll=true or add surrounding context to make it unique`,
80
+ }
81
+ }
82
+
83
+ let next
84
+ if (replaceAll) {
85
+ next = content.split(oldString).join(newString)
86
+ } else {
87
+ const at = content.indexOf(oldString)
88
+ next = content.slice(0, at) + newString + content.slice(at + oldString.length)
89
+ }
90
+ return { ok: true, next, replacements: matchCount }
91
+ }
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // Read — line-numbered output shape
95
+ // ---------------------------------------------------------------------------
96
+
97
+ /** Width the 1-indexed line number is right-padded to (then `→` then the line). */
98
+ export const READ_LINE_NUMBER_PAD = 5
99
+
100
+ /** Default line cap applied when no positive `limit` is given. */
101
+ export const DEFAULT_READ_LINE_LIMIT = 2_000
102
+
103
+ /**
104
+ * Slice `text` by a 1-indexed line range and render Claude Code's line-numbered
105
+ * Read shape (`<pad>→<line>`). PURE. (The container produces the same shape via
106
+ * an in-container `awk 'printf "%5d→%s"'` after a `sed | head` slice, mirroring
107
+ * READ_LINE_NUMBER_PAD — it can't reuse this JS because the slice happens
108
+ * in-container to avoid transferring the whole file.)
109
+ *
110
+ * @param {string} text
111
+ * @param {{ offset?: number, limit?: number, maxLines?: number }} opts
112
+ * @returns {{ content: string, totalLines: number, linesReturned: number, truncatedByLimit: boolean }}
113
+ */
114
+ export function formatNumberedLines(text, { offset, limit, maxLines = DEFAULT_READ_LINE_LIMIT } = {}) {
115
+ const allLines = text.split('\n')
116
+ const totalLines = allLines.length
117
+ const start = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) - 1 : 0
118
+ const requestedCount = Number.isFinite(limit) && limit > 0
119
+ ? Math.min(Math.floor(limit), maxLines)
120
+ : maxLines
121
+ const slice = allLines.slice(start, start + requestedCount)
122
+ const content = slice
123
+ .map((line, i) => `${String(start + i + 1).padStart(READ_LINE_NUMBER_PAD)}→${line}`)
124
+ .join('\n')
125
+ return {
126
+ content,
127
+ totalLines,
128
+ linesReturned: slice.length,
129
+ truncatedByLimit: slice.length < totalLines - start,
130
+ }
131
+ }
132
+
133
+ // ---------------------------------------------------------------------------
134
+ // Glob / Grep — shell command builders
135
+ // ---------------------------------------------------------------------------
136
+
137
+ /**
138
+ * Shell metacharacters a Glob pattern must never contain — the `for f in
139
+ * <pattern>` expansion would otherwise run an attacker payload (#4070). Glob
140
+ * patterns legitimately need only `* ? [] {} / .` alnum `_ -`.
141
+ */
142
+ export const GLOB_PATTERN_SHELL_METACHARS = /[$`;|&><()\\\n\r]/
143
+
144
+ /**
145
+ * Build the bash command that lists files matching `pattern` under `root`.
146
+ * `pattern` MUST already be validated against GLOB_PATTERN_SHELL_METACHARS by
147
+ * the caller (it is interpolated unquoted so the shell expands it).
148
+ */
149
+ export function buildGlobCommand(pattern, root) {
150
+ return `shopt -s globstar nullglob; cd ${shellQuote(root)} && for f in ${pattern}; do printf '%s\\n' "$f"; done`
151
+ }
152
+
153
+ /**
154
+ * Derive the rg/grep flag fragments from a Grep tool input: case-insensitive
155
+ * (`-i`), line numbers (`-n`, default on), and an optional `--glob` filter.
156
+ */
157
+ export function buildGrepArgs(input) {
158
+ const ci = input?.['-i'] === true ? '-i' : ''
159
+ const ln = input?.['-n'] !== false ? '-n' : ''
160
+ const globArg = typeof input?.glob === 'string' && input.glob.length > 0
161
+ ? ` --glob ${shellQuote(input.glob)}` : ''
162
+ return { ci, ln, globArg }
163
+ }
164
+
165
+ /**
166
+ * Build the bash command that greps `pattern` under `root`, preferring ripgrep
167
+ * and falling back to `grep -r` only when rg is truly absent (an `if/then/else`,
168
+ * NOT `rg || grep`, so a no-match rg exit-1 doesn't re-run the search). Both
169
+ * exit 1 on "no matches"; pass `maskExit:true` when the runner rejects on
170
+ * non-zero (the container's `execInEnvironment`) so that case isn't a failure.
171
+ *
172
+ * @param {{ pattern: string, root: string, ci: string, ln: string, globArg: string, maskExit?: boolean }} opts
173
+ */
174
+ export function buildGrepCommand({ pattern, root, ci, ln, globArg, maskExit = false }) {
175
+ const rgCmd = `rg ${ci} ${ln} --no-heading${globArg} ${shellQuote(pattern)} ${shellQuote(root)}`
176
+ const grepCmd = `grep -r ${ci} ${ln} ${shellQuote(pattern)} ${shellQuote(root)}`
177
+ const core = `if command -v rg >/dev/null 2>&1; then ${rgCmd}; else ${grepCmd}; fi`
178
+ return maskExit ? `${core}; true` : core
179
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Built-in slash command registry per provider (#3856).
3
+ *
4
+ * Source-of-truth for the slash-command picker so users see the commands the
5
+ * underlying CLI/SDK accepts — `/clear`, `/compact`, `/model`, etc. — alongside
6
+ * the user-authored `.md` skill files we already scan. Without this list the
7
+ * picker only surfaces the markdown skills (browser.js:375), so newcomers never
8
+ * discover the most useful commands and Codex users see Claude-flavoured names
9
+ * that don't match their CLI.
10
+ *
11
+ * The commands themselves are interpreted **downstream** by the provider's
12
+ * CLI/SDK — Chroxy doesn't intercept `/clear` or `/compact`. We're purely
13
+ * making them discoverable in the picker.
14
+ *
15
+ * Hand-maintained. Cost of staleness is low: a missing entry just means the
16
+ * command isn't visible in the picker, but typing it still works.
17
+ *
18
+ * When updating, cross-reference:
19
+ * - Claude Code: https://docs.claude.com/en/docs/claude-code/slash-commands
20
+ * - Codex CLI: https://github.com/openai/codex (run `codex` and type `/`)
21
+ * - Gemini CLI: https://github.com/google-gemini/gemini-cli
22
+ */
23
+
24
+ /**
25
+ * @typedef {Object} BuiltinCommand
26
+ * @property {string} name - Command name (no leading slash)
27
+ * @property {string} description - Short human-readable description
28
+ * @property {boolean} [requiresModelSwitch] - When true, only surfaced for
29
+ * providers whose `capabilities.modelSwitch === true`. Used for `/model`.
30
+ */
31
+
32
+ /** Commands available across every Claude-flavoured provider. */
33
+ const CLAUDE_COMMON = [
34
+ { name: 'clear', description: 'Clear conversation history' },
35
+ { name: 'compact', description: 'Compact conversation to a summary' },
36
+ { name: 'cost', description: 'Show session cost / token usage' },
37
+ { name: 'help', description: 'List all commands' },
38
+ { name: 'model', description: 'Switch model mid-session', requiresModelSwitch: true },
39
+ { name: 'memory', description: 'View or edit memory files' },
40
+ { name: 'permissions', description: 'Manage tool permissions' },
41
+ { name: 'agents', description: 'List custom agents' },
42
+ { name: 'init', description: 'Initialize a CLAUDE.md for this repo' },
43
+ { name: 'review', description: 'Review a pull request' },
44
+ ]
45
+
46
+ /**
47
+ * Per-provider registry. Keys match provider names registered in providers.js.
48
+ * Unknown providers fall back to an empty list — the picker still shows
49
+ * user/project commands; built-ins just don't surface (safe default).
50
+ *
51
+ * Docker variants reuse the Claude registry: `docker-cli` extends `CliSession`
52
+ * and `docker-sdk` extends `SdkSession` (see docker-session.js / docker-sdk-
53
+ * session.js), so the in-container CLI/SDK accepts the same `/clear`,
54
+ * `/compact`, etc. The hidden `docker` alias (registered for backward compat
55
+ * in providers.js) is intentionally omitted — new sessions never resolve to it.
56
+ */
57
+ export const BUILTIN_COMMANDS = {
58
+ 'claude-sdk': CLAUDE_COMMON,
59
+ 'claude-cli': CLAUDE_COMMON,
60
+ 'claude-tui': CLAUDE_COMMON,
61
+ 'claude-byok': CLAUDE_COMMON,
62
+ 'docker-cli': CLAUDE_COMMON,
63
+ 'docker-sdk': CLAUDE_COMMON,
64
+ 'codex': [
65
+ { name: 'clear', description: 'Clear conversation history' },
66
+ { name: 'help', description: 'List all commands' },
67
+ { name: 'init', description: 'Generate AGENTS.md for this repo' },
68
+ { name: 'model', description: 'Switch model mid-session', requiresModelSwitch: true },
69
+ { name: 'new', description: 'Start a new chat session' },
70
+ { name: 'review', description: 'Review the pending diff' },
71
+ { name: 'status', description: 'Show current session settings' },
72
+ ],
73
+ 'gemini': [
74
+ { name: 'clear', description: 'Clear conversation history' },
75
+ { name: 'compress', description: 'Compress conversation context' },
76
+ { name: 'help', description: 'List all commands' },
77
+ { name: 'memory', description: 'View or edit memory files' },
78
+ { name: 'model', description: 'Switch model mid-session', requiresModelSwitch: true },
79
+ { name: 'stats', description: 'Show session token usage' },
80
+ { name: 'tools', description: 'List available tools' },
81
+ ],
82
+ }
83
+
84
+ /**
85
+ * Resolve the built-in commands for a given provider, filtered by capabilities.
86
+ *
87
+ * `/model` is gated on `capabilities.modelSwitch` so Claude TUI sessions
88
+ * (which can't hot-swap models — see claude-tui-session.js:225) don't show it.
89
+ * Unknown providers return `[]` rather than throwing so callers don't need to
90
+ * handle the "no built-ins registered" case as an error.
91
+ *
92
+ * @param {string|null|undefined} providerName
93
+ * @param {{ modelSwitch?: boolean } | null | undefined} capabilities
94
+ * @returns {Array<{ name: string, description: string, source: 'builtin' }>}
95
+ */
96
+ export function getBuiltinCommands(providerName, capabilities = null) {
97
+ if (!providerName || typeof providerName !== 'string') return []
98
+ const list = BUILTIN_COMMANDS[providerName]
99
+ if (!Array.isArray(list)) return []
100
+ const supportsModelSwitch = !!(capabilities && capabilities.modelSwitch)
101
+ const out = []
102
+ for (const cmd of list) {
103
+ if (cmd.requiresModelSwitch && !supportsModelSwitch) continue
104
+ out.push({ name: cmd.name, description: cmd.description, source: 'builtin' })
105
+ }
106
+ return out
107
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Process-wide singleton for the docker-byok compose-state store (#5081).
3
+ *
4
+ * Kept in its own module so live `DockerByokSession`s (which record/forget
5
+ * their project id) and the boot-time `sweepOrphanedComposeStacks()` agree on
6
+ * exactly one on-disk state file. Mirrors `getSharedPool()` in
7
+ * docker-byok-pool.js.
8
+ */
9
+
10
+ import { ByokComposeStateStore } from './byok-compose-state.js'
11
+
12
+ let _shared = null
13
+
14
+ /**
15
+ * Lazily construct (once) and return the process-wide compose-state store.
16
+ * @returns {ByokComposeStateStore}
17
+ */
18
+ export function getSharedComposeStateStore() {
19
+ if (!_shared) {
20
+ _shared = new ByokComposeStateStore({})
21
+ }
22
+ return _shared
23
+ }
24
+
25
+ /**
26
+ * Test helper — reset the singleton so a test using the real default path
27
+ * doesn't bleed into the next. Not used in production.
28
+ */
29
+ export function _resetSharedComposeStateStore() {
30
+ _shared = null
31
+ }