@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -90,6 +90,26 @@ export function applyEdit(content, { oldString, newString, replaceAll = false }
90
90
  return { ok: true, next, replacements: matchCount }
91
91
  }
92
92
 
93
+ // ---------------------------------------------------------------------------
94
+ // Write — confirmation text shape
95
+ // ---------------------------------------------------------------------------
96
+
97
+ /**
98
+ * Build the short, model-facing confirmation text for a successful Write —
99
+ * never the file body. This is the SINGLE SOURCE for that wording:
100
+ * `byok-tool-executor.js`'s `runWrite` uses it to build its `tool_result`
101
+ * content, and `claude-tui-tool-response.js` reuses it (#8082 review,
102
+ * Critical #1) so a claude-tui Write card renders the exact same short
103
+ * confirmation instead of the tool's raw structured result — whose own
104
+ * `content` field is the ENTIRE written file, not a summary.
105
+ *
106
+ * @param {{ bytesWritten: number, filePath: string, created?: boolean }} opts
107
+ * @returns {string}
108
+ */
109
+ export function formatWriteConfirmation({ bytesWritten, filePath, created = false }) {
110
+ return `Wrote ${bytesWritten} bytes to ${filePath}${created ? ' (created)' : ''}.`
111
+ }
112
+
93
113
  // ---------------------------------------------------------------------------
94
114
  // Read — line-numbered output shape
95
115
  // ---------------------------------------------------------------------------
@@ -142,24 +162,846 @@ export function formatNumberedLines(text, { offset, limit, maxLines = DEFAULT_RE
142
162
  export const GLOB_PATTERN_SHELL_METACHARS = /[$`;|&><()\\\n\r]/
143
163
 
144
164
  /**
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).
165
+ * SECURITY (#7341) — reject a Glob `pattern` that OBVIOUSLY escapes the
166
+ * workspace, so the model gets a clear `EINVAL` instead of a puzzling
167
+ * "No matches".
168
+ *
169
+ * THIS IS NOT THE SECURITY BOUNDARY, and the history of the file is the reason
170
+ * it says so this loudly. It began as one — a check that tried to predict what
171
+ * bash would do with the pattern — and three review rounds walked past it six
172
+ * times (whitespace word-splitting, brace expansion, a glob matching the `..`
173
+ * entry, quote removal, a brace body with no top-level comma, POSIX bracket
174
+ * sub-expressions). The replacement modelled bash properly: a real brace
175
+ * expander and a glob-to-regex segment matcher. That was worse. It was
176
+ * measurably wrong (46 of 515 enumerated bracket segments answered "cannot
177
+ * reach `..`" for segments bash expands straight to `..`) and it was a denial
178
+ * of service (a 4 KB pattern of `{a,b}` groups and stars backtracked for 12.9
179
+ * SECONDS of blocked event loop, on a tool auto-approved in `acceptEdits`).
180
+ *
181
+ * Both problems came from the same source: modelling a shell. So the model is
182
+ * gone. Containment is enforced entirely on the OUTPUT — `confineGlobMatches`
183
+ * realpaths every match on the host, `globMatchEscapesRoot` filters every match
184
+ * on the container — and all six historical bypasses were re-confirmed closed
185
+ * at that layer, by fuzzing real bash. What remains here is a linear scan whose
186
+ * only job is a good error message, and which cannot be wrong in a way that
187
+ * matters: a false negative just yields "No matches" from the layer below.
188
+ *
189
+ * @param {string} pattern
190
+ * @returns {string|null} A reason string when the pattern obviously escapes.
191
+ */
192
+ export function globPatternEscapeReason(pattern) {
193
+ if (typeof pattern !== 'string') return 'not a string'
194
+ // Whitespace: the CONTAINER interpolates the pattern unquoted into
195
+ // `for f in <pattern>`, so a space there is several patterns. Rejected on
196
+ // both paths so one input cannot mean two things depending on the backend.
197
+ if (/\s/.test(pattern)) {
198
+ return 'whitespace — use ** or a wildcard instead of a literal space'
199
+ }
200
+ // Word starts: the beginning, or after a `{` or `,` — brace expansion makes
201
+ // each alternative its own word. No expansion is performed; these anchors are
202
+ // a cheap approximation, which is all a message needs to be.
203
+ if (/(^|[{,])~/.test(pattern)) return 'home-directory (~) expansion'
204
+ if (/(^|[{,])[/\\]/.test(pattern)) return 'absolute path'
205
+ // Windows: `C:\x`, `C:/x` and the drive-relative `C:x` are all absolute
206
+ // enough to leave the workspace, and none of them starts with a separator.
207
+ // #6928 is the same lesson one layer down — a `/`-shaped path evading a
208
+ // guard that only knew about `\`, or the reverse.
209
+ if (/(^|[{,])[A-Za-z]:/.test(pattern)) return 'absolute path'
210
+ // A literal `..` path segment. Segments are delimited by either separator
211
+ // and by brace punctuation. This deliberately does NOT try to work out
212
+ // whether a glob such as `.*` could EXPAND to `..` — that computation is
213
+ // what produced both the false accepts and the DoS, and the output layer
214
+ // catches the real thing regardless.
215
+ for (const segment of pattern.split(/[/\\{},]/)) {
216
+ if (segment === '..') return 'parent-directory (..) traversal'
217
+ }
218
+ return null
219
+ }
220
+
221
+ /**
222
+ * SECURITY (#7341) — does a glob MATCH, as produced, point outside the root it
223
+ * was expanded in? Purely lexical, and deliberately so: it inspects what the
224
+ * expansion ACTUALLY produced instead of predicting what it will produce.
225
+ *
226
+ * That distinction is the whole lesson of this fix. Two review rounds found
227
+ * six ways past a guard that tried to model bash's expansion — quote removal,
228
+ * whitespace word-splitting, a brace body with no top-level comma, a glob that
229
+ * matches the `..` entry, POSIX bracket sub-expressions, and nested braces.
230
+ * Every one of them is invisible in the source text and every one of them is
231
+ * plainly visible in the OUTPUT, as a leading `/` or a `..` segment. Checking
232
+ * the output needs no model of the shell and therefore has no round seven.
233
+ *
234
+ * The host does strictly better than this (`confineGlobMatches` realpaths each
235
+ * match). What this cannot see is a symlinked directory inside `/workspace` —
236
+ * lexically clean, resolves out. That is no longer a residual: since #7354 the
237
+ * container resolves every match physically in-container
238
+ * ({@link buildConfinedGlobBody}), and this stays in FRONT of it as the layer
239
+ * that needs nothing from the guest's userland.
240
+ */
241
+ export function globMatchEscapesRoot(match) {
242
+ if (typeof match !== 'string') return true
243
+ // Both separators and the Windows drive/UNC forms. Splitting on `/` alone is
244
+ // #6928 exactly — a guard that knew one separator and let the other through.
245
+ // The container is Linux today, so the Windows arms are contract rather than
246
+ // live defence; a validator whose JSDoc claims "absolute" must mean it.
247
+ if (/^[/\\]/.test(match)) return true
248
+ if (/^[A-Za-z]:/.test(match)) return true
249
+ return match.split(/[/\\]/).includes('..')
250
+ }
251
+
252
+ /** The tool_result message for a pattern rejected by {@link globPatternEscapeReason}. */
253
+ export function globPatternEscapeMessage(reason) {
254
+ return `EINVAL: glob pattern escapes the workspace root (${reason}). Patterns are relative to the workspace; use the "path" argument to search a subdirectory.`
255
+ }
256
+
257
+ /**
258
+ * SECURITY (#7898 round 4) — hard ceilings on `pattern` BEFORE it reaches
259
+ * either backend's matcher: the host's hand-written case-check parser
260
+ * (`compileCaseCheck`/`parseSegmentTokens`/`advanceToken` in
261
+ * byok-tool-executor.js) and the container's bash brace expansion
262
+ * (`buildConfinedGlobBody`). Nothing upstream of this point bounds `pattern`
263
+ * at all — not the tool's JSON-schema `input_schema` (a bare `{ type:
264
+ * 'string' }`, no `maxLength`), not {@link GLOB_PATTERN_SHELL_METACHARS}, not
265
+ * {@link globPatternEscapeReason} (both are fixed-cost linear scans that
266
+ * don't look at length or nesting). This is the first and only place either
267
+ * is checked, which is why both backends call it.
268
+ *
269
+ * Two independent, cheap (each a single linear scan, no recursion) checks:
270
+ *
271
+ * - **Length.** Every cost this file's review history has found in the host
272
+ * matcher is polynomial in `pattern.length` (P) for a BOUNDED P — see the
273
+ * worst-case bound written above {@link compileCaseCheck} — so bounding P
274
+ * bounds all of them at once, including constructs no round has found yet.
275
+ * 2,000 characters is generous: the longest pattern in this file's own test
276
+ * suite, deliberately adversarial (`'{*a,*b}'.repeat(30)`), is 210; a real
277
+ * pattern is rarely more than a few dozen.
278
+ *
279
+ * - **Brace nesting depth.** #7898 round 4 — chain-nested braces
280
+ * (`{a,{b,{c,d}}}`, extended: `{x1,{x2,{x3,...}}}`) are the one construct
281
+ * round 3's "self-limiting" dismissal ("depth d needs ~2^d characters",
282
+ * true only for a BALANCED binary tree of alternatives) got wrong: a
283
+ * right-leaning CHAIN needs only ~4 characters per extra level, so nesting
284
+ * depth is near-linear in pattern length, not exponential. Two independent
285
+ * defects follow, both measured directly against `compileCaseCheck`/
286
+ * `caseCheckPasses` on this machine:
287
+ * 1. `parseSegmentTokens` re-scans the shrinking remainder at every
288
+ * nesting level (`findMatchingBrace` + `splitTopLevelCommas`, each
289
+ * O(remaining length)), so PARSE time alone is O(depth²): 0.16ms at
290
+ * depth 10 (48 chars), 18.72ms at depth 1000 (6,890 chars), 301.88ms
291
+ * at depth 4000 (30,890 chars) — quadratic scaling confirmed (~4x
292
+ * time per ~2x length). This runs UNCONDITIONALLY per Glob call, in
293
+ * `confineGlobMatches`, before a single match is even checked.
294
+ * 2. Both `parseSegmentTokens` (parse) and `advanceToken`/`advanceTokens`
295
+ * (match, the `alt` branch recursing into nested options) are
296
+ * RECURSIVE with one JS call frame per nesting level, and neither has
297
+ * a depth check — a pattern nested deep enough throws an uncaught
298
+ * `RangeError: Maximum call stack size exceeded`. Measured on Node
299
+ * 22.23.2: parsing survives to ~depth 5,505 (~38,000 chars) before
300
+ * overflowing; MATCHING overflows far sooner, at ~depth 2,000 (~14,500
301
+ * chars), because `advanceToken`/`advanceTokens` mutually recurse with
302
+ * a shallower frame budget than `parseSegmentTokens`'s single
303
+ * self-recursion. `executeBuiltinTool`'s outer try/catch turns this
304
+ * into a caught `Tool Glob failed: Maximum call stack size exceeded`
305
+ * rather than crashing the daemon — but the exact depth that overflows
306
+ * depends on how much OTHER stack is already in use by the async call
307
+ * chain when a real Glob call runs, which is neither deterministic nor
308
+ * portable, so it cannot be treated as an implicit safety bound.
309
+ * 32 levels is far above anything a legitimate pattern needs (the task's
310
+ * own `{a,{b,{c,d}}}` example is depth 3) and leaves a >60x margin below
311
+ * the measured match-time overflow point, so the ceiling is reached and
312
+ * refused long before either the quadratic parse cost or the recursion
313
+ * depth becomes a problem — regardless of how much stack the caller has
314
+ * already used.
315
+ *
316
+ * FAIL CLOSED: this runs BEFORE `fs.glob`'s own walk starts (host) and before
317
+ * the container `docker exec` is issued, so an over-budget pattern costs
318
+ * nothing beyond this scan — no walk, no case-check compile, no container
319
+ * round-trip.
320
+ *
321
+ * @param {string} pattern
322
+ * @returns {string|null} A reason string when the pattern is too complex.
323
+ */
324
+ export const GLOB_PATTERN_MAX_LENGTH = 2_000
325
+ export const GLOB_PATTERN_MAX_BRACE_DEPTH = 32
326
+
327
+ export function globPatternComplexityReason(pattern) {
328
+ if (typeof pattern !== 'string') return 'not a string'
329
+ if (pattern.length > GLOB_PATTERN_MAX_LENGTH) {
330
+ return `longer than ${GLOB_PATTERN_MAX_LENGTH} characters (${pattern.length})`
331
+ }
332
+ // A plain linear scan, no recursion — and a SAFE upper bound on the real
333
+ // parser's recursion depth even though it does not distinguish a bracket
334
+ // expression's literal '{'/'}' members from real brace syntax: every
335
+ // recursion `parseSegmentTokens` actually performs happens on a MATCHED
336
+ // '{'...'}' pair, which this counter always sees too (an unmatched '{' —
337
+ // what the parser treats as a literal and never recurses into —
338
+ // can only make this counter's depth reading HIGHER than the true parse
339
+ // depth, never lower). Over-rejecting a pattern that merely contains many
340
+ // literal, unmatched '{' characters is an acceptable false positive for a
341
+ // guard whose only job is to never under-count real recursion.
342
+ //
343
+ // #7951 review — that argument holds for a BRACKET-OBLIVIOUS pairer (bash
344
+ // in the container). The host parser now pairs braces bracket-AWARE, so a
345
+ // '}' inside '[...]' lowers this counter without closing anything the host
346
+ // parser sees, and this reading can UNDER-count the host's depth. The host
347
+ // therefore re-measures with its own pairing (`hostBraceDepthExceeded` in
348
+ // byok-tool-executor.js) against the same ceiling; this counter stays as
349
+ // the bound for the container.
350
+ let depth = 0
351
+ for (let i = 0; i < pattern.length; i++) {
352
+ const c = pattern[i]
353
+ if (c === '{') {
354
+ depth++
355
+ if (depth > GLOB_PATTERN_MAX_BRACE_DEPTH) {
356
+ return `"{" nesting deeper than ${GLOB_PATTERN_MAX_BRACE_DEPTH} levels`
357
+ }
358
+ } else if (c === '}' && depth > 0) {
359
+ depth--
360
+ }
361
+ }
362
+ return null
363
+ }
364
+
365
+ /** The tool_result message for a pattern rejected by {@link globPatternComplexityReason}. */
366
+ export function globPatternComplexityMessage(reason) {
367
+ return `EINVAL: glob pattern is too complex (${reason}). Narrow the search with "path", or split it into more than one simpler Glob call.`
368
+ }
369
+
370
+ // ---------------------------------------------------------------------------
371
+ // Container path confinement (#7354) — resolve INSIDE the container
372
+ // ---------------------------------------------------------------------------
373
+
374
+ /**
375
+ * SECURITY (#7354) — the sentinel the container-side confinement preamble
376
+ * prints as the FIRST line of stdout when the target resolved inside the
377
+ * workspace and the body is about to run.
378
+ *
379
+ * It exists so the host can tell "the guard ran and passed" apart from "the
380
+ * guard did not run at all". Without it, a command that lost the preamble
381
+ * would be indistinguishable from one that passed it — success and
382
+ * not-checking would be the same observable, which is the defect class
383
+ * `docs/false-safety-guards.md` is a catalogue of.
384
+ */
385
+ export const CONTAINER_CONFINE_OK = '__chroxy_confine_ok__'
386
+
387
+ /** Printed when the target resolved OUTSIDE the workspace. */
388
+ export const CONTAINER_CONFINE_ESCAPE = '__chroxy_confine_escape__'
389
+
390
+ /** Printed when the target could not be resolved at all (fail closed). */
391
+ export const CONTAINER_CONFINE_ERROR = '__chroxy_confine_error__'
392
+
393
+ /**
394
+ * SECURITY (#7354) — the trailer the Glob body prints as its LAST line,
395
+ * carrying the number of matches the in-container resolution WITHHELD.
396
+ *
397
+ * Withheld matches stay invisible to the MODEL (see {@link buildConfinedGlobBody}
398
+ * — distinguishing "matched, but outside" from "matched nothing" is an existence
399
+ * oracle on a tool `acceptEdits` auto-approves). They must not be invisible to
400
+ * the OPERATOR. A containment that fires silently and reports success is the
401
+ * exact shape `docs/false-safety-guards.md` catalogues: the daemon log line the
402
+ * host writes from this count is the difference between "the guard held" and
403
+ * "nothing was there", which is otherwise unobservable from outside the
404
+ * container.
405
+ *
406
+ * The count is a count, never a path: the names and link targets of what was
407
+ * withheld would put the very thing containment refused into the daemon log.
408
+ *
409
+ * #7357 — this line is STILL `\n`-terminated (unlike the matches above it,
410
+ * which are NUL-delimited): it is host-authored fixed text, never a filename,
411
+ * so it cannot itself contain a stray delimiter, and keeping it human-legible
412
+ * on its own line is what let {@link splitWithheldTrailer} stay a boundary
413
+ * split rather than a scan.
414
+ */
415
+ export const CONTAINER_CONFINE_WITHHELD = '__chroxy_confine_withheld__'
416
+
417
+ /** Matches the trailer line emitted by {@link buildConfinedGlobBody}. */
418
+ const WITHHELD_TRAILER_RE = new RegExp(`^${CONTAINER_CONFINE_WITHHELD} (\\d+)$`)
419
+
420
+ /**
421
+ * Max symlink hops `__cx_resolve` follows before giving up (ELOOP guard).
422
+ * Linux's own limit is 40; matching it means we refuse exactly what the
423
+ * kernel refuses rather than inventing a stricter one.
424
+ */
425
+ const CONTAINER_RESOLVE_MAX_HOPS = 40
426
+
427
+ /**
428
+ * SECURITY (#7354) — the bash source of `__cx_resolve`, which resolves a path
429
+ * to its PHYSICAL location inside the container: every symlinked directory
430
+ * component via `cd -P`, and a symlinked leaf via a bounded `readlink` loop.
431
+ *
432
+ * Why this has to run in the container at all: `globMatchEscapesRoot` and
433
+ * `remapToContainerPath` are both LEXICAL. `esc/passwd`, where `/workspace/esc`
434
+ * is a symlink to `/etc` in the CONTAINER's filesystem, has no leading `/` and
435
+ * no `..` segment — it is lexically spotless and resolves out. The host cannot
436
+ * see that link (it is not on the host's filesystem), so the only place the
437
+ * question can be answered is inside the container. That is the whole of #7354.
438
+ *
439
+ * UTILITIES: `cd -P`, `pwd -P`, `case`, `${x%/*}` and `local` are bash
440
+ * builtins/syntax, and `execInEnvironment` already invokes `bash -c` (the
441
+ * existing Glob command uses `shopt`, so bash is a standing requirement, not a
442
+ * new one). The ONLY external program is `readlink`, and it is reached only
443
+ * when a component is actually a symlink — it ships in GNU coreutils (the
444
+ * default `node:22-slim` image) and in busybox (alpine). If it is missing the
445
+ * `$(readlink ...)` fails, the function returns non-zero, and the caller emits
446
+ * CONTAINER_CONFINE_ERROR: unresolvable is refused, never waved through.
447
+ *
448
+ * `unset CDPATH` before every `cd`: with CDPATH set, bash's `cd` ECHOES the
449
+ * directory it landed in on stdout, which would corrupt the `$( ... )` capture
450
+ * (project memory: cdpath_corrupts_cd_pwd_capture).
451
+ *
452
+ * Contract: prints the physical path and returns 0, or prints nothing and
453
+ * returns non-zero. A MISSING LEAF still resolves — its parent directory does,
454
+ * and the leaf is appended — so `Read` of a file that is not there keeps
455
+ * reporting the tool's own "No such file", not a containment error. A missing
456
+ * or unreadable PARENT is a failure, which is correct for these three tools:
457
+ * Read/Glob/Grep only ever name a path that must already exist.
458
+ *
459
+ * OPTIONAL SECOND ARG (#7897) — `$2`, non-empty to opt in, empty/absent (every
460
+ * pre-#7897 caller) to keep the contract above byte-for-byte. It widens
461
+ * exactly one case: a missing PARENT hit while resolving a FOLLOWED SYMLINK's
462
+ * TARGET (`$__n -gt 0` — at least one `readlink` hop already happened), never
463
+ * the original `$1`'s own first-hop parent, which stays a hard failure
464
+ * regardless of this flag. The host's component-wise resolver
465
+ * (`resolveTargetComponentwiseAsync`, utils/componentwise-resolver.js) hits
466
+ * ENOENT and switches to a purely lexical tail-append with no further
467
+ * filesystem access; `__cx_resolve` had no equivalent, so a dangling symlink
468
+ * whose target's own parent is ALSO missing (`sub/target.ts -> ./gone/x.ts`,
469
+ * `gone` not just `x.ts` absent) failed the `cd -P` on that missing parent and
470
+ * the whole match was withheld — a real undermatch against the host for a
471
+ * shape #7355/#7357's single-level fixture never exercised. `__cx_resolve_new`
472
+ * (below) already implements exactly this "peel trailing components until one
473
+ * exists, resolve that prefix physically, re-append the rest lexically"
474
+ * walk for CREATE-mode paths, so the fallback reuses it rather than growing a
475
+ * second copy (`__cx_resolve_new`'s own doc: "reused, not reimplemented — a
476
+ * second resolution loop is a second thing to drift") — at the point of
477
+ * failure `$__p` is always already absolute (built from a prior hop's
478
+ * `pwd -P`), which is exactly what `__cx_resolve_new` requires. Gated to
479
+ * `$__n -gt 0` rather than applied unconditionally so the original path's own
480
+ * missing-parent case — Read/Grep naming a path with no such directory at
481
+ * all — keeps failing exactly as before; only Glob's per-match symlink
482
+ * resolution ({@link buildConfinedGlobBody}) passes the flag.
483
+ */
484
+ const CONTAINER_RESOLVE_FN = [
485
+ '__cx_resolve() {',
486
+ ' local __p=$1 __cx_lenient=${2:-} __d __b __t __cd __n=0',
487
+ ` while [ "$__n" -lt ${CONTAINER_RESOLVE_MAX_HOPS} ]; do`,
488
+ ' if [ -d "$__p" ]; then ( unset CDPATH; cd -P -- "$__p" 2>/dev/null && pwd -P ) || return 1; return 0; fi',
489
+ ' case $__p in */*) __d=${__p%/*}; __b=${__p##*/} ;; *) __d=.; __b=$__p ;; esac',
490
+ ' [ -n "$__d" ] || __d=/',
491
+ ' if ! __cd=$( unset CDPATH; cd -P -- "$__d" 2>/dev/null && pwd -P ); then',
492
+ // #7897 — only past the first hop (already inside a followed symlink's
493
+ // target, never the original `$1`) and only when the caller opted in.
494
+ ' if [ "$__n" -gt 0 ] && [ -n "$__cx_lenient" ]; then __cx_resolve_new "$__p" && return 0; fi',
495
+ ' return 1',
496
+ ' fi',
497
+ ' __d=$__cd',
498
+ ' __p=$__d/$__b',
499
+ ' if [ -L "$__p" ]; then',
500
+ // The `--` first, then WITHOUT it (Copilot, PR #7867): the image is a user
501
+ // opt, there is no allowlist, and a BusyBox `readlink` that did not honour
502
+ // `--` would refuse every legitimate symlink in an Alpine container. Dropping
503
+ // `--` costs nothing here and cannot recreate #7295: by this line `$__p` is
504
+ // `$__d/$__b` where `__d` came from `pwd -P`, so it ALWAYS begins with `/`
505
+ // and can never be read as an option. The `--` stays first so the guarantee
506
+ // does not rest on that invariant where a utility honours the terminator.
507
+ ' __t=$(readlink -- "$__p" 2>/dev/null || readlink "$__p") || return 1',
508
+ ' case $__t in /*) __p=$__t ;; *) __p=$__d/$__t ;; esac',
509
+ ' __n=$((__n+1))',
510
+ ' continue',
511
+ ' fi',
512
+ ' printf \'%s\\n\' "$__p"',
513
+ ' return 0',
514
+ ' done',
515
+ ' return 1',
516
+ '}',
517
+ ].join('\n')
518
+
519
+ /**
520
+ * SECURITY (#7876) — the bash source of `__cx_resolve_new`, the CREATE-mode
521
+ * resolver for container Write/Edit: the DEEPEST-EXISTING-ANCESTOR walk.
522
+ *
523
+ * `__cx_resolve` is right for Read/Glob/Grep because they only ever name a path
524
+ * whose parent exists. Write names paths that may be several levels short of
525
+ * existing (`esc/new/deeper/file.txt`) and `mkdir -p`s the gap, so resolving
526
+ * the whole path fails outright — and resolving nothing leaves `mkdir -p` free
527
+ * to walk through `esc -> /etc`. This walk:
528
+ *
529
+ * 1. peels components off the END of the lexical path until what is left
530
+ * EXISTS. "Exists" is `[ -e ] || [ -L ]`, never `-e` alone: `-e` follows
531
+ * the link, so a DANGLING link reads as absent, the walk steps past it,
532
+ * and the later `mkdir -p` / `>` goes through it to wherever it points
533
+ * (`>` CREATES a dangling link's target). Stopping on the link hands it to
534
+ * `__cx_resolve`, which resolves it to its target — outside is an escape,
535
+ * unresolvable is a failure, never a pass;
536
+ * 2. refuses any peeled component that is `..`, `.` or empty (`//`, a
537
+ * trailing `/`). `remapToContainerPath` already collapses those lexically,
538
+ * and this refusal deliberately does not trust it: the peeled remainder is
539
+ * re-appended WITHOUT resolution, so a `..` in it would be resolved by the
540
+ * kernel only at `mkdir` time — after the containment check. The remainder
541
+ * cannot be absolute: it is built from components, none of which contain
542
+ * `/`;
543
+ * 3. resolves the existing prefix physically with `__cx_resolve` (reused, not
544
+ * reimplemented — a second resolution loop is a second thing to drift);
545
+ * 4. prints `<resolved-prefix>/<remainder>`. When the whole path exists the
546
+ * remainder is empty and this is exactly `__cx_resolve target`, i.e. the
547
+ * Read route.
548
+ *
549
+ * Every component the caller's body creates afterwards is created under the
550
+ * RESOLVED prefix, never under the lexical alias, so a link swapped on the
551
+ * alias after the check does not redirect the write. A link swapped INSIDE the
552
+ * already-resolved prefix between the check and the write is the same
553
+ * check-then-use window the host-side tools and #7354 accept.
554
+ *
555
+ * Absolute paths only: every caller hands it a `/workspace/...` path from
556
+ * `remapToContainerPath`, and refusing a relative one keeps the walk's
557
+ * termination (it always reaches `/`, which exists) unconditional.
558
+ */
559
+ const CONTAINER_RESOLVE_NEW_FN = [
560
+ '__cx_resolve_new() {',
561
+ ' local __p=$1 __rest= __c __r',
562
+ ' case $__p in /*) ;; *) return 1 ;; esac',
563
+ ' while ! { [ -e "$__p" ] || [ -L "$__p" ]; }; do',
564
+ ' __c=${__p##*/}',
565
+ ' case $__c in \'\'|.|..) return 1 ;; esac',
566
+ ' __rest=$__c${__rest:+/$__rest}',
567
+ ' __p=${__p%/*}',
568
+ ' [ -n "$__p" ] || __p=/',
569
+ ' done',
570
+ ' __r=$(__cx_resolve "$__p") || return 1',
571
+ ' if [ -z "$__rest" ]; then printf \'%s\\n\' "$__r"; return 0; fi',
572
+ ' case $__r in */) printf \'%s%s\\n\' "$__r" "$__rest" ;; *) printf \'%s/%s\\n\' "$__r" "$__rest" ;; esac',
573
+ '}',
574
+ ].join('\n')
575
+
576
+ /**
577
+ * Resolver per confinement mode — see {@link buildConfinedContainerCommand}.
578
+ *
579
+ * `'read'` now carries `CONTAINER_RESOLVE_NEW_FN` too (#7897): `__cx_resolve`'s
580
+ * optional lenient fallback calls `__cx_resolve_new`, and Glob
581
+ * ({@link buildConfinedGlobBody}) — the only caller that opts in — runs in
582
+ * 'read' mode. The top-level `__cx_ws`/`__cx_target` resolution in `'read'`
583
+ * mode is unaffected: neither call passes the lenient flag, so `__cx_resolve`
584
+ * behaves exactly as before for them, and `__cx_resolve_new` being merely
585
+ * DEFINED (not called) costs nothing.
586
+ */
587
+ const CONFINE_MODES = new Map([
588
+ ['read', { fns: [CONTAINER_RESOLVE_FN, CONTAINER_RESOLVE_NEW_FN], resolver: '__cx_resolve' }],
589
+ ['create', { fns: [CONTAINER_RESOLVE_FN, CONTAINER_RESOLVE_NEW_FN], resolver: '__cx_resolve_new' }],
590
+ ])
591
+
592
+ /**
593
+ * SECURITY (#7354) — wrap `body` in the container-side confinement preamble.
594
+ *
595
+ * The emitted script resolves `workspace` and `target` physically, refuses
596
+ * unless the resolved target is the resolved workspace or under it, and only
597
+ * then prints {@link CONTAINER_CONFINE_OK} and runs `body`. `body` receives the
598
+ * RESOLVED target in `"$__cx_target"` and must use it in place of the lexical
599
+ * path — the same thing the host does (`safeResolveRoot` hands bash the
600
+ * realpath, not the symlinked alias), so a link swapped after the check cannot
601
+ * redirect the read.
602
+ *
603
+ * FAIL CLOSED, in both directions: every bail prints a sentinel and `exit 0`,
604
+ * so the failure arrives as a parseable reply rather than as a non-zero exit
605
+ * that `execInEnvironment` turns into a thrown Error; and the host refuses any
606
+ * stdout whose first line is not one of the three sentinels, so a reply it
607
+ * cannot account for is an error and never "no matches".
608
+ *
609
+ * `mode` picks how `target` is resolved; the workspace is always resolved with
610
+ * `__cx_resolve` and the containment `case` is the same in both:
611
+ * - `'read'` (default) — `__cx_resolve`: the parent must exist. Read, Glob and
612
+ * Grep; their emitted script is unchanged by the existence of `'create'`.
613
+ * - `'create'` (#7876) — `__cx_resolve_new`, the deepest-existing-ancestor
614
+ * walk, for a target that may not exist yet. Write and Edit. The body must
615
+ * create anything it creates under `"$__cx_target"` (e.g.
616
+ * `mkdir -p "${__cx_target%/*}"`), never under the lexical path.
617
+ *
618
+ * @param {{ target: string, body: string, setup?: string, workspace?: string, mode?: 'read'|'create' }} opts
619
+ * `setup` runs AFTER the containment check and BEFORE the OK sentinel; it
620
+ * must be a single command whose non-zero exit means "could not proceed".
621
+ */
622
+ export function buildConfinedContainerCommand({ target, body, setup = '', workspace = '/workspace', mode = 'read' }) {
623
+ const confine = CONFINE_MODES.get(mode)
624
+ // An unknown mode is a caller bug. Falling back to either resolver would pick
625
+ // a containment policy the caller did not ask for, silently.
626
+ if (!confine) throw new Error(`buildConfinedContainerCommand: unknown mode ${JSON.stringify(mode)}`)
627
+ const bail = (sentinel) => `{ printf '%s\\n' '${sentinel}'; exit 0; }`
628
+ const lines = [
629
+ ...confine.fns,
630
+ `__cx_ws=$(__cx_resolve ${shellQuote(workspace)}) || ${bail(CONTAINER_CONFINE_ERROR)}`,
631
+ `__cx_target=$(${confine.resolver} ${shellQuote(target)}) || ${bail(CONTAINER_CONFINE_ERROR)}`,
632
+ `case $__cx_target in "$__cx_ws"|"$__cx_ws"/*) ;; *) ${bail(CONTAINER_CONFINE_ESCAPE)} ;; esac`,
633
+ ]
634
+ if (setup) lines.push(`${setup} || ${bail(CONTAINER_CONFINE_ERROR)}`)
635
+ lines.push(`printf '%s\\n' '${CONTAINER_CONFINE_OK}'`)
636
+ lines.push(body)
637
+ return lines.join('\n')
638
+ }
639
+
640
+ /**
641
+ * SECURITY (#7354) — the container-side Glob body: expand `pattern` under the
642
+ * already-confined `"$__cx_target"` and emit only the matches that RESOLVE
643
+ * inside it.
644
+ *
645
+ * The pattern route needs its own layer because the search root is clean and
646
+ * the MATCH is what leaves: `{"pattern":"esc/*"}` produces `esc/passwd`, which
647
+ * `globMatchEscapesRoot` reads as perfectly in-bounds.
648
+ *
649
+ * Withheld matches are dropped silently AS FAR AS THE MODEL IS CONCERNED — the
650
+ * tool_result is indistinguishable from "matched nothing". That is the #7341
651
+ * rule and it is deliberate: anything that separates "matched, but outside"
652
+ * from "matched nothing" is an existence oracle on a tool that
653
+ * `ACCEPT_EDITS_TOOLS` auto-approves. An escaping `path` ARGUMENT is different
654
+ * and does return an error — the caller named that directory outright, so
655
+ * refusing it tells them nothing they did not already supply.
656
+ *
657
+ * Silent to the model is NOT silent to the operator. The body counts what it
658
+ * withheld and prints {@link CONTAINER_CONFINE_WITHHELD} as a trailer, which
659
+ * the host strips (never forwarding it) and writes to the daemon log. A guard
660
+ * whose only successful outcome is an ordinary-looking success leaves an
661
+ * operator no way to tell it from a guard that was never wired — the shape
662
+ * `docs/false-safety-guards.md` exists to catalogue.
663
+ *
664
+ * COST: one subshell per unique directory, not per match. The last directory's
665
+ * verdict is memoised in two plain variables (glob output is sorted, so runs of
666
+ * matches share a directory) rather than in a bash-4 associative array, and the
667
+ * entry itself is resolved only when the glob already found it to be a symlink
668
+ * — the same shape as the host's `confineGlobMatches`.
669
+ *
670
+ * FAIL CLOSED: a match whose resolution fails is withheld, never emitted.
671
+ *
672
+ * `pattern` MUST already be validated against GLOB_PATTERN_SHELL_METACHARS AND
673
+ * {@link globPatternEscapeReason} by the caller — it is interpolated UNQUOTED so
674
+ * the shell expands it, which is the whole point of the tool and also why
675
+ * containment cannot be delegated to `shellQuote`.
676
+ *
677
+ * This replaced an unconfined `buildGlobCommand` (#7354). The old builder was
678
+ * deleted rather than left beside it: an exported "same thing, no resolution"
679
+ * variant is how a guard comes to be wired to only some of its callers
680
+ * (`docs/false-safety-guards.md`, #7262), and it had exactly one caller.
681
+ *
682
+ * #7357 — matches are NUL-delimited (`printf '%s\0'`), not `\n`-delimited. A
683
+ * filename may legally contain a newline; a `\n`-joined stream can't tell "one
684
+ * match with an embedded newline" apart from "two matches", so the HOST's
685
+ * parser ({@link splitWithheldTrailer}, then the caller's `split('\0')`) would
686
+ * silently turn one real match into two lines — one of them a path that does
687
+ * not exist as spelled. NUL is the one byte a POSIX filename cannot contain,
688
+ * so it is the only delimiter that is unambiguous for every legal match. The
689
+ * withheld-count TRAILER stays `\n`-terminated (see {@link CONTAINER_CONFINE_WITHHELD}) —
690
+ * it is fixed host-authored text, not a filename, so it carries no ambiguity
691
+ * and is the one line the host can split on safely.
692
+ *
693
+ * #7896 — a purely LITERAL match (no `*`/`?`/`[`/`{`) must be existence-checked
694
+ * too. `nullglob` only suppresses a pattern that CONTAINS a wildcard
695
+ * metacharacter and fails to expand; a fully literal `pattern` is never
696
+ * subject to pathname expansion at all, so bash hands the `for` loop the
697
+ * literal word verbatim whether or not anything on disk matches it. The host
698
+ * (`fs.glob`, via `byok-tool-executor.js`'s `runGlob`) always verifies
699
+ * existence, so a literal pattern with no real match must be withheld here the
700
+ * same way — `[ -e "$f" ]`, skipped for a symlink entry since the `-L` branch
701
+ * below already existence-checks (and resolves) it, including the dangling
702
+ * case that legitimately has no target.
703
+ *
704
+ * #7897 — resolving a symlink MATCH now passes `__cx_resolve`'s lenient flag
705
+ * (`"$f" 1`), so a dangling symlink whose target's own parent is also missing
706
+ * (`deep/x.ts -> ./gone/y.ts`, `gone` absent, not just `y.ts`) resolves
707
+ * lexically past that point instead of failing outright — the same "ENOENT
708
+ * stops filesystem access, lexically append the rest" rule the host's
709
+ * `resolveTargetComponentwiseAsync` already applies (see `__cx_resolve`'s doc).
710
+ * The containment check on the next line is UNCHANGED and still the only
711
+ * thing that decides keep-vs-withhold: a lenient resolution that lands outside
712
+ * `$__cx_target` is withheld exactly like any other escaping symlink target,
713
+ * so this only closes an undermatch, never opens an escape.
714
+ */
715
+ export function buildConfinedGlobBody(pattern) {
716
+ return [
717
+ // Two statements, not `shopt -s nullglob globstar`: an image whose bash
718
+ // predates globstar (3.2, still the system bash on macOS) makes the
719
+ // combined form fail, and `nullglob` — the one that decides whether an
720
+ // unmatched pattern is emitted VERBATIM — must not be lost with it.
721
+ 'shopt -s nullglob',
722
+ // `2>/dev/null` is not cosmetic. On a bash with no `globstar` (3.2) the
723
+ // option name is rejected on STDERR, and the caller's "no stdout AND
724
+ // stderr" branch then turns every empty Glob — including one whose matches
725
+ // were all WITHHELD — into `Glob failed: ...` instead of `No matches`.
726
+ // Losing globstar degrades `**` to `*`, which is the intended degradation;
727
+ // turning containment into a container error is not.
728
+ 'shopt -s globstar 2>/dev/null',
729
+ // \x01 cannot appear in a path, so the first iteration always misses.
730
+ '__cx_lastd=$\'\\001\'; __cx_lastv=n; __cx_withheld=0',
731
+ `for f in ${pattern}; do`,
732
+ ' case $f in */*) __cx_d=${f%/*} ;; *) __cx_d=. ;; esac',
733
+ ' if [ "$__cx_d" != "$__cx_lastd" ]; then',
734
+ ' if __cx_r=$(__cx_resolve "$__cx_d"); then',
735
+ ' case $__cx_r in "$__cx_target"|"$__cx_target"/*) __cx_lastv=y ;; *) __cx_lastv=n ;; esac',
736
+ ' else',
737
+ ' __cx_lastv=n',
738
+ ' fi',
739
+ ' __cx_lastd=$__cx_d',
740
+ ' fi',
741
+ ' if [ "$__cx_lastv" != y ]; then __cx_withheld=$((__cx_withheld+1)); continue; fi',
742
+ ' if [ -L "$f" ]; then',
743
+ ' if ! __cx_r=$(__cx_resolve "$f" 1); then __cx_withheld=$((__cx_withheld+1)); continue; fi',
744
+ ' case $__cx_r in "$__cx_target"|"$__cx_target"/*) ;; *) __cx_withheld=$((__cx_withheld+1)); continue ;; esac',
745
+ // #7896 — nullglob only suppresses a WILDCARD pattern that fails to
746
+ // expand; a purely literal `pattern` reaches this loop verbatim even when
747
+ // nothing on disk matches it. A symlink entry (handled above, including
748
+ // dangling) is excluded here since it is not `-e`-testable by definition
749
+ // when dangling and was already existence-checked (via resolution) above.
750
+ ' elif [ ! -e "$f" ]; then',
751
+ ' __cx_withheld=$((__cx_withheld+1)); continue',
752
+ ' fi',
753
+ ' printf \'%s\\0\' "$f"',
754
+ 'done',
755
+ // The operator's trace. Always emitted, including as `... 0`, so the host
756
+ // can tell "nothing was withheld" from "the trailer never arrived" — the
757
+ // same reason the OK sentinel exists.
758
+ `printf '%s %s\\n' '${CONTAINER_CONFINE_WITHHELD}' "$__cx_withheld"`,
759
+ ].join('\n')
760
+ }
761
+
762
+ /**
763
+ * SECURITY (#7354) — host side of {@link buildConfinedContainerCommand}: split
764
+ * the sentinel off the container's stdout.
765
+ *
766
+ * ONLY the three sentinels are accepted. Anything else — an empty reply, a
767
+ * banner some image prints on shell startup, a truncated stream — is
768
+ * `{ ok:false, reason:'unparseable' }`, which callers surface as an error.
769
+ * Treating it as "no matches" instead would be the catalogue's second recurring
770
+ * cause verbatim: "cannot check this" silently treated as "nothing to check".
771
+ *
772
+ * @param {string} stdout
773
+ * @returns {{ ok: true, body: string } | { ok: false, reason: 'escape'|'error'|'unparseable' }}
774
+ */
775
+ export function parseConfinedContainerStdout(stdout) {
776
+ if (typeof stdout !== 'string') return { ok: false, reason: 'unparseable' }
777
+ const nl = stdout.indexOf('\n')
778
+ const first = nl === -1 ? stdout : stdout.slice(0, nl)
779
+ const rest = nl === -1 ? '' : stdout.slice(nl + 1)
780
+ if (first === CONTAINER_CONFINE_OK) return { ok: true, body: rest }
781
+ if (first === CONTAINER_CONFINE_ESCAPE) return { ok: false, reason: 'escape' }
782
+ if (first === CONTAINER_CONFINE_ERROR) return { ok: false, reason: 'error' }
783
+ return { ok: false, reason: 'unparseable' }
784
+ }
785
+
786
+ /**
787
+ * SECURITY (#7354) — split the {@link CONTAINER_CONFINE_WITHHELD} trailer off a
788
+ * confined Glob body.
789
+ *
790
+ * The trailer NEVER reaches the model: stripping it here is what keeps the
791
+ * no-oracle rule while still giving the daemon log a count. It is always the
792
+ * last thing in the body, so it is matched positionally rather than by
793
+ * scanning — a file literally named `__chroxy_confine_withheld__ 3` in the
794
+ * middle of the results cannot be mistaken for it.
795
+ *
796
+ * #7357 — matches above the trailer are NUL-delimited (see
797
+ * {@link buildConfinedGlobBody}), so the trailer is found by locating the
798
+ * LAST `\0` rather than the last `\n`: everything before and including it is
799
+ * the (still NUL-delimited) match stream, untouched; everything after it is
800
+ * the trailer's own `\n`-terminated line. When there are zero matches the
801
+ * body is just the trailer line with no NUL at all, which the `lastIndexOf`
802
+ * fallback (`-1` → treat the whole body as the trailer candidate) handles the
803
+ * same way.
804
+ *
805
+ * `withheld: null` means the trailer was absent, which is reported as "unknown"
806
+ * rather than as zero. The count is observability, not containment (the
807
+ * withholding already happened in the container), so a missing trailer must not
808
+ * read as "nothing was withheld" — that is the catalogue's "cannot check this
809
+ * treated as nothing to check" one register down.
810
+ *
811
+ * @param {string} body
812
+ * @returns {{ body: string, withheld: number | null }}
813
+ */
814
+ export function splitWithheldTrailer(body) {
815
+ if (typeof body !== 'string') return { body: '', withheld: null }
816
+ const lastNul = body.lastIndexOf('\0')
817
+ const matches = lastNul === -1 ? '' : body.slice(0, lastNul + 1)
818
+ const trailerPart = lastNul === -1 ? body : body.slice(lastNul + 1)
819
+ const trailerLine = trailerPart.endsWith('\n') ? trailerPart.slice(0, -1) : trailerPart
820
+ const match = WITHHELD_TRAILER_RE.exec(trailerLine)
821
+ if (!match) return { body, withheld: null }
822
+ return { body: matches, withheld: Number(match[1]) }
823
+ }
824
+
825
+ /**
826
+ * The tool_result message for a confinement failure. `reason` comes from
827
+ * {@link parseConfinedContainerStdout}; `label` is the tool name.
148
828
  */
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`
829
+ export function confinedContainerFailureMessage(label, reason, path) {
830
+ const where = typeof path === 'string' && path.length > 0 ? ` ${path}` : ''
831
+ if (reason === 'escape') {
832
+ return `${label} refused:${where} resolves outside the workspace inside the container (symlinked path)`
833
+ }
834
+ // `unparseable` is NOT a fact about the path (Copilot, PR #7867). The error
835
+ // sentinel says the container resolved the path and failed; an unparseable
836
+ // reply says the container's verdict never arrived — the guard may not have
837
+ // run at all, stdout may have been truncated, an image may have printed a
838
+ // banner. Collapsing the two sends an operator to look at the file when the
839
+ // thing to look at is the container. The refusal is the same either way; the
840
+ // diagnosis is not.
841
+ if (reason === 'unparseable') {
842
+ return `${label} failed: the container returned no valid confinement verdict${where} — the reply was missing or malformed, so the guard's result is unknown and the output was withheld rather than reported as no matches`
843
+ }
844
+ return `${label} failed: could not resolve${where} inside the container (missing, inaccessible, or a symlink loop)`
151
845
  }
152
846
 
153
847
  /**
154
848
  * Derive the rg/grep flag fragments from a Grep tool input: case-insensitive
155
849
  * (`-i`), line numbers (`-n`, default on), and an optional `--glob` filter.
850
+ * `--glob` is ripgrep-specific, so `globArg` is threaded only into
851
+ * `buildGrepCommand`'s `rg` branch. The `grep -r` fallback (used when `rg` is
852
+ * absent, e.g. node:22-slim) gets `grepGlob` instead, from
853
+ * {@link translateGlobForGrep}: `--include=`/`--exclude=` where the glob is
854
+ * faithfully expressible, otherwise a refusal — never a silently unfiltered
855
+ * search (#7961). `ci`/`ln`/`pattern`/`root` apply identically on both
856
+ * branches.
857
+ *
858
+ * SECURITY (#7928): `glob` is model-controlled, same as `pattern`/`root`
859
+ * (#7295) — but unlike those two, it is bound to a NAMED flag (`--glob`)
860
+ * rather than a bare positional, which `argv-safety.js` documents as
861
+ * generally the safer shape (case 3: fuse the value into the same token as
862
+ * the flag, `--flag=<value>`, so it can never be split into a separate argv
863
+ * element). `--glob <value>` (the space-separated form this used to emit) is
864
+ * only as safe as `--glob`'s DECLARED ARITY, and that must be measured, not
865
+ * assumed — the same rule `cliHelpFlagArity`'s doc states for every other CLI
866
+ * in this repo. Measured against ripgrep 15.2.0 (`-g GLOB, --glob=GLOB`,
867
+ * required-arg): the space form already consumed a hostile next token
868
+ * (`--pre=<script>`, `-e`, `--files`, `-h`, `--help`, `-V`, `--version`) as
869
+ * the glob's own value in every case — none reached rg's own option parser as
870
+ * a distinct flag, so no `--pre` execution and no help/version short-circuit.
871
+ *
872
+ * That measurement is still not a fix: it is a fact about one rg build, and
873
+ * `--glob`'s arity is not documented as part of any argv contract this repo
874
+ * controls. The `--glob=<value>` JOINED form below removes the question
875
+ * entirely rather than resting on it — `shellQuote(input.glob)` still closes
876
+ * SHELL injection (unchanged), and butting it directly against `--glob=` with
877
+ * no space fuses both into one shell word, so word-splitting can never hand
878
+ * the value to rg as a second, independent argv element regardless of what
879
+ * `--glob` requires. Proven by `tests/built-in-tools/grep-argv-injection.test.js`.
156
880
  */
157
881
  export function buildGrepArgs(input) {
158
882
  const ci = input?.['-i'] === true ? '-i' : ''
159
883
  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 }
884
+ const hasGlob = typeof input?.glob === 'string' && input.glob.length > 0
885
+ const globArg = hasGlob ? ` --glob=${shellQuote(input.glob)}` : ''
886
+ const grepGlob = hasGlob ? translateGlobForGrep(input.glob) : undefined
887
+ return { ci, ln, globArg, grepGlob }
888
+ }
889
+
890
+ const GREP_GLOB_MAX_EXPANSIONS = 32
891
+ const GREP_ENUMERATE_FIND_REFUSAL = 'Grep failed: could not list the files to search, because ripgrep is not installed in this environment and `find` could not enumerate the directory'
892
+ const GREP_ENUMERATE_GIT_REFUSAL = 'Grep failed: could not list the files to search, because ripgrep is not installed in this environment and `git ls-files` could not enumerate the work tree'
893
+ // How many files, and how many path characters, one fallback grep invocation is
894
+ // handed. The character budget is what bounds argv: 32768 characters is at most
895
+ // ~128 KiB as UTF-8, under the smallest ARG_MAX in play (macOS: 256 KiB, shared
896
+ // with the environment) even before one more path of up to PATH_MAX is added.
897
+ const GREP_FALLBACK_BATCH = 200
898
+ const GREP_FALLBACK_BATCH_CHARS = 32768
899
+ /**
900
+ * Prefix of the informational lines the fallback writes to stderr (a skipped
901
+ * unreadable directory). They are NOT failures: a no-match search that skipped a
902
+ * directory must still say "No matches", but the container's `maskExit` leaves
903
+ * stderr as the only error signal, so callers drop these lines before deciding.
904
+ * Refusals and real grep errors carry no prefix and stay errors.
905
+ */
906
+ export const GREP_NOTE_PREFIX = 'chroxy-grep-note: '
907
+
908
+ /**
909
+ * Split fallback stderr into the lines that mean failure and the informational
910
+ * notes. `errors` is empty when nothing but notes was written.
911
+ *
912
+ * @param {string} stderr
913
+ * @returns {{ errors: string, notes: string }}
914
+ */
915
+ export function splitGrepNotes(stderr) {
916
+ const errors = []
917
+ const notes = []
918
+ for (const line of String(stderr ?? '').split('\n')) {
919
+ if (line.startsWith(GREP_NOTE_PREFIX)) notes.push(line)
920
+ else errors.push(line)
921
+ }
922
+ return { errors: errors.join('\n').trim(), notes: notes.join('\n') }
923
+ }
924
+ // Bounds on the work/size one glob may cause (Codex review of #7961): the raw
925
+ // glob, and the total length (in characters) of generated --include/--exclude flags.
926
+ const GREP_GLOB_MAX_INPUT = 1024
927
+ const GREP_GLOB_MAX_FLAG_BYTES = 8192
928
+
929
+ /**
930
+ * Expand non-nested `{a,b}` sets into the alternatives grep can take as
931
+ * repeated flags. Returns null for anything it cannot expand faithfully
932
+ * (nested, unbalanced, empty, or more than {@link GREP_GLOB_MAX_EXPANSIONS}).
933
+ */
934
+ function expandSimpleBraces(glob) {
935
+ let results = ['']
936
+ let rest = glob
937
+ while (rest.length > 0) {
938
+ const open = rest.indexOf('{')
939
+ const closeFirst = rest.indexOf('}')
940
+ if (open === -1) {
941
+ if (closeFirst !== -1) return null
942
+ results = results.map((r) => r + rest)
943
+ break
944
+ }
945
+ if (closeFirst !== -1 && closeFirst < open) return null
946
+ const close = rest.indexOf('}', open)
947
+ if (close === -1) return null
948
+ const inner = rest.slice(open + 1, close)
949
+ if (inner.includes('{')) return null
950
+ const alts = inner.split(',')
951
+ const head = rest.slice(0, open)
952
+ // Check cardinality BEFORE building the product, not after.
953
+ if (results.length * alts.length > GREP_GLOB_MAX_EXPANSIONS) return null
954
+ const next = []
955
+ for (const r of results) for (const a of alts) next.push(r + head + a)
956
+ results = next
957
+ rest = rest.slice(close + 1)
958
+ }
959
+ return results
960
+ }
961
+
962
+ /**
963
+ * Translate a Grep tool `glob` into the `grep -r` fallback's file filter
964
+ * (#7961). ripgrep's `--glob` is silently dropped by `grep -r`, which returned
965
+ * every file's matches as if the filter had been applied. Only globs whose
966
+ * grep form is equivalent are translated:
967
+ *
968
+ * - a basename glob (`*.js`, `*.{ts,tsx}`) -> `{ includes }`, one entry per
969
+ * brace alternative (rg matches a slash-less glob against the basename at
970
+ * any depth)
971
+ * - a negated basename glob (`!*.min.js`) -> `{ excludes }`; like rg it also
972
+ * drops anything under a directory of that name
973
+ *
974
+ * Anything else (a `/` or `**` path glob, a backslash escape, nested or
975
+ * oversized braces, an empty negation) cannot be expressed that way, so it
976
+ * returns `{ refusal }` and the command fails loudly rather than searching
977
+ * unfiltered. The alternatives are applied by the shell over the fallback's
978
+ * file list as `case` PATTERNS passed as shell-quoted DATA (never as grep
979
+ * flags), so a glob that begins with `-` is never an option.
980
+ *
981
+ * @param {string} glob
982
+ * @returns {{ includes: string[] } | { excludes: string[] } | { refusal: string }}
983
+ */
984
+ export function translateGlobForGrep(glob) {
985
+ const refuse = (why) => ({
986
+ refusal: `Grep failed: the glob ${JSON.stringify(glob.length > 200 ? `${glob.slice(0, 200)}...` : glob)} cannot be applied because ripgrep is not installed in this environment and grep cannot express it (${why}); use a simple filename glob such as "*.js", or omit the glob`,
987
+ })
988
+ const negated = glob.startsWith('!')
989
+ const body = negated ? glob.slice(1) : glob
990
+ if (body.length === 0) return refuse('empty pattern')
991
+ if (body.length > GREP_GLOB_MAX_INPUT) return refuse('glob too long')
992
+ if (body.includes('/') || body.includes('**') || body.includes('\\')) return refuse('path and escaped globs are not supported')
993
+ const alts = expandSimpleBraces(body)
994
+ if (!alts) return refuse('unsupported brace set')
995
+ if (alts.some((a) => a.length === 0)) return refuse('empty alternative')
996
+ // The alternatives are NOT turned into grep flags any more (#7981): the
997
+ // fallback now greps an explicit file list, so the include/exclude decision is
998
+ // made in the shell over that list (see {@link buildGrepFallbackFunctions}),
999
+ // where it behaves identically on GNU and BSD grep and cannot hit the root
1000
+ // (grep applies --exclude-dir to the command-line root too, which is what
1001
+ // #7961's refusal guarded against). A negated glob also excludes a DIRECTORY
1002
+ // of that name (rg parity), which the shell filter does per path component.
1003
+ if (alts.join('').length > GREP_GLOB_MAX_FLAG_BYTES) return refuse('glob expands to too many characters')
1004
+ return negated ? { excludes: alts } : { includes: alts }
163
1005
  }
164
1006
 
165
1007
  /**
@@ -169,11 +1011,269 @@ export function buildGrepArgs(input) {
169
1011
  * exit 1 on "no matches"; pass `maskExit:true` when the runner rejects on
170
1012
  * non-zero (the container's `execInEnvironment`) so that case isn't a failure.
171
1013
  *
172
- * @param {{ pattern: string, root: string, ci: string, ln: string, globArg: string, maskExit?: boolean }} opts
1014
+ * SECURITY (#7295): BOTH model/caller-controlled interpolations are kept out
1015
+ * of a bare positional slot — the pattern by `-e`, and the root by the `--`
1016
+ * terminator after it. `shellQuote` closes SHELL injection only: bash eats the
1017
+ * quotes, and rg/grep then run their OWN option parser over an argv element
1018
+ * that still begins with `-`. Measured against ripgrep 15.1.0, a positional
1019
+ * `--pre=<path>` value makes rg EXECUTE `<path>` as a per-file preprocessor,
1020
+ * and — with the root swallowed into the pattern slot, leaving rg zero paths —
1021
+ * blocks forever reading stdin. Program execution plus a hung tool call,
1022
+ * through `Grep`.
1023
+ *
1024
+ * That matters because of WHERE this sits. `Grep` gets a reduced (secrets-only)
1025
+ * permission floor via `SECRET_READ_FLOOR_TOOLS`, is auto-approved in
1026
+ * `acceptEdits` mode via `ACCEPT_EDITS_TOOLS`, and can carry a standing
1027
+ * auto-allow rule via `ELIGIBLE_TOOLS` — while `Bash`, which owns this
1028
+ * capability honestly, is refused a whitelist outright by `NEVER_AUTO_ALLOW`.
1029
+ *
1030
+ * The `--` is defence in depth, not a live fix: both callers already guarantee
1031
+ * an absolute root (`safeResolveRoot` on the host, `remapToContainerPath` in
1032
+ * the container). It is here so the builder does not depend on an invariant it
1033
+ * neither states nor tests — a third caller passing a raw client path would
1034
+ * otherwise restore the identical `--pre=` execution through the root slot.
1035
+ * MEASURED: `rg -e TODO '--pre=<script>'` executes the script (rc=0, marker
1036
+ * written); with `--` before it, rc=2 and no execution.
1037
+ *
1038
+ * `--no-config` is both hardening and a correctness fix. rg reads the file named
1039
+ * by `RIPGREP_CONFIG_PATH` and applies it as flags — including `--pre`, so an env
1040
+ * that reaches the daemon reinstates the execution this function exists to stop.
1041
+ * It is not client-reachable today (`buildSafeBashEnv` copies the daemon's own
1042
+ * env, which nothing mutates at runtime), but it also breaks ordinary searching:
1043
+ * MEASURED, a config containing `--pre=/bin/echo` turned a matching search into
1044
+ * rc=1 no-match, silently. Machine-parsed output must not depend on a developer's
1045
+ * personal rg config. `grep` has no equivalent to disable.
1046
+ *
1047
+ * `-e` and not a leading-dash REJECTION: `-Wall` and `--force` are legitimate
1048
+ * search patterns, so rejecting them would be a functional regression. See
1049
+ * `utils/argv-safety.js` (bind-to-a-named-flag); rg and grep accept the
1050
+ * two-token `-e <value>` form, measured. Proven red-before-green by
1051
+ * `tests/built-in-tools/grep-argv-injection.test.js`, which spawns the built
1052
+ * command and asserts the preprocessor never runs.
1053
+ *
1054
+ * `rootExpr` (#7354) replaces the quoted literal root with a shell EXPRESSION —
1055
+ * the container passes `"$__cx_target"`, the variable the confinement preamble
1056
+ * left the physically-resolved root in. It exists so the container can search
1057
+ * the resolved path rather than the symlinked alias it was handed, which is
1058
+ * exactly what the host already does (`buildGrepCommand` is called with
1059
+ * `safeResolveRoot`'s realpath). The caller owns the quoting of that expression;
1060
+ * the `--` terminator — the part that carries the #7295 property — is unchanged
1061
+ * either way, so a root that still begins with `-` cannot reach rg's own option
1062
+ * parser through this door.
1063
+ *
1064
+ * `globArg` (#7928) is `buildGrepArgs`'s third model-controlled interpolation,
1065
+ * and is a THIRD, distinct case from `pattern`/`root` above: it is bound to a
1066
+ * named flag rather than a bare positional, so `buildGrepArgs` fuses it into
1067
+ * one token (`--glob=<value>`, argv-safety.js case 3) instead of using a `-e`-
1068
+ * style two-token bind or a `--` terminator — either of those needs a
1069
+ * positional slot to terminate INTO, which `--glob` does not have. See
1070
+ * `buildGrepArgs`'s own doc for the measurement (ripgrep 15.2.0, required-arg)
1071
+ * and why the fix does not rest on it.
1072
+ *
1073
+ * `grepGlob` (#7961) is the fallback's counterpart to `globArg`, from
1074
+ * `buildGrepArgs`. It is REQUIRED whenever `globArg` is non-empty: a caller
1075
+ * that forwards only `globArg` would reintroduce the silent unfiltered search,
1076
+ * so that combination throws instead of degrading.
1077
+ *
1078
+ * @param {{ pattern: string, root?: string, rootExpr?: string, ci: string, ln: string, globArg: string, grepGlob?: { args: string } | { refusal: string }, maskExit?: boolean }} opts
173
1079
  */
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`
1080
+ export function buildGrepCommand({ pattern, root, rootExpr, ci, ln, globArg, grepGlob, maskExit = false }) {
1081
+ const rootArg = typeof rootExpr === 'string' && rootExpr.length > 0 ? rootExpr : shellQuote(root)
1082
+ if (globArg && !grepGlob) {
1083
+ throw new Error('buildGrepCommand: globArg without grepGlob would leave the grep -r fallback unfiltered (#7961)')
1084
+ }
1085
+ const rgCmd = `rg --no-config ${ci} ${ln} --no-heading${globArg} -e ${shellQuote(pattern)} -- ${rootArg}`
1086
+ const refuse = (msg) => `printf '%s\\n' ${shellQuote(msg)} >&2; (exit 2)`
1087
+ const refusing = grepGlob && 'refusal' in grepGlob
1088
+ const prelude = refusing ? '' : `${buildGrepFallbackFunctions({ pattern, ci, ln, grepGlob })}\n`
1089
+ const grepCmd = refusing ? refuse(grepGlob.refusal) : `__gx_search ${rootArg}`
1090
+ const core = `${prelude}if command -v rg >/dev/null 2>&1; then ${rgCmd}; else ${grepCmd}; fi`
178
1091
  return maskExit ? `${core}; true` : core
179
1092
  }
1093
+
1094
+ /**
1095
+ * The bash functions behind the `grep -r` fallback (#7981). ripgrep skips
1096
+ * hidden and gitignored files by default; `grep -r` skips neither, so with no
1097
+ * rg (every `node:22-slim` container) a plain directory Grep read `.env`,
1098
+ * `.claude/settings.local.json` and friends. Rather than hand `grep -r` the
1099
+ * directory, the fallback builds the candidate file list itself, COMPLETELY,
1100
+ * and only then greps it:
1101
+ *
1102
+ * - inside a git work tree (git present, root not itself gitignored):
1103
+ * `git ls-files -z --cached --others --exclude-standard` (honours
1104
+ * .gitignore, .git/info/exclude, the global excludes), minus tracked files
1105
+ * that are also ignored (`-ci`, subtracted by an in-order merge because
1106
+ * ripgrep skips them). A directory entry (a nested repo / submodule) is
1107
+ * expanded with the find lister;
1108
+ * - otherwise `find . -mindepth 1 ( -name '.*' -prune ) -o -type f -print0`.
1109
+ * Without git, gitignored NON-hidden files cannot be known, so they are
1110
+ * still searched (recorded in docs/security/permission-floor.md). A root
1111
+ * inside a gitignored directory (`build/`, `node_modules/pkg`) takes this
1112
+ * path too: git lists nothing there, which would be a silent no-match where
1113
+ * rg and `grep -r` search it.
1114
+ *
1115
+ * Every candidate must pass: no path component starting with `.` (rg's hidden
1116
+ * rule, judged on the path RELATIVE to the root, so a hidden root or one under
1117
+ * a hidden directory is still searched, the #7961 lesson); the glob; a regular
1118
+ * file; and NO symlinked ancestor under the root (`[ -L ]` on every prefix, with
1119
+ * the last directory's verdict memoised), because a tracked `sub/f.txt` whose
1120
+ * `sub` was later swapped for a link to an outside directory passes `-f` and
1121
+ * `! -L` on the leaf alone. A file root is searched as named, hidden or not.
1122
+ * Unreadable directories under the find lister are pruned with a one-line
1123
+ * stderr note instead of failing the listing.
1124
+ *
1125
+ * FAIL CLOSED: each lister writes an empty record (impossible as a path) after
1126
+ * a successful listing. Nothing is grepped until every lister has been seen to
1127
+ * finish, so a listing failure yields NO stdout and exit 2 (both callers treat
1128
+ * non-empty stdout as success, and the container's maskExit turns the status
1129
+ * into 0). An empty list is a genuine no-match (exit 1). A missing root is exit
1130
+ * 2 before the glob is consulted. Output stays `<root>/<relative>:line:text`
1131
+ * (the prefix `grep -r` produced); exit 0 match, 1 none, 2 error.
1132
+ *
1133
+ * Requires bash (arrays, `read -d ''`, process substitution): the host runs
1134
+ * `bash -c` and the container exec is `bash` too (the confinement preamble
1135
+ * already depends on it).
1136
+ */
1137
+ function buildGrepFallbackFunctions({ pattern, ci, ln, grepGlob }) {
1138
+ const excludes = grepGlob?.excludes ?? []
1139
+ const includes = grepGlob?.includes ?? []
1140
+ const anyOf = (alts, subject) => alts.map((a) => `__gx_m ${shellQuote(a)} ${subject}`).join(' || ')
1141
+ const keep = ['__gx_keep() {', ' local rel=$1 base=${1##*/} d']
1142
+ if (excludes.length) {
1143
+ keep.push(
1144
+ ` if ${anyOf(excludes, '"$base"')}; then return 1; fi`,
1145
+ ' d=${rel%/*}',
1146
+ ' if [ "$d" != "$rel" ]; then',
1147
+ ' while :; do',
1148
+ ` if ${anyOf(excludes, '"${d%%/*}"')}; then return 1; fi`,
1149
+ ' case $d in */*) d=${d#*/};; *) break;; esac',
1150
+ ' done',
1151
+ ' fi',
1152
+ )
1153
+ }
1154
+ if (includes.length) keep.push(` if ! { ${anyOf(includes, '"$base"')}; }; then return 1; fi`)
1155
+ keep.push(' return 0', '}')
1156
+ const grepFiles = `grep -H ${ci} ${ln} -e ${shellQuote(pattern)} --`
1157
+ const refuseWith = (msg) => `printf '%s\\n' ${shellQuote(msg)} >&2`
1158
+ const FIND_LIST = [
1159
+ ' cd -- "$1" || exit 1',
1160
+ ' if find . -maxdepth 0 -readable -executable >/dev/null 2>&1; then',
1161
+ " find . -mindepth 1 \\( -name '.*' -prune \\) -o \\( -type d \\( ! -readable -o ! -executable \\) -print0 -prune \\) -o -type f -print0",
1162
+ ' elif type -P test >/dev/null 2>&1; then',
1163
+ " find . -mindepth 1 \\( -name '.*' -prune \\) -o \\( -type d ! -exec test -r {} -a -x {} \\; -print0 -prune \\) -o -type f -print0",
1164
+ ' else',
1165
+ " find . -mindepth 1 \\( -name '.*' -prune \\) -o -type f -print0",
1166
+ ' fi && printf \'\\0\'',
1167
+ ]
1168
+ return [
1169
+ // `case $2 in $1)`: the VALUE of $1 is a pattern with no further parsing, so
1170
+ // a model-supplied alternative is data here, never shell text.
1171
+ '__gx_m() { case $2 in $1) return 0;; esac; return 1; }',
1172
+ ...keep,
1173
+ // 0 when no ancestor directory of $1 (under the root) is a symlink.
1174
+ '__gx_safe() {',
1175
+ ' local rel=$1 d acc=',
1176
+ ' case $rel in */*) ;; *) return 0;; esac',
1177
+ ' d=${rel%/*}',
1178
+ ' if [ "$d" = "$__gx_lastdir" ]; then return "$__gx_lastrc"; fi',
1179
+ ' __gx_lastdir=$d; __gx_lastrc=0',
1180
+ ' while :; do',
1181
+ ' acc=$acc${d%%/*}',
1182
+ ' if [ -L "$__gx_root/$acc" ]; then __gx_lastrc=1; break; fi',
1183
+ ' case $d in */*) d=${d#*/}; acc=$acc/;; *) break;; esac',
1184
+ ' done',
1185
+ ' return "$__gx_lastrc"',
1186
+ '}',
1187
+ '__gx_consider() {',
1188
+ ' local f=$1 p',
1189
+ ' case /$f in */.*) return 0;; esac',
1190
+ ' __gx_keep "$f" || return 0',
1191
+ ' __gx_safe "$f" || return 0',
1192
+ ' p=$__gx_root/$f',
1193
+ ' if [ -f "$p" ] && [ ! -L "$p" ]; then __gx_cand+=("$p"); fi',
1194
+ '}',
1195
+ // $1 = directory to list, $2 = path prefix of its entries relative to the root.
1196
+ '__gx_find_dir() {',
1197
+ ' local f ok=0',
1198
+ " while IFS= read -r -d '' f; do",
1199
+ ' if [ -z "$f" ]; then ok=1; continue; fi',
1200
+ ' f=${f#./}',
1201
+ ' if [ -d "$1/$f" ] && [ ! -L "$1/$f" ]; then',
1202
+ ` printf '%s%s: Permission denied (skipped)\\n' ${shellQuote(GREP_NOTE_PREFIX)} "$__gx_root/$2$f" >&2`,
1203
+ ' continue',
1204
+ ' fi',
1205
+ ' __gx_consider "$2$f"',
1206
+ ' done < <(',
1207
+ ...FIND_LIST,
1208
+ ' )',
1209
+ ' [ "$ok" = 1 ] || __gx_fail=find',
1210
+ '}',
1211
+ '__gx_flush() {',
1212
+ ' [ "${#__gx_batch[@]}" -gt 0 ] || return 0',
1213
+ ` ${grepFiles} "\${__gx_batch[@]}" </dev/null`,
1214
+ ' case $? in 0) __gx_rc=0;; 1) ;; *) __gx_err=1;; esac',
1215
+ ' __gx_batch=()',
1216
+ '}',
1217
+ '__gx_search() {',
1218
+ ' local root=$1 f p lister=find ok=0 bytes=0 prefix rc',
1219
+ ' __gx_root=${root%/}; __gx_cand=(); __gx_tci=(); __gx_ti=0; __gx_fail=',
1220
+ ' __gx_lastdir=; __gx_lastrc=0; __gx_batch=(); __gx_rc=1; __gx_err=0',
1221
+ ' if [ ! -e "$root" ] && [ ! -L "$root" ]; then',
1222
+ " printf 'grep: %s: No such file or directory\\n' \"$root\" >&2; return 2",
1223
+ ' fi',
1224
+ ' if [ ! -d "$root" ]; then',
1225
+ ' __gx_keep "${root##*/}" || return 1',
1226
+ ` ${grepFiles} "$root" </dev/null; return`,
1227
+ ' fi',
1228
+ // Every git call's status is read, none is assumed. `--is-inside-work-tree`
1229
+ // failing means "not a work tree" (git exits 128 outside one), which is the
1230
+ // find lister's job. After that point a git failure is an ERROR, never a
1231
+ // default: a failed `--show-prefix` must not read as the empty top-level
1232
+ // prefix, and `check-ignore` is 0 ignored / 1 not ignored / else error.
1233
+ ' if command -v git >/dev/null 2>&1 && [ "$(git -C "$root" -c core.fsmonitor=false rev-parse --is-inside-work-tree 2>/dev/null)" = true ]; then',
1234
+ ` prefix=$(git -C "$root" -c core.fsmonitor=false rev-parse --show-prefix 2>/dev/null) || { ${refuseWith(GREP_ENUMERATE_GIT_REFUSAL)}; return 2; }`,
1235
+ ' lister=git',
1236
+ ' if [ -n "$prefix" ]; then',
1237
+ ' git -C "$root" -c core.fsmonitor=false check-ignore -q . >/dev/null 2>&1; rc=$?',
1238
+ ` case $rc in 0) lister=find;; 1) ;; *) ${refuseWith(GREP_ENUMERATE_GIT_REFUSAL)}; return 2;; esac`,
1239
+ ' fi',
1240
+ ' fi',
1241
+ ` if [ "$lister" = find ] && ! command -v find >/dev/null 2>&1; then ${refuseWith(GREP_ENUMERATE_FIND_REFUSAL)}; return 2; fi`,
1242
+ ' if [ "$lister" = git ]; then',
1243
+ " while IFS= read -r -d '' f; do",
1244
+ ' if [ -z "$f" ]; then ok=1; else __gx_tci+=("$f"); fi',
1245
+ ' done < <(git -C "$root" -c core.fsmonitor=false ls-files -z -ci --exclude-standard && printf \'\\0\')',
1246
+ ' [ "$ok" = 1 ] || __gx_fail=git',
1247
+ ' ok=0',
1248
+ " while IFS= read -r -d '' f; do",
1249
+ ' if [ -z "$f" ]; then ok=1; continue; fi',
1250
+ // Tracked-but-ignored entries arrive in index order. The merge relies on
1251
+ // `ls-files -ci` ordering matching `--cached`'s; if they ever diverge the
1252
+ // pointer stalls and the remaining tracked-ignored files are SEARCHED (it fails
1253
+ // open to ripgrep-less behaviour, never skips a file it should read).
1254
+ ' if [ "$__gx_ti" -lt "${#__gx_tci[@]}" ] && [ "$f" = "${__gx_tci[$__gx_ti]}" ]; then __gx_ti=$((__gx_ti+1)); continue; fi',
1255
+ ' f=${f%/}',
1256
+ ' case /$f in */.*) continue;; esac',
1257
+ ' if [ -d "$__gx_root/$f" ] && [ ! -L "$__gx_root/$f" ]; then',
1258
+ ' __gx_safe "$f/x" || continue',
1259
+ ' __gx_find_dir "$__gx_root/$f" "$f/"',
1260
+ ' continue',
1261
+ ' fi',
1262
+ ' __gx_consider "$f"',
1263
+ ' done < <(git -C "$root" -c core.fsmonitor=false ls-files -z --cached --others --exclude-standard && printf \'\\0\')',
1264
+ ' [ "$ok" = 1 ] || __gx_fail=git',
1265
+ ' else',
1266
+ ' __gx_find_dir "$root" ""',
1267
+ ' fi',
1268
+ ` if [ "$__gx_fail" = git ]; then ${refuseWith(GREP_ENUMERATE_GIT_REFUSAL)}; return 2; fi`,
1269
+ ` if [ -n "$__gx_fail" ]; then ${refuseWith(GREP_ENUMERATE_FIND_REFUSAL)}; return 2; fi`,
1270
+ ' for p in "${__gx_cand[@]}"; do',
1271
+ ' __gx_batch+=("$p"); bytes=$((bytes+${#p}+1))',
1272
+ ` if [ "\${#__gx_batch[@]}" -ge ${GREP_FALLBACK_BATCH} ] || [ "$bytes" -ge ${GREP_FALLBACK_BATCH_CHARS} ]; then __gx_flush; bytes=0; fi`,
1273
+ ' done',
1274
+ ' __gx_flush',
1275
+ ' if [ "$__gx_err" = 1 ]; then return 2; fi',
1276
+ ' return "$__gx_rc"',
1277
+ '}',
1278
+ ].join('\n')
1279
+ }