@parcha/agentrun-serve 0.1.0-beta.33 → 0.1.0-beta.34

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 (381) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +266 -201
  3. package/dist/adapters.d.ts +0 -4
  4. package/dist/adapters.js +11 -15
  5. package/dist/agent-rows.d.ts +98 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +60 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +1 -1
  14. package/dist/api-only.js +2 -2
  15. package/dist/bash-read-only.d.ts +22 -0
  16. package/dist/bash-read-only.js +701 -0
  17. package/dist/box-settings.d.ts +3 -23
  18. package/dist/box-settings.js +7 -51
  19. package/dist/boxes.d.ts +17 -0
  20. package/dist/boxes.js +27 -20
  21. package/dist/browser-commands.d.ts +5 -2
  22. package/dist/browser-commands.js +4 -4
  23. package/dist/browser-computer.d.ts +5 -0
  24. package/dist/browser-computer.js +21 -0
  25. package/dist/browser-cost.d.ts +9 -6
  26. package/dist/browser-cost.js +92 -50
  27. package/dist/browser-live.d.ts +7 -20
  28. package/dist/browser-live.js +15 -93
  29. package/dist/browser-person.d.ts +18 -51
  30. package/dist/browser-person.js +94 -277
  31. package/dist/cap.d.ts +8 -5
  32. package/dist/cap.js +12 -5
  33. package/dist/cli.js +39 -13
  34. package/dist/closed-pipes.d.ts +2 -0
  35. package/dist/closed-pipes.js +13 -0
  36. package/dist/computer-commands.d.ts +2 -0
  37. package/dist/computer-commands.js +2 -0
  38. package/dist/computer-keys.js +5 -2
  39. package/dist/computer-setting.d.ts +20 -4
  40. package/dist/computer-setting.js +25 -5
  41. package/dist/computers.d.ts +30 -2
  42. package/dist/computers.js +70 -11
  43. package/dist/confine.d.ts +120 -0
  44. package/dist/confine.js +436 -0
  45. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  46. package/dist/console/assets/index-opTN5Naq.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decision-rows.d.ts +1 -1
  49. package/dist/decision-rows.js +1 -1
  50. package/dist/docker-daemon.d.ts +31 -0
  51. package/dist/docker-daemon.js +56 -0
  52. package/dist/effort-guidance.js +4 -3
  53. package/dist/environment.d.ts +0 -3
  54. package/dist/environment.js +3 -5
  55. package/dist/errors.d.ts +0 -2
  56. package/dist/errors.js +6 -9
  57. package/dist/filed-answer.d.ts +32 -0
  58. package/dist/filed-answer.js +160 -0
  59. package/dist/files.d.ts +1 -3
  60. package/dist/files.js +2 -4
  61. package/dist/github-connection.d.ts +1 -1
  62. package/dist/graph-view.d.ts +3 -5
  63. package/dist/graph-view.js +4 -14
  64. package/dist/handed-values.d.ts +9 -0
  65. package/dist/handed-values.js +26 -0
  66. package/dist/harness-install.d.ts +1 -7
  67. package/dist/harness-install.js +1 -18
  68. package/dist/harness-opencode/adapter.d.ts +7 -0
  69. package/dist/harness-opencode/adapter.js +23 -6
  70. package/dist/harness-opencode/index.d.ts +1 -1
  71. package/dist/harness-opencode/index.js +1 -1
  72. package/dist/harness-opencode/verify.d.ts +17 -0
  73. package/dist/harness-opencode/verify.js +30 -10
  74. package/dist/harness-table.js +6 -1
  75. package/dist/heard.js +1 -1
  76. package/dist/held-fd.d.ts +5 -0
  77. package/dist/held-fd.js +14 -0
  78. package/dist/host-calls.d.ts +20 -0
  79. package/dist/host-calls.js +12 -0
  80. package/dist/host-tools.d.ts +4 -21
  81. package/dist/host-tools.js +4 -61
  82. package/dist/host.d.ts +2 -4
  83. package/dist/host.js +2 -7
  84. package/dist/import-summary.d.ts +1 -5
  85. package/dist/import-summary.js +0 -21
  86. package/dist/import.d.ts +6 -6
  87. package/dist/import.js +14 -15
  88. package/dist/key-refusal.d.ts +5 -1
  89. package/dist/key-refusal.js +19 -4
  90. package/dist/learn/check.d.ts +6 -2
  91. package/dist/learn/check.js +83 -29
  92. package/dist/learn/folder.d.ts +5 -1
  93. package/dist/learn/folder.js +10 -3
  94. package/dist/learn/grade.d.ts +14 -0
  95. package/dist/learn/grade.js +68 -12
  96. package/dist/learn/index.d.ts +4 -4
  97. package/dist/learn/index.js +4 -4
  98. package/dist/learn/reflect.d.ts +31 -2
  99. package/dist/learn/reflect.js +79 -4
  100. package/dist/learn/relevance.d.ts +24 -0
  101. package/dist/learn/relevance.js +91 -0
  102. package/dist/learn/secrets.d.ts +7 -1
  103. package/dist/learn/secrets.js +86 -19
  104. package/dist/learn/skills.d.ts +112 -14
  105. package/dist/learn/skills.js +556 -52
  106. package/dist/learned-workflow.d.ts +32 -1
  107. package/dist/learned-workflow.js +100 -9
  108. package/dist/learning-routes.d.ts +8 -4
  109. package/dist/learning-routes.js +23 -9
  110. package/dist/learning-run.d.ts +9 -26
  111. package/dist/learning-run.js +22 -32
  112. package/dist/learning-words.d.ts +12 -5
  113. package/dist/learning-words.js +18 -9
  114. package/dist/learning.d.ts +93 -77
  115. package/dist/learning.js +176 -304
  116. package/dist/live/stream.js +1 -1
  117. package/dist/live/translate.js +12 -2
  118. package/dist/local-models.d.ts +11 -5
  119. package/dist/local-models.js +13 -8
  120. package/dist/mcp-gateway.d.ts +11 -49
  121. package/dist/mcp-gateway.js +44 -135
  122. package/dist/mcp-oauth.d.ts +10 -14
  123. package/dist/mcp-oauth.js +14 -32
  124. package/dist/mcp-probe.d.ts +0 -7
  125. package/dist/mcp-probe.js +4 -10
  126. package/dist/mcp-servers-store.d.ts +6 -6
  127. package/dist/mcp-servers-store.js +12 -14
  128. package/dist/mcp-store.js +3 -4
  129. package/dist/mcp.js +4 -3
  130. package/dist/model.d.ts +6 -7
  131. package/dist/model.js +43 -27
  132. package/dist/monid.d.ts +0 -2
  133. package/dist/monid.js +3 -6
  134. package/dist/openapi.d.ts +8 -1
  135. package/dist/openapi.js +121 -47
  136. package/dist/page.d.ts +1 -3
  137. package/dist/page.js +6 -18
  138. package/dist/paid-calls.d.ts +21 -27
  139. package/dist/paid-calls.js +25 -60
  140. package/dist/propose.js +83 -39
  141. package/dist/push-handler.d.ts +1 -1
  142. package/dist/reflect-range.d.ts +25 -0
  143. package/dist/reflect-range.js +30 -0
  144. package/dist/refusal-words.d.ts +5 -1
  145. package/dist/refusal-words.js +5 -1
  146. package/dist/rows.d.ts +1 -1
  147. package/dist/run-cut.d.ts +0 -6
  148. package/dist/run-cut.js +0 -6
  149. package/dist/run-db.d.ts +2 -11
  150. package/dist/run-db.js +2 -37
  151. package/dist/run-launch.d.ts +19 -2
  152. package/dist/run-launch.js +13 -5
  153. package/dist/run-learning-served.d.ts +10 -4
  154. package/dist/run-learning-served.js +23 -13
  155. package/dist/run-reads-over-store.d.ts +1 -1
  156. package/dist/run-reads-over-store.js +15 -6
  157. package/dist/run-secrets.d.ts +1 -1
  158. package/dist/run-timeline-served.d.ts +5 -1
  159. package/dist/run-timeline-served.js +15 -4
  160. package/dist/run-view.d.ts +7 -8
  161. package/dist/run-view.js +26 -7
  162. package/dist/runnable.d.ts +18 -10
  163. package/dist/runnable.js +21 -10
  164. package/dist/runner/adapter-loop.d.ts +6 -1
  165. package/dist/runner/adapter-loop.js +423 -53
  166. package/dist/runner/adapter-run-spec.d.ts +21 -8
  167. package/dist/runner/adapter-run-spec.js +90 -32
  168. package/dist/runner/adapters/index.js +11 -1
  169. package/dist/runner/adapters/pi.d.ts +12 -2
  170. package/dist/runner/adapters/pi.js +16 -5
  171. package/dist/runner/beside.d.ts +30 -3
  172. package/dist/runner/beside.js +36 -5
  173. package/dist/runner/claim-secrets.d.ts +10 -1
  174. package/dist/runner/claim-secrets.js +48 -14
  175. package/dist/runner/cli-run-spec.d.ts +2 -0
  176. package/dist/runner/cli-run-spec.js +45 -16
  177. package/dist/runner/commands.js +1 -1
  178. package/dist/runner/computer-journal.d.ts +15 -2
  179. package/dist/runner/computer-journal.js +41 -5
  180. package/dist/runner/conformance/harness.js +118 -8
  181. package/dist/runner/conformance/subject.d.ts +4 -1
  182. package/dist/runner/dispatch.d.ts +8 -1
  183. package/dist/runner/dispatch.js +81 -7
  184. package/dist/runner/end-of-run.d.ts +8 -2
  185. package/dist/runner/end-of-run.js +10 -4
  186. package/dist/runner/github-app.js +1 -1
  187. package/dist/runner/harness-loops.d.ts +9 -1
  188. package/dist/runner/harness-loops.js +15 -2
  189. package/dist/runner/journal-kinds.d.ts +24 -6
  190. package/dist/runner/journal-kinds.js +20 -5
  191. package/dist/runner/journal-reader.d.ts +1 -1
  192. package/dist/runner/journal-reader.js +2 -2
  193. package/dist/runner/learning-ask.d.ts +4 -0
  194. package/dist/runner/learning-ask.js +15 -1
  195. package/dist/runner/learning-end.d.ts +18 -3
  196. package/dist/runner/learning-end.js +113 -11
  197. package/dist/runner/learning-loop.d.ts +5 -0
  198. package/dist/runner/learning-loop.js +26 -6
  199. package/dist/runner/main.d.ts +56 -9
  200. package/dist/runner/main.js +127 -18
  201. package/dist/runner/mcp-claim.js +1 -2
  202. package/dist/runner/mcp-run.d.ts +2 -0
  203. package/dist/runner/mcp-run.js +15 -5
  204. package/dist/runner/memory-claim.d.ts +9 -0
  205. package/dist/runner/memory-claim.js +25 -0
  206. package/dist/runner/metrics.d.ts +33 -1
  207. package/dist/runner/metrics.js +85 -1
  208. package/dist/runner/model-route.d.ts +13 -0
  209. package/dist/runner/model-route.js +133 -9
  210. package/dist/runner/reflect-hook.d.ts +12 -1
  211. package/dist/runner/reflect-hook.js +33 -3
  212. package/dist/runner/runner.d.ts +20 -0
  213. package/dist/runner/runner.js +56 -10
  214. package/dist/runner/store-port.d.ts +1 -1
  215. package/dist/runner/store-secrets.d.ts +3 -3
  216. package/dist/runner/store-secrets.js +8 -12
  217. package/dist/runner/text-tools.d.ts +44 -0
  218. package/dist/runner/text-tools.js +237 -0
  219. package/dist/runner/workflow-loop.d.ts +6 -0
  220. package/dist/runner/workflow-loop.js +6 -4
  221. package/dist/runner/workflow-spec.d.ts +18 -0
  222. package/dist/runner/workflow-spec.js +63 -17
  223. package/dist/runs-over-store.d.ts +7 -2
  224. package/dist/runs-over-store.js +60 -14
  225. package/dist/seal-key.js +5 -43
  226. package/dist/sealed-settings-store.d.ts +19 -4
  227. package/dist/sealed-settings-store.js +9 -9
  228. package/dist/sealing.d.ts +4 -0
  229. package/dist/sealing.js +20 -0
  230. package/dist/secret-cut.d.ts +1 -1
  231. package/dist/secret-cut.js +1 -1
  232. package/dist/secret-name.d.ts +9 -0
  233. package/dist/secret-name.js +15 -0
  234. package/dist/secret-writes.d.ts +0 -1
  235. package/dist/secret-writes.js +0 -1
  236. package/dist/server-fs.d.ts +4 -0
  237. package/dist/server-fs.js +8 -2
  238. package/dist/server-lock.d.ts +0 -24
  239. package/dist/server-lock.js +1 -80
  240. package/dist/server-secrets-store.d.ts +4 -4
  241. package/dist/server-secrets-store.js +9 -31
  242. package/dist/server-secrets.d.ts +4 -9
  243. package/dist/server-secrets.js +12 -36
  244. package/dist/server.d.ts +16 -38
  245. package/dist/server.js +145 -106
  246. package/dist/sign-ins-store.d.ts +34 -36
  247. package/dist/sign-ins-store.js +27 -38
  248. package/dist/sign-ins.d.ts +2 -119
  249. package/dist/sign-ins.js +5 -311
  250. package/dist/standard-webhooks.d.ts +1 -1
  251. package/dist/standard-webhooks.js +1 -1
  252. package/dist/stats.d.ts +3 -2
  253. package/dist/stats.js +1 -1
  254. package/dist/store/agent-body.d.ts +8 -2
  255. package/dist/store/agent-body.js +16 -4
  256. package/dist/store/index.d.ts +2 -2
  257. package/dist/store/index.js +2 -2
  258. package/dist/store/open.d.ts +6 -3
  259. package/dist/store/open.js +2 -2
  260. package/dist/store/postgres/connection.d.ts +18 -2
  261. package/dist/store/postgres/connection.js +156 -32
  262. package/dist/store/postgres/migrate.d.ts +4 -0
  263. package/dist/store/postgres/migrate.js +9 -2
  264. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  265. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  266. package/dist/store/postgres/store.d.ts +9 -2
  267. package/dist/store/postgres/store.js +9 -0
  268. package/dist/store/schema.js +1 -1
  269. package/dist/store/seal.js +2 -2
  270. package/dist/store/sqlite/connection.js +49 -5
  271. package/dist/store/sqlite/run-patch.d.ts +3 -0
  272. package/dist/store/sqlite/run-patch.js +3 -0
  273. package/dist/store/sqlite/store.js +41 -12
  274. package/dist/store/store.d.ts +35 -6
  275. package/dist/store/store.js +12 -2
  276. package/dist/store-reads/cap.d.ts +1 -1
  277. package/dist/store-reads/cap.js +22 -4
  278. package/dist/store-reads/journal.d.ts +9 -6
  279. package/dist/store-reads/journal.js +93 -17
  280. package/dist/store-reads/learning.d.ts +26 -8
  281. package/dist/store-reads/learning.js +12 -4
  282. package/dist/store-reads/workflow.d.ts +1 -1
  283. package/dist/store-reads/workflow.js +1 -1
  284. package/dist/store-view.d.ts +5 -1
  285. package/dist/store-view.js +53 -18
  286. package/dist/template-eval.d.ts +60 -4
  287. package/dist/template-eval.js +120 -54
  288. package/dist/templates.d.ts +24 -10
  289. package/dist/templates.js +69 -38
  290. package/dist/timeline/group.d.ts +33 -0
  291. package/dist/timeline/group.js +77 -0
  292. package/dist/timeline/index.d.ts +7 -0
  293. package/dist/timeline/index.js +7 -0
  294. package/dist/timeline/labels.d.ts +79 -0
  295. package/dist/timeline/labels.js +150 -0
  296. package/dist/timeline/origin.d.ts +56 -0
  297. package/dist/timeline/origin.js +92 -0
  298. package/dist/timeline/render-text.d.ts +11 -0
  299. package/dist/timeline/render-text.js +62 -0
  300. package/dist/timeline/timeline.d.ts +274 -0
  301. package/dist/timeline/timeline.js +1308 -0
  302. package/dist/timeline/util.d.ts +17 -0
  303. package/dist/timeline/util.js +49 -0
  304. package/dist/tool-gate.d.ts +41 -216
  305. package/dist/tool-gate.js +79 -540
  306. package/dist/tool-keys-store.d.ts +11 -12
  307. package/dist/tool-keys-store.js +24 -31
  308. package/dist/tool-keys.d.ts +5 -101
  309. package/dist/tool-keys.js +8 -267
  310. package/dist/tool-plane.d.ts +14 -42
  311. package/dist/tool-plane.js +23 -81
  312. package/dist/tool-settings-store.d.ts +1 -2
  313. package/dist/tool-settings-store.js +5 -8
  314. package/dist/tools.d.ts +30 -18
  315. package/dist/tools.js +97 -107
  316. package/dist/trigger-adapter.d.ts +2 -2
  317. package/dist/trigger-targets.d.ts +13 -1
  318. package/dist/trigger-targets.js +31 -1
  319. package/dist/triggers.d.ts +2 -2
  320. package/dist/triggers.js +3 -3
  321. package/dist/turn-end.d.ts +1 -1
  322. package/dist/turn-end.js +1 -1
  323. package/dist/turns.d.ts +0 -6
  324. package/dist/turns.js +0 -19
  325. package/dist/uploads.js +1 -1
  326. package/dist/usage.d.ts +0 -2
  327. package/dist/usage.js +0 -2
  328. package/dist/validate.d.ts +2 -0
  329. package/dist/validate.js +23 -14
  330. package/dist/webhooks.d.ts +102 -76
  331. package/dist/webhooks.js +266 -233
  332. package/dist/workflow-run.d.ts +114 -0
  333. package/dist/workflow-run.js +144 -0
  334. package/dist/workspace/beneath.d.ts +19 -0
  335. package/dist/workspace/beneath.js +106 -0
  336. package/dist/workspace/computer-deps.d.ts +24 -6
  337. package/dist/workspace/computer-deps.js +108 -20
  338. package/dist/workspace/computer-for-claim.d.ts +12 -11
  339. package/dist/workspace/computer-for-claim.js +76 -15
  340. package/dist/workspace/computer-hold.d.ts +6 -1
  341. package/dist/workspace/computer-hold.js +6 -1
  342. package/dist/workspace/computer-janitor.d.ts +47 -0
  343. package/dist/workspace/computer-janitor.js +182 -0
  344. package/dist/workspace/grep-worker.d.ts +5 -0
  345. package/dist/workspace/grep-worker.js +9 -6
  346. package/dist/workspace/index.d.ts +3 -2
  347. package/dist/workspace/index.js +3 -3
  348. package/dist/workspace/local.d.ts +11 -2
  349. package/dist/workspace/local.js +161 -43
  350. package/dist/workspace/resolve-computer.d.ts +50 -10
  351. package/dist/workspace/resolve-computer.js +46 -11
  352. package/dist/workspace/run-tools.d.ts +13 -31
  353. package/dist/workspace/run-tools.js +10 -27
  354. package/dist/workspace-paths.d.ts +0 -17
  355. package/dist/workspace-paths.js +1 -41
  356. package/dist/workspace.d.ts +0 -14
  357. package/dist/workspace.js +3 -96
  358. package/package.json +13 -13
  359. package/templates/README.md +9 -3
  360. package/templates/market-monitor/agent.md +2 -2
  361. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  362. package/dist/bound-files.d.ts +0 -4
  363. package/dist/bound-files.js +0 -164
  364. package/dist/coding-tools.d.ts +0 -47
  365. package/dist/coding-tools.js +0 -189
  366. package/dist/computer-adb.d.ts +0 -12
  367. package/dist/computer-adb.js +0 -14
  368. package/dist/console/assets/index-Dn0ngwG9.js +0 -535
  369. package/dist/console/assets/index-DvW6Aled.css +0 -1
  370. package/dist/grade.d.ts +0 -63
  371. package/dist/grade.js +0 -150
  372. package/dist/mcp-servers.d.ts +0 -269
  373. package/dist/mcp-servers.js +0 -456
  374. package/dist/packs.d.ts +0 -71
  375. package/dist/packs.js +0 -180
  376. package/dist/sealed-settings.d.ts +0 -60
  377. package/dist/sealed-settings.js +0 -171
  378. package/dist/sessions.d.ts +0 -6
  379. package/dist/sessions.js +0 -109
  380. package/dist/workspace/computer-serves.d.ts +0 -12
  381. package/dist/workspace/computer-serves.js +0 -15
@@ -0,0 +1,701 @@
1
+ // The read-only bash policy: an agent's own tool setting `tool_settings.bash.policy: "read-only"` (a template's
2
+ // `tool_policy: {bash: read-only}`). The tool gate (tool-gate.ts RunGate.decide) reads every bash call's command before it
3
+ // runs or anyone is asked, and refuses, in words the model reads, any command that could write, run code, or read outside
4
+ // the run's folder. A policy adds to bash's permission and is never one, as a pin is: bash: deny still refuses, an allow
5
+ // or an ask decides only once the policy let the command through, and approvals "never" lifts no refusal of it. An
6
+ // approved call is decided again on its resume, so the policy holds then too.
7
+ //
8
+ // The rule, for one command line:
9
+ // - Shape: a shell-style tokenizer (single quotes, double quotes, backslash escapes; a quoted or escaped `;` is part of
10
+ // its word). Commands are joined by `;` or `&&`; a line with a `cd` joins them by `&&` only, so a cd that fails stops
11
+ // what follows. Refused outright: `||`, a lone `&` (backgrounding), `$` (variables, `$(...)`), backticks, subshells and
12
+ // braces, `!`, newlines and carriage returns, NUL, and `~` or `#` at a word's start. A command may pipe into a filter
13
+ // (PIPE_TARGETS), each segment checked as a command. The only redirections are the exact words `2>/dev/null` and
14
+ // `2>&1`; any other `>` or `<` is refused.
15
+ // - Programs: PROGRAMS only (git's read subcommands, grep, sed -n, cat, head, tail, wc, ls, find and the like). Every
16
+ // other program, a shell, an interpreter, a package manager, xargs, env, awk, tee, is refused.
17
+ // - Paths: for every program, `--` ends the options; every positional (and every `--opt=value` value) must stay inside
18
+ // the run's folder, lexically: resolved from the command's directory, never absolute elsewhere, never `~`, never up
19
+ // past the folder with `..`, and never a name on the never-open list (.env*, .ssh/, id_rsa*, *.pem, *.key, .npmrc,
20
+ // .netrc, .git-credentials, credentials). A short option with an attached path (`-f/x`) is refused. The policy reads
21
+ // the command, never the folder: a symbolic link in the folder is followed by the program that opens it, so what a
22
+ // link can reach is the computer's to contain (a run's computer holds no key of the server's).
23
+ // - Globs: a word holding `*`, `?`, `[` or `]` is refused unless all of them are quoted or escaped (the shell never
24
+ // expands it: an expanded glob is the folder's file names, any of which may read as an option), and it is a grep/rg
25
+ // pattern, a `--include=`/`--exclude=`/`--exclude-dir=` value (grep, egrep, fgrep, rg) or find's `-name`/`-iname`
26
+ // value, that value holding no `/`.
27
+ // - git: `--no-pager` and `-C <dir>` (a directory inside the folder; later paths are read from it, as git reads them)
28
+ // may precede a read subcommand (GIT_READS); options that read or write a file, run a program, page, or point git at
29
+ // another repository are refused, their abbreviations too (git takes those).
30
+ // - sed: `-n` with one `N,Mp` range script (`$` for the last line), nothing else. find: no -exec, -execdir, -ok,
31
+ // -okdir, -delete, -fprint*, -fls, -L, -follow or -H. sort: no -o or -T. tail: no -f. diff: no -r. grep and rg: no
32
+ // -R, --pre, --follow; rg no -L, -z or --hostname-bin. `--files0-from` is refused for every program. Each refused
33
+ // long option is refused with every prefix too (`sort --out=f`), as GNU getopt takes an unambiguous prefix.
34
+ // - The shell tools: bash's command is read as above. bash_background and bash_input are refused (a read-only shell
35
+ // runs one command in the foreground); bash_output, bash_list and bash_signal, which reach only processes this run
36
+ // started, pass. A CLI harness's own shell call (codex's `shell`, an argv) is read as the command it runs.
37
+ //
38
+ // What it does not hold: the policy reads bash alone. An agent that may also write or edit can change what a read
39
+ // program obeys (a repository's .git/config names programs git runs), so a read-only agent's tools are read and bash.
40
+ // The never-open list refuses a command that names such a file; it is no fence around the folder's contents: a recursive
41
+ // search (grep -r, rg, git grep, git log -p) reads every file the folder holds. The folder holds the run's own files
42
+ // (its checkout, its inputs), never a key of the server's, and the agent may read all of it.
43
+ import { posix } from "node:path";
44
+ /** The policies an agent may set on bash (tool_settings.bash.policy). */
45
+ export const BASH_POLICIES = ["read-only"];
46
+ /** The programs a read-only command may run. */
47
+ export const PROGRAMS = new Set(["git", "grep", "egrep", "fgrep", "rg", "sed", "ls", "cat", "head", "tail", "wc", "nl", "sort", "uniq", "cut", "tr", "find", "diff", "basename", "dirname", "true", "echo"]);
48
+ /** The programs a command may pipe into: filters of their input. */
49
+ export const PIPE_TARGETS = new Set(["head", "tail", "sed", "wc", "sort", "uniq", "grep", "egrep", "fgrep", "rg", "cut", "tr", "nl"]);
50
+ /** git's read subcommands. */
51
+ export const GIT_READS = new Set(["diff", "show", "log", "blame", "grep", "ls-files", "ls-tree", "rev-parse", "cat-file", "merge-base", "status", "shortlog", "rev-list", "diff-tree", "name-rev", "describe"]);
52
+ /** The only redirections: stderr dropped, or joined to stdout. */
53
+ const REDIRECTIONS = ["2>/dev/null", "2>&1"];
54
+ /** The shell tools that only watch or end a process the run started: nothing for a read-only shell to refuse. */
55
+ const WATCHERS = new Set(["bash_output", "bash_list", "bash_signal"]);
56
+ /** What a refusal adds, so the model knows what it may run instead. */
57
+ export const READ_ONLY_HINT = "Use read commands only: git diff, show, log, grep, ls-files, merge-base or rev-parse; grep -n; sed -n 'N,Mp' FILE; cat, head, tail, wc, ls; find without -exec. Pipe only into head, tail, sed -n, grep, wc, sort, uniq, cut, tr or nl, with no redirection but 2>/dev/null or 2>&1, no $ or backticks, and quote glob patterns.";
58
+ /** The refusal of a call under the read-only policy, as the model reads it: the reason, that it did not run, and what may. */
59
+ export const readOnlyText = (tool, reason, notRun) => `${tool} is read-only for this agent, so this call was refused: ${reason}. ${notRun} ${READ_ONLY_HINT}`;
60
+ // The never-open list: any path segment `.ssh`, or a final name matching.
61
+ const SECRET = [/^\.env/, /^id_rsa/, /\.pem$/, /\.key$/, /^\.npmrc$/, /^\.netrc$/, /^\.git-credentials$/, /^credentials(\.json)?$/];
62
+ const secretPath = (rel) => {
63
+ const segments = rel.split("/");
64
+ return segments.includes(".ssh") || SECRET.some((re) => re.test(segments[segments.length - 1] ?? ""));
65
+ };
66
+ /** `given` from the folder-relative directory `here`, as a folder-relative path ("" for the folder), or undefined when
67
+ * it leaves the folder. Lexical (posix): no link is read. */
68
+ function inFolder(folder, here, given) {
69
+ if (given.startsWith("~") || given.includes("\0"))
70
+ return undefined;
71
+ const abs = posix.resolve(posix.join(folder[0], here), given);
72
+ for (const name of folder.map((one) => posix.resolve(one))) {
73
+ if (abs === name)
74
+ return "";
75
+ if (abs.startsWith(name === "/" ? "/" : `${name}/`))
76
+ return abs.slice(name === "/" ? 1 : name.length + 1);
77
+ }
78
+ return undefined;
79
+ }
80
+ /** `p`, from `here`, as a folder-relative path; throws when it leaves the folder or is on the never-open list. */
81
+ function checkPath(folder, here, p, what = "path") {
82
+ if (p.startsWith("~"))
83
+ throw new Error(`${what} ${p}: ~ is not allowed`);
84
+ const rel = inFolder(folder, here, p);
85
+ if (rel === undefined)
86
+ throw new Error(`${what} ${p} is outside the run's folder`);
87
+ if (secretPath(rel))
88
+ throw new Error(`${what} ${p} is on the never-open list (.env*, .ssh/, id_rsa*, *.pem, *.key, .npmrc, .netrc, .git-credentials, credentials)`);
89
+ return rel;
90
+ }
91
+ /** A grep/rg pattern is never opened, but if its position was misjudged it would be: it must still not name a path
92
+ * outside the folder. The never-open list is not applied to a pattern. */
93
+ function checkPattern(folder, here, p) {
94
+ if (p.startsWith("~"))
95
+ throw new Error(`pattern ${p}: ~ is not allowed`);
96
+ if (inFolder(folder, here, p) === undefined)
97
+ throw new Error(`pattern ${p} would name a path outside the run's folder`);
98
+ }
99
+ /** The shell-style tokenizer. Words come back unquoted; operators are `;`, `&&`, `|` and the two redirections. */
100
+ function tokenize(command) {
101
+ if (/[\n\r]/.test(command))
102
+ throw new Error("newlines and carriage returns are not allowed: give one command line");
103
+ if (/[\u0000\u0001]/.test(command))
104
+ throw new Error("NUL and \\u0001 characters are not allowed");
105
+ const tokens = [];
106
+ let current = "";
107
+ let inWord = false;
108
+ let unquotedGlob = false;
109
+ const push = () => {
110
+ if (inWord)
111
+ tokens.push({ word: (unquotedGlob ? "\u0001" : "") + current });
112
+ current = "";
113
+ inWord = false;
114
+ unquotedGlob = false;
115
+ };
116
+ let i = 0;
117
+ while (i < command.length) {
118
+ const c = command[i];
119
+ if (c === "'") {
120
+ const j = command.indexOf("'", i + 1);
121
+ if (j < 0)
122
+ throw new Error("unterminated quote");
123
+ current += command.slice(i + 1, j);
124
+ inWord = true;
125
+ i = j + 1;
126
+ continue;
127
+ }
128
+ if (c === '"') {
129
+ let j = i + 1;
130
+ while (j < command.length && command[j] !== '"') {
131
+ const d = command[j];
132
+ if (d === "$" || d === "`")
133
+ throw new Error("$ and backticks are not allowed (no variables or command substitution)");
134
+ if (d === "\\" && j + 1 < command.length && '$`"\\'.includes(command[j + 1])) {
135
+ current += command[j + 1];
136
+ j += 2;
137
+ continue;
138
+ }
139
+ current += d;
140
+ j++;
141
+ }
142
+ if (j >= command.length)
143
+ throw new Error("unterminated quote");
144
+ inWord = true;
145
+ i = j + 1;
146
+ continue;
147
+ }
148
+ if (c === "\\") {
149
+ if (i + 1 >= command.length)
150
+ throw new Error("trailing backslash");
151
+ current += command[i + 1];
152
+ inWord = true;
153
+ i += 2;
154
+ continue;
155
+ }
156
+ if (c === " " || c === "\t") {
157
+ push();
158
+ i++;
159
+ continue;
160
+ }
161
+ if (c === ";") {
162
+ push();
163
+ tokens.push({ op: ";" });
164
+ i++;
165
+ continue;
166
+ }
167
+ if (c === "&") {
168
+ if (command[i + 1] === "&") {
169
+ push();
170
+ tokens.push({ op: "&&" });
171
+ i += 2;
172
+ continue;
173
+ }
174
+ throw new Error("a lone & (backgrounding) is not allowed");
175
+ }
176
+ if (c === "|") {
177
+ if (command[i + 1] === "|")
178
+ throw new Error("|| is not allowed");
179
+ push();
180
+ tokens.push({ op: "|" });
181
+ i++;
182
+ continue;
183
+ }
184
+ if (c === ">" || c === "<") {
185
+ // Only the exact words 2>/dev/null and 2>&1, standing alone.
186
+ const start = i - 1;
187
+ const redirection = REDIRECTIONS.find((one) => command.startsWith(one, start));
188
+ const end = start + (redirection ? redirection.length : 0);
189
+ if (redirection && inWord && current === "2" && (start === 0 || " \t".includes(command[start - 1])) &&
190
+ (end === command.length || " \t;|".includes(command[end]) || command.startsWith("&&", end))) {
191
+ current = "";
192
+ inWord = false;
193
+ tokens.push({ op: redirection });
194
+ i = end;
195
+ continue;
196
+ }
197
+ throw new Error("redirection is not allowed (only 2>/dev/null and 2>&1): nothing may be written");
198
+ }
199
+ if ("$`(){}!".includes(c))
200
+ throw new Error(`${JSON.stringify(c)} is not allowed (no variables, command substitution, subshells or history)`);
201
+ if (!inWord && (c === "~" || c === "#"))
202
+ throw new Error(`${JSON.stringify(c)} at a word's start is not allowed`);
203
+ if ("*?[]".includes(c))
204
+ unquotedGlob = true;
205
+ current += c;
206
+ inWord = true;
207
+ i++;
208
+ }
209
+ push();
210
+ return tokens;
211
+ }
212
+ /** The command line's commands, each a pipeline of segments (word lists), and the operators that join them. */
213
+ function parse(command) {
214
+ const commands = [];
215
+ const joins = [];
216
+ let pipe = [[]];
217
+ const endCommand = (last) => {
218
+ const empty = pipe.length === 1 && pipe[0].length === 0;
219
+ if (empty) {
220
+ if (last && commands.length > 0 && joins[joins.length - 1] === ";") {
221
+ joins.pop(); // one trailing `;` is fine
222
+ return;
223
+ }
224
+ throw new Error("empty command");
225
+ }
226
+ if (pipe.some((segment) => segment.length === 0))
227
+ throw new Error("empty pipeline segment");
228
+ commands.push(pipe);
229
+ pipe = [[]];
230
+ };
231
+ for (const token of tokenize(command)) {
232
+ if ("op" in token) {
233
+ if (token.op === ";" || token.op === "&&") {
234
+ endCommand(false);
235
+ joins.push(token.op);
236
+ }
237
+ else if (token.op === "|") {
238
+ if (pipe[pipe.length - 1].length === 0)
239
+ throw new Error("empty pipeline segment");
240
+ pipe.push([]);
241
+ }
242
+ else
243
+ pipe[pipe.length - 1].push(`\u0000${token.op}`);
244
+ }
245
+ else
246
+ pipe[pipe.length - 1].push(token.word);
247
+ }
248
+ endCommand(true);
249
+ if (commands.length === 0)
250
+ throw new Error("empty command");
251
+ return { commands, joins };
252
+ }
253
+ // Long options that read a file, write a file, run a program, page, or point git elsewhere (git's global options and its
254
+ // read subcommands'). An unambiguous abbreviation of one (git takes those) is refused too.
255
+ const GIT_BAD_LONG = [
256
+ "--config", "--config-env", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--super-prefix",
257
+ "--paginate", "--list-cmds", "--attr-source", "--output", "--output-directory", "--ext-diff", "--textconv",
258
+ "--no-index", "--orderfile", "--open-files-in-pager", "--contents", "--ignore-revs-file", "--file",
259
+ "--exclude-from", "--exclude-per-directory", "--pathspec-from-file", "--pathspec-file-nul", "--filters", "--path",
260
+ "--resolve-git-dir", "--git-path", "--show-signature", "--upload-pack", "--receive-pack", "--exec", "--template",
261
+ "--separate-git-dir", "--reference",
262
+ ];
263
+ // Short options after the subcommand with the same effect: -O (an order file, or grep's pager), -X (ls-files' exclude
264
+ // file), blame -S (a revisions file), grep -f (a patterns file).
265
+ const GIT_BAD_SHORT = [/^-O/, /^-X/];
266
+ const GIT_BAD_SUB = { blame: [/^-S/], grep: [/^-f/] };
267
+ function gitOptionBad(sub, a) {
268
+ if (a.startsWith("--")) {
269
+ const name = a.split("=")[0];
270
+ if (name === "--")
271
+ return false;
272
+ return GIT_BAD_LONG.some((bad) => abbreviates(name, bad));
273
+ }
274
+ if (a.startsWith("-"))
275
+ return GIT_BAD_SHORT.some((re) => re.test(a)) || (GIT_BAD_SUB[sub] ?? []).some((re) => re.test(a));
276
+ return false;
277
+ }
278
+ /** An option word: a `--opt=value` value is a path (checked when it looks like one: holds `/`, starts with `.` or `~`);
279
+ * a short option never carries an attached path or `~`. */
280
+ function checkOption(folder, here, a) {
281
+ const eq = a.indexOf("=");
282
+ if (a.startsWith("--") && eq > 0) {
283
+ const value = a.slice(eq + 1);
284
+ if (value && (value.includes("/") || value.startsWith("~") || value.startsWith(".")))
285
+ checkPath(folder, here, value, `option value ${a.slice(0, eq)}=`);
286
+ return;
287
+ }
288
+ if (!a.startsWith("--") && a.includes("/"))
289
+ throw new Error(`option ${a}: an attached path is not allowed; give it as its own word`);
290
+ if (!a.startsWith("--") && a.includes("~"))
291
+ throw new Error(`option ${a}: ~ is not allowed`);
292
+ }
293
+ // Options that take their value as the next word, so that word is not taken for the pattern.
294
+ const GREP_VALUE_OPTS = new Set(["-m", "-A", "-B", "-C", "-d", "-D", "--max-count", "--context", "--after-context", "--before-context", "--binary-files", "--devices", "--directories", "--label", "--group-separator", "--exclude-from"]);
295
+ const RG_VALUE_OPTS = new Set(["-g", "--glob", "--iglob", "-t", "--type", "-T", "--type-not", "--type-add", "-m", "--max-count", "-A", "-B", "-C", "--context", "--after-context", "--before-context", "-M", "--max-columns", "-j", "--threads", "-E", "--encoding", "-r", "--replace", "-d", "--max-depth", "--sort", "--sortr", "--colors", "--path-separator", "--max-filesize", "--context-separator", "--field-match-separator", "--engine", "--ignore-file"]);
296
+ // Short options that take a value, per program (attached, `-e.`, or the next word, `-e .`).
297
+ const GREP_VALUE_LETTERS = "efmABCdD";
298
+ const RG_VALUE_LETTERS = "efgtTmABCMjErd";
299
+ const GREP_LIKE = ["grep", "egrep", "fgrep", "rg"];
300
+ const unmark = (w) => (w.startsWith("\u0001") ? w.slice(1) : w);
301
+ /** For a grep/rg short option word: its first value-taking letter, and that value as attached ("": the next word). */
302
+ function shortValue(program, w) {
303
+ if (!(w.length >= 2 && w[0] === "-" && w[1] !== "-"))
304
+ return null;
305
+ const letters = program === "rg" ? RG_VALUE_LETTERS : GREP_VALUE_LETTERS;
306
+ for (let i = 1; i < w.length; i++)
307
+ if (letters.includes(w[i]))
308
+ return { letter: w[i], attached: w.slice(i + 1) };
309
+ return null;
310
+ }
311
+ /** The index of the `--` that ends the options (not one taken as an option's value), or -1. */
312
+ function endOfOptions(program, rest) {
313
+ const grepLike = GREP_LIKE.includes(program);
314
+ const valueOpts = program === "rg" ? RG_VALUE_OPTS : GREP_VALUE_OPTS;
315
+ for (let k = 0; k < rest.length; k++) {
316
+ const a = rest[k];
317
+ if (a === "--")
318
+ return k;
319
+ if (grepLike) {
320
+ const sv = shortValue(program, a);
321
+ if ((sv && sv.attached === "") || a === "--regexp" || a === "--file" || valueOpts.has(a))
322
+ k++;
323
+ }
324
+ else if (program === "sed" && a === "-e")
325
+ k++;
326
+ }
327
+ return -1;
328
+ }
329
+ /** Whether long option `name` (`--out`, without its `=value`) is `bad` or a prefix of it: GNU getopt and git take any
330
+ * unambiguous prefix (`sort --out=f` is `--output=f`), so each prefix of a refused option is refused too. */
331
+ const abbreviates = (name, bad) => name === bad || (name.length >= 3 && name !== "--" && bad.startsWith(name));
332
+ // Long options that write a file, read a list of files, follow, or run a program, per program, refused with every
333
+ // prefix (abbreviates).
334
+ const LONG_BAN = {
335
+ sort: ["--output", "--compress-program", "--temporary-directory", "--files0-from"],
336
+ wc: ["--files0-from"],
337
+ tail: ["--follow", "--retry"],
338
+ diff: ["--to-file", "--from-file", "--recursive"],
339
+ grep: ["--dereference-recursive"], egrep: ["--dereference-recursive"], fgrep: ["--dereference-recursive"],
340
+ rg: ["--pre", "--pre-glob", "--follow", "--search-zip", "--hostname-bin"],
341
+ };
342
+ /** The indexes of the words options before `dd` (the `--` that ends them, -1: none) take as their value: the next word
343
+ * of a grep/rg option that takes one with none attached (`-e`, `-m`, `--regexp`, `--file`, ...), and of sed's `-e`. */
344
+ function optionValues(program, rest, dd) {
345
+ const values = new Set();
346
+ const grepLike = GREP_LIKE.includes(program);
347
+ const valueOpts = program === "rg" ? RG_VALUE_OPTS : GREP_VALUE_OPTS;
348
+ for (let k = 0; k < rest.length && (dd < 0 || k < dd); k++) {
349
+ const a = rest[k];
350
+ if (!a.startsWith("-") || a === "-")
351
+ continue;
352
+ const sv = grepLike ? shortValue(program, a) : null;
353
+ const takes = grepLike ? (sv !== null && sv.attached === "") || valueOpts.has(a) || a === "--regexp" || a === "--file" : program === "sed" && a === "-e";
354
+ if (takes && k + 1 < rest.length)
355
+ values.add(++k);
356
+ }
357
+ return values;
358
+ }
359
+ // A short-option cluster (`-rf`, `-iz`) may carry a refused letter that an exact match would miss.
360
+ const CLUSTER_BAN = { rg: /[zL]/, sort: /[oT]/, tail: /[fF]/, diff: /r/ };
361
+ const GIT_CLUSTER_BAN = { grep: /[Of]/, blame: /S/, "ls-files": /X/, diff: /O/, log: /O/, show: /O/, "diff-tree": /O/ };
362
+ const shortCluster = (a) => a.length > 2 && a[0] === "-" && a[1] !== "-";
363
+ const SED_RANGE = /^(\d+|\$)(,(\d+|\$|\+\d+))?p$/;
364
+ /** One pipeline segment, run from the folder-relative directory `start`. */
365
+ function checkSegment(folder, start, words) {
366
+ const marked = words.filter((w) => !w.startsWith("\u0000"));
367
+ const args = marked.map(unmark);
368
+ const program = args[0];
369
+ if (program === undefined)
370
+ throw new Error("a redirection alone is no command");
371
+ if (!PROGRAMS.has(program))
372
+ throw new Error(`${JSON.stringify(program)} is not a read command this policy runs`);
373
+ const rest = args.slice(1);
374
+ const restUnquotedGlob = marked.slice(1).map((w) => w.startsWith("\u0001"));
375
+ let here = start;
376
+ const dd = endOfOptions(program, rest);
377
+ const isOption = (idx) => (dd < 0 || idx < dd) && rest[idx].startsWith("-") && rest[idx] !== "-";
378
+ const exempt = new Set(); // never opened as files: the sed script, git's subcommand and -C, a rev:path
379
+ const patterns = new Set(); // grep/rg patterns: a relaxed check (checkPattern)
380
+ if (dd >= 0)
381
+ exempt.add(dd);
382
+ // The words an option takes as its value (grep's `-e --pre`, sed's `-e`): text, never an option of their own.
383
+ const values = optionValues(program, rest, dd);
384
+ for (let idx = 0; idx < rest.length; idx++) {
385
+ if (values.has(idx))
386
+ continue;
387
+ const name = rest[idx].split("=")[0];
388
+ if (isOption(idx) && (name === "-files0-from" || name === "--files0-from"))
389
+ throw new Error(`${program} ${rest[idx]} is not allowed (it reads a list of files to open)`);
390
+ if (isOption(idx) && name.startsWith("--") && (LONG_BAN[program] ?? []).some((bad) => abbreviates(name, bad)))
391
+ throw new Error(`${program} ${rest[idx]} is not allowed (it writes or names a file to read, follows, or runs a program; a prefix of such an option is refused too)`);
392
+ const ban = CLUSTER_BAN[program];
393
+ if (ban && isOption(idx) && shortCluster(rest[idx]) && ban.test(rest[idx].slice(1)))
394
+ throw new Error(`${program} option ${rest[idx]} is not allowed`);
395
+ }
396
+ switch (program) {
397
+ case "git": {
398
+ // Before the subcommand: --no-pager, and -C <dir> inside the folder (git reads later paths from it).
399
+ let k = 0;
400
+ for (;;) {
401
+ if (rest[k] === "--no-pager") {
402
+ exempt.add(k);
403
+ k++;
404
+ continue;
405
+ }
406
+ if (rest[k] === "-C") {
407
+ const dir = rest[k + 1];
408
+ if (dir === undefined)
409
+ throw new Error("git -C needs a directory");
410
+ if (/[*?[\]]/.test(dir))
411
+ throw new Error(`git -C ${dir}: a glob is not allowed`);
412
+ here = checkPath(folder, here, dir, "git -C");
413
+ exempt.add(k);
414
+ exempt.add(k + 1);
415
+ k += 2;
416
+ continue;
417
+ }
418
+ break;
419
+ }
420
+ const sub = rest[k];
421
+ if (sub === undefined || !GIT_READS.has(sub))
422
+ throw new Error(`git ${sub ?? ""} is not allowed: only --no-pager and -C <dir> may precede a read subcommand (${[...GIT_READS].join(", ")})`);
423
+ exempt.add(k);
424
+ for (let idx = k + 1; idx < rest.length; idx++) {
425
+ const a = rest[idx];
426
+ if (gitOptionBad(sub, a))
427
+ throw new Error(`git ${sub} option ${a} is not allowed (it reads or writes a file, runs a program, pages or points git elsewhere)`);
428
+ const ban = GIT_CLUSTER_BAN[sub];
429
+ if (ban && isOption(idx) && shortCluster(a) && ban.test(a.slice(1)))
430
+ throw new Error(`git ${sub} option ${a} is not allowed`);
431
+ if ((dd < 0 || idx < dd) && /^[^/:]*:/.test(a) && !a.startsWith("-")) {
432
+ // <rev>:<path> reads an object: its path part is checked as a path.
433
+ const p = a.slice(a.indexOf(":") + 1);
434
+ if (p)
435
+ checkPath(folder, here, p);
436
+ exempt.add(idx);
437
+ }
438
+ }
439
+ break;
440
+ }
441
+ case "sed": {
442
+ let hasN = false;
443
+ let sawScript = rest.some((x, k) => x === "-e" && isOption(k));
444
+ for (let k = 0; k < rest.length; k++) {
445
+ const x = rest[k];
446
+ if (k === dd)
447
+ continue;
448
+ if (isOption(k)) {
449
+ if (x === "-n") {
450
+ hasN = true;
451
+ exempt.add(k);
452
+ }
453
+ else if (x === "-E" || x === "-r")
454
+ exempt.add(k);
455
+ else if (x === "-e") {
456
+ if (!SED_RANGE.test(rest[k + 1] ?? ""))
457
+ throw new Error("sed's script must be one N,Mp range");
458
+ exempt.add(k);
459
+ exempt.add(k + 1);
460
+ k++;
461
+ }
462
+ else
463
+ throw new Error(`sed ${x} is not allowed (only -n with an N,Mp range)`);
464
+ }
465
+ else if (!sawScript) {
466
+ if (!SED_RANGE.test(x))
467
+ throw new Error("sed's script must be one N,Mp range");
468
+ exempt.add(k);
469
+ sawScript = true;
470
+ }
471
+ }
472
+ if (!hasN)
473
+ throw new Error("sed needs -n (sed -n 'N,Mp' FILE)");
474
+ break;
475
+ }
476
+ case "grep":
477
+ case "egrep":
478
+ case "fgrep":
479
+ case "rg": {
480
+ let explicit = false;
481
+ const takesValue = program === "rg" ? RG_VALUE_OPTS : GREP_VALUE_OPTS;
482
+ const nextIsValue = (k) => {
483
+ const sv = shortValue(program, rest[k]);
484
+ return (sv !== null && sv.attached === "") || takesValue.has(rest[k]) || rest[k] === "--regexp" || rest[k] === "--file";
485
+ };
486
+ for (let k = 0; k < rest.length; k++) {
487
+ const a = rest[k];
488
+ if (!isOption(k))
489
+ continue;
490
+ if (a === "-R" || a === "--dereference-recursive" || a.startsWith("--pre") || a === "--follow" ||
491
+ (program === "rg" && (a === "-L" || a === "-z" || a.startsWith("--search-zip") || a.startsWith("--hostname-bin")))) {
492
+ throw new Error(`${program} ${a} is not allowed`);
493
+ }
494
+ const sv = shortValue(program, a);
495
+ if (sv && (sv.letter === "e" || sv.letter === "f")) {
496
+ // -e<pat>, -ie<pat>, -e <pat>, -f<file>, -f <file>: explicit patterns, so no positional is the pattern.
497
+ explicit = true;
498
+ if (sv.attached !== "") {
499
+ if (sv.letter === "e")
500
+ checkPattern(folder, here, sv.attached);
501
+ else
502
+ checkPath(folder, here, sv.attached, "pattern file");
503
+ }
504
+ else if (sv.letter === "e")
505
+ patterns.add(k + 1);
506
+ if (sv.attached === "")
507
+ k++;
508
+ continue;
509
+ }
510
+ if (a === "--regexp") {
511
+ patterns.add(k + 1);
512
+ explicit = true;
513
+ k++;
514
+ }
515
+ else if (a.startsWith("--regexp=")) {
516
+ patterns.add(k);
517
+ explicit = true;
518
+ }
519
+ else if (a === "--file") {
520
+ explicit = true;
521
+ k++;
522
+ }
523
+ else if (a.startsWith("--file=")) {
524
+ explicit = true;
525
+ checkPath(folder, here, a.slice("--file=".length), "pattern file");
526
+ }
527
+ // A file an option reads, named in the option's own word: the whole path rule, never-open list included.
528
+ if (a.startsWith("--exclude-from=") || (program === "rg" && a.startsWith("--ignore-file=")))
529
+ checkPath(folder, here, a.slice(a.indexOf("=") + 1), "file");
530
+ else if (nextIsValue(k))
531
+ k++;
532
+ }
533
+ if (!explicit) {
534
+ // The pattern: the first positional that is not an option's value (after `--`, simply the first word).
535
+ for (let k = 0; k < rest.length; k++) {
536
+ if (k === dd)
537
+ continue;
538
+ if (isOption(k)) {
539
+ if (nextIsValue(k))
540
+ k++;
541
+ continue;
542
+ }
543
+ patterns.add(k);
544
+ break;
545
+ }
546
+ }
547
+ break;
548
+ }
549
+ case "find": {
550
+ for (const a of rest)
551
+ if (/^-(exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls|L|follow|H)$/.test(a))
552
+ throw new Error(`find ${a} is not allowed`);
553
+ break;
554
+ }
555
+ case "sort": {
556
+ rest.forEach((a, idx) => {
557
+ if (isOption(idx) && (a.startsWith("-o") || a.startsWith("--output") || a.startsWith("--compress-program") || a.startsWith("--temporary-directory") || a.startsWith("-T")))
558
+ throw new Error(`sort ${a} is not allowed`);
559
+ });
560
+ break;
561
+ }
562
+ case "uniq": {
563
+ if (rest.filter((_, idx) => idx !== dd && !isOption(idx)).length > 1)
564
+ throw new Error("uniq's output file is not allowed");
565
+ break;
566
+ }
567
+ case "tail": {
568
+ rest.forEach((a, idx) => {
569
+ if (isOption(idx) && (a === "-f" || a === "-F" || a.startsWith("--follow") || a.startsWith("--retry")))
570
+ throw new Error("tail -f is not allowed");
571
+ });
572
+ break;
573
+ }
574
+ case "diff": {
575
+ rest.forEach((a, idx) => {
576
+ if (isOption(idx) && (a.startsWith("--to-file") || a.startsWith("--from-file") || a === "-r" || (a.length >= 5 && "--recursive".startsWith(a.split("=")[0]))))
577
+ throw new Error(`diff ${a} is not allowed`);
578
+ });
579
+ break;
580
+ }
581
+ }
582
+ // Globs: quoted, and only in a grep/rg pattern, --include=/--exclude=/--exclude-dir= values (grep family, rg) and find
583
+ // -name/-iname, without '/'.
584
+ for (let idx = 0; idx < rest.length; idx++) {
585
+ const a = rest[idx];
586
+ if (!/[*?[\]]/.test(a))
587
+ continue;
588
+ const m = isOption(idx) ? /^--(include|exclude|exclude-dir)=(.*)$/.exec(a) : null;
589
+ // Every glob must be quoted or escaped: one the shell expands becomes the folder's file names, any of which may read
590
+ // as an option (a file named -delete after find -name *delete).
591
+ const quotedGlob = !restUnquotedGlob[idx];
592
+ const okGrep = GREP_LIKE.includes(program) && m !== null && !m[2].includes("/") && quotedGlob;
593
+ const okFind = program === "find" && idx > 0 && (rest[idx - 1] === "-name" || rest[idx - 1] === "-iname") && !a.includes("/") && quotedGlob;
594
+ const okPattern = patterns.has(idx) && quotedGlob;
595
+ if (!okGrep && !okFind && !okPattern)
596
+ throw new Error(`the glob ${a} is not allowed here (quote it: only in a quoted grep/rg pattern, an --include=, --exclude= or --exclude-dir= value, or find -name/-iname, without '/')`);
597
+ }
598
+ for (let idx = 0; idx < rest.length; idx++) {
599
+ const a = rest[idx];
600
+ if (patterns.has(idx)) {
601
+ checkPattern(folder, here, a);
602
+ continue;
603
+ }
604
+ if (exempt.has(idx))
605
+ continue;
606
+ if (isOption(idx)) {
607
+ checkOption(folder, here, a);
608
+ continue;
609
+ }
610
+ // Every positional is a path, whatever it looks like (a word that is no path names something in the folder).
611
+ checkPath(folder, here, a);
612
+ }
613
+ }
614
+ /** Throws, with the reason, unless `command` is a read-only command line run from `folder`'s first name (relative to the
615
+ * folder: `start`, "" for the folder itself). */
616
+ export function checkReadOnly(command, folder, start = "") {
617
+ const { commands, joins } = parse(command);
618
+ let here = start;
619
+ const hasCd = commands.some((pipeline) => pipeline.some((segment) => unmark(segment.find((w) => !w.startsWith("\u0000")) ?? "") === "cd"));
620
+ // A cd that fails leaves the shell where it was: joined by && only, nothing after it runs then.
621
+ if (hasCd && joins.some((join) => join !== "&&"))
622
+ throw new Error("a command line with cd joins its commands with && only, so nothing runs where cd did not go");
623
+ for (const pipeline of commands) {
624
+ const first = pipeline[0].filter((w) => !w.startsWith("\u0000")).map(unmark);
625
+ if (first[0] === "cd") {
626
+ if (pipeline.length !== 1 || pipeline[0].length !== first.length)
627
+ throw new Error("cd must be a command of its own");
628
+ if (first.length !== 2)
629
+ throw new Error("cd needs exactly one directory");
630
+ // An option-shaped word (`-`, `--`, `-P`) is cd's option, never a directory: with none left, cd goes to $HOME.
631
+ if (first[1].startsWith("-") || /[*?[\]]/.test(first[1]))
632
+ throw new Error(`cd ${first[1]} is not allowed: give cd one directory inside the run's folder`);
633
+ here = checkPath(folder, here, first[1], "cd");
634
+ continue;
635
+ }
636
+ pipeline.forEach((segment, k) => {
637
+ const words = segment.filter((w) => !w.startsWith("\u0000")).map(unmark);
638
+ if (words[0] === "cd")
639
+ throw new Error("cd must be a command of its own");
640
+ if (k > 0 && words[0] !== undefined && !PIPE_TARGETS.has(words[0]))
641
+ throw new Error(`${words[0]} cannot take piped input (pipe only into ${[...PIPE_TARGETS].join(", ")})`);
642
+ checkSegment(folder, here, segment);
643
+ });
644
+ }
645
+ }
646
+ /** A word of an argv, quoted for the shell: what the argv runs, as a command line (no word of it expanded). */
647
+ const quoted = (word) => `'${word.replace(/'/g, `'\\''`)}'`;
648
+ const SHELLS = new Set(["bash", "sh", "zsh", "dash", "/bin/bash", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh", "/bin/zsh", "/bin/dash"]);
649
+ /** The command line a shell call runs, and the folder-relative directory it starts in, or the reason it can't be read.
650
+ * `command` a string (bash, claude-agent's Bash), or an argv (codex's shell: `[bash, -lc, <line>]`, else the argv as
651
+ * is); `workdir` or `cwd`, where given, inside the folder (readOnlyReason checks the command from there and from the
652
+ * folder, as a tool that does not take one runs it in the folder). */
653
+ function commandOf(args, folder) {
654
+ const given = (typeof args === "object" && args !== null ? args : {});
655
+ if (given.run_in_background === true)
656
+ return { reason: "a command run in the background is not allowed: run it in the foreground" };
657
+ let start = "";
658
+ for (const key of ["workdir", "cwd"]) {
659
+ const dir = given[key];
660
+ if (dir === undefined)
661
+ continue;
662
+ if (typeof dir !== "string")
663
+ return { reason: `its ${key} is not a path` };
664
+ const rel = inFolder(folder, "", dir);
665
+ if (rel === undefined)
666
+ return { reason: `its ${key} ${dir} is outside the run's folder` };
667
+ start = rel;
668
+ }
669
+ const command = given.command;
670
+ if (typeof command === "string")
671
+ return { line: command, start };
672
+ if (Array.isArray(command) && command.length > 0 && command.every((word) => typeof word === "string")) {
673
+ const argv = command;
674
+ if (argv.length === 3 && SHELLS.has(argv[0]) && (argv[1] === "-c" || argv[1] === "-lc"))
675
+ return { line: argv[2], start };
676
+ return { line: argv.map(quoted).join(" "), start };
677
+ }
678
+ return { reason: "it carries no command this policy can read" };
679
+ }
680
+ /** Why the read-only policy refuses shell tool `tool`'s call with `args`, or undefined when it may go on to the gate's
681
+ * permission. `folder`: the run's folder by its names (the first is where a command starts). */
682
+ export function readOnlyReason(tool, args, folder) {
683
+ if (WATCHERS.has(tool))
684
+ return undefined;
685
+ if (tool !== "bash")
686
+ return `${tool} is not offered: a read-only shell runs one command at a time, in the foreground, with bash`;
687
+ const read = commandOf(args, folder);
688
+ if ("reason" in read)
689
+ return read.reason;
690
+ try {
691
+ // Checked from the folder and from the call's workdir: a tool that does not honor the workdir runs the command in the
692
+ // folder, so it must hold from both.
693
+ checkReadOnly(read.line, folder);
694
+ if (read.start !== "")
695
+ checkReadOnly(read.line, folder, read.start);
696
+ return undefined;
697
+ }
698
+ catch (error) {
699
+ return error.message;
700
+ }
701
+ }