@johnhenry/mallory-cli 0.0.0-stage → 0.1.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 (760) hide show
  1. package/README.md +60 -2
  2. package/bin/mallory.mjs +51 -0
  3. package/package.json +51 -4
  4. package/src/a2a/client.js +511 -0
  5. package/src/a2a/demo-agent.js +396 -0
  6. package/src/a2a/hub.js +578 -0
  7. package/src/a2a/settings.js +88 -0
  8. package/src/a2a/task.js +358 -0
  9. package/src/acp/client.js +573 -0
  10. package/src/acp/demo-agent.js +332 -0
  11. package/src/acp/hub.js +632 -0
  12. package/src/acp/settings.js +78 -0
  13. package/src/actions/map.js +524 -0
  14. package/src/agent/cloud.js +77 -0
  15. package/src/agent/compact.js +84 -0
  16. package/src/agent/constants.js +39 -0
  17. package/src/agent/diff.js +101 -0
  18. package/src/agent/fork.js +159 -0
  19. package/src/agent/grounding.js +73 -0
  20. package/src/agent/guards.js +129 -0
  21. package/src/agent/local-transport.js +152 -0
  22. package/src/agent/loop.js +479 -0
  23. package/src/agent/park-store.js +77 -0
  24. package/src/agent/park.js +76 -0
  25. package/src/agent/ports.js +28 -0
  26. package/src/agent/providers.js +591 -0
  27. package/src/agent/restart.js +51 -0
  28. package/src/agent/router.js +380 -0
  29. package/src/agent/run.js +861 -0
  30. package/src/agent/tools.js +247 -0
  31. package/src/agent-library/engine.js +43 -0
  32. package/src/ai/bridge.js +155 -0
  33. package/src/ai/policy.js +131 -0
  34. package/src/aimatey/vendor.js +18 -0
  35. package/src/audio/container-duration.js +35 -0
  36. package/src/audio/instruments.js +776 -0
  37. package/src/audio/lanes.js +230 -0
  38. package/src/audio/patch.js +1410 -0
  39. package/src/audio/plan.js +276 -0
  40. package/src/audio/rack.js +1006 -0
  41. package/src/audio/sample-trim.js +293 -0
  42. package/src/audio/soundfont.js +243 -0
  43. package/src/audio/take-store.js +87 -0
  44. package/src/audio/takes.js +129 -0
  45. package/src/audio/wav.js +170 -0
  46. package/src/audio/zzfx.js +333 -0
  47. package/src/autonomy/bundle.js +207 -0
  48. package/src/autonomy/confine.js +61 -0
  49. package/src/autonomy/enforce.js +155 -0
  50. package/src/autonomy/file-kv.js +88 -0
  51. package/src/autonomy/ledger.js +203 -0
  52. package/src/autonomy/pins.js +50 -0
  53. package/src/autonomy/psl/index.js +32 -0
  54. package/src/autonomy/psl/suffixes.json +1 -0
  55. package/src/autonomy/record.js +28 -0
  56. package/src/autonomy/routines.js +107 -0
  57. package/src/autonomy/server.js +175 -0
  58. package/src/autonomy/signer-node.js +167 -0
  59. package/src/autonomy/store.js +43 -0
  60. package/src/autonomy/unattended.js +13 -0
  61. package/src/bytes/bytes.js +378 -0
  62. package/src/calc/syntax.js +125 -0
  63. package/src/calc/tex.js +28 -0
  64. package/src/calendar/vendor.js +2 -0
  65. package/src/clipboard.js +130 -0
  66. package/src/clsh/clsh.js +3417 -0
  67. package/src/codec/capnp.js +1804 -0
  68. package/src/codec/core.js +2043 -0
  69. package/src/codec/vendor/avro.js +136 -0
  70. package/src/codec/vendor/cbor.js +25 -0
  71. package/src/codec/vendor/flatbuffers.js +206 -0
  72. package/src/codec/vendor/msgpack.js +9 -0
  73. package/src/codec/vendor/protobuf.js +53 -0
  74. package/src/delegation/caps.js +60 -0
  75. package/src/delegation/config.js +32 -0
  76. package/src/device/model.js +246 -0
  77. package/src/device/recording.js +198 -0
  78. package/src/device/stream-model.js +151 -0
  79. package/src/documents/documents.js +1224 -0
  80. package/src/effects/catalog.js +63 -0
  81. package/src/effects/extras.js +133 -0
  82. package/src/effects/parse.js +339 -0
  83. package/src/embed/protocol.js +131 -0
  84. package/src/env/env.js +159 -0
  85. package/src/exact/vendor.js +45 -0
  86. package/src/example-meta.js +164 -0
  87. package/src/examples.js +94 -0
  88. package/src/export/canvas-image.js +217 -0
  89. package/src/export/expr-latex-lazy.js +8 -0
  90. package/src/export/formats.js +322 -0
  91. package/src/export/latex.js +183 -0
  92. package/src/export/pane.js +184 -0
  93. package/src/export/value.js +452 -0
  94. package/src/export/zip.js +214 -0
  95. package/src/ext/access.js +58 -0
  96. package/src/ext/btasks.js +225 -0
  97. package/src/ext/client.js +209 -0
  98. package/src/ext/tools.js +69 -0
  99. package/src/ext/view.js +105 -0
  100. package/src/ext/webmcp-tabs.js +299 -0
  101. package/src/files/archive.js +232 -0
  102. package/src/files/files.js +317 -0
  103. package/src/formats/json.js +24 -0
  104. package/src/formats/jupyter.js +188 -0
  105. package/src/formats/markdown.js +254 -0
  106. package/src/formats/n8n.js +276 -0
  107. package/src/formats/node-red.js +363 -0
  108. package/src/formats/registry.js +177 -0
  109. package/src/formats/rivet.js +259 -0
  110. package/src/formats/shared.js +98 -0
  111. package/src/formats/structure.js +182 -0
  112. package/src/formats/yaml.js +127 -0
  113. package/src/frame/frame.js +962 -0
  114. package/src/frame/vendor.js +1484 -0
  115. package/src/gate/audit.js +116 -0
  116. package/src/gate/gate.js +365 -0
  117. package/src/gate/policy.js +295 -0
  118. package/src/gate/scripted.js +110 -0
  119. package/src/gate/seams.js +32 -0
  120. package/src/gate/store.js +66 -0
  121. package/src/geometry/model.js +533 -0
  122. package/src/grant-key.js +149 -0
  123. package/src/graph/model.js +381 -0
  124. package/src/headless/a2a-push.js +123 -0
  125. package/src/headless/channels/config.js +142 -0
  126. package/src/headless/channels/connectors.js +283 -0
  127. package/src/headless/channels/index.js +257 -0
  128. package/src/headless/channels/mail.js +197 -0
  129. package/src/headless/channels/mailnet.js +223 -0
  130. package/src/headless/channels/platforms.js +194 -0
  131. package/src/headless/channels/replay.js +49 -0
  132. package/src/headless/cli.js +1397 -0
  133. package/src/headless/companion-client.js +182 -0
  134. package/src/headless/cost-cli.js +177 -0
  135. package/src/headless/deprecations-cli.js +102 -0
  136. package/src/headless/examples.js +48 -0
  137. package/src/headless/ffmpeg-exec.js +217 -0
  138. package/src/headless/gateways/config.js +213 -0
  139. package/src/headless/gateways/homeassistant.js +159 -0
  140. package/src/headless/gateways/index.js +121 -0
  141. package/src/headless/gateways/matter.js +150 -0
  142. package/src/headless/gateways/mqtt-client.js +177 -0
  143. package/src/headless/gateways/mqtt.js +70 -0
  144. package/src/headless/gateways/netway.js +226 -0
  145. package/src/headless/gateways/serverpod-worker.mjs +16 -0
  146. package/src/headless/gateways/serverpod.js +71 -0
  147. package/src/headless/gateways/util.js +27 -0
  148. package/src/headless/grant-cli.js +208 -0
  149. package/src/headless/guard.js +125 -0
  150. package/src/headless/guards.js +124 -0
  151. package/src/headless/machine-cli.js +853 -0
  152. package/src/headless/mcp-endpoint.js +287 -0
  153. package/src/headless/mcp-roots.js +38 -0
  154. package/src/headless/model-endpoint.js +88 -0
  155. package/src/headless/net.js +151 -0
  156. package/src/headless/node.js +263 -0
  157. package/src/headless/npm-tarball.js +29 -0
  158. package/src/headless/operator-page.js +112 -0
  159. package/src/headless/operator.js +242 -0
  160. package/src/headless/people.js +34 -0
  161. package/src/headless/pkg-cli.js +1103 -0
  162. package/src/headless/pkg-serve.js +138 -0
  163. package/src/headless/process-worker.js +88 -0
  164. package/src/headless/runner-remote.js +477 -0
  165. package/src/headless/sandbox-child.mjs +21 -0
  166. package/src/headless/scheduled.js +557 -0
  167. package/src/headless/serve-stream.js +97 -0
  168. package/src/headless/serve.js +2238 -0
  169. package/src/headless/short-links.js +158 -0
  170. package/src/headless/static-dirs.js +207 -0
  171. package/src/headless/trust-file.js +51 -0
  172. package/src/headless/watch.js +291 -0
  173. package/src/headless/ws-connect.js +65 -0
  174. package/src/headless/ws-connections.js +44 -0
  175. package/src/headless/ws-echo.js +150 -0
  176. package/src/headless/ws-proxy.js +354 -0
  177. package/src/headless/ws-ticket.js +48 -0
  178. package/src/hooks/config.js +50 -0
  179. package/src/hooks/engine.js +189 -0
  180. package/src/input/log.js +613 -0
  181. package/src/input/player.js +217 -0
  182. package/src/input/replay.js +209 -0
  183. package/src/jth/vendor.js +28 -0
  184. package/src/ledger/tx.js +94 -0
  185. package/src/machine/apply.js +193 -0
  186. package/src/machine/diff.js +168 -0
  187. package/src/machine/drive.js +296 -0
  188. package/src/machine/engine.js +478 -0
  189. package/src/machine/files-tool.js +76 -0
  190. package/src/machine/lint.js +139 -0
  191. package/src/machine/llmtm-trace.js +117 -0
  192. package/src/machine/llmtm.js +475 -0
  193. package/src/machine/otel.js +80 -0
  194. package/src/machine/pane-provider.js +51 -0
  195. package/src/machine/propose.js +159 -0
  196. package/src/machine/random.js +52 -0
  197. package/src/machine/risk.js +107 -0
  198. package/src/machine/session.js +1017 -0
  199. package/src/machine/shell-tool.js +45 -0
  200. package/src/machine/tape.js +349 -0
  201. package/src/machine/templates.js +104 -0
  202. package/src/machine/trace.js +664 -0
  203. package/src/machine/view.js +73 -0
  204. package/src/machine/vm-tool.js +47 -0
  205. package/src/machine/watchdog.js +46 -0
  206. package/src/mcp/app-args.js +51 -0
  207. package/src/mcp/app-run.js +56 -0
  208. package/src/mcp/apps.js +468 -0
  209. package/src/mcp/cache.js +232 -0
  210. package/src/mcp/client.js +507 -0
  211. package/src/mcp/demo-app.js +183 -0
  212. package/src/mcp/demo-server.js +602 -0
  213. package/src/mcp/elicitation.js +116 -0
  214. package/src/mcp/hub.js +1326 -0
  215. package/src/mcp/roots.js +139 -0
  216. package/src/mcp/sampling.js +105 -0
  217. package/src/mcp/settings.js +125 -0
  218. package/src/mcp/tape.js +292 -0
  219. package/src/mcp/uri-template.js +156 -0
  220. package/src/mcp/wsh-client.js +164 -0
  221. package/src/media/animated-codec.js +7 -0
  222. package/src/media/animated.js +623 -0
  223. package/src/media/compare-agent.js +70 -0
  224. package/src/media/compare-job.js +63 -0
  225. package/src/media/compare-page.js +296 -0
  226. package/src/media/compare-worker.js +14 -0
  227. package/src/media/compare.js +600 -0
  228. package/src/media/contract.js +62 -0
  229. package/src/media/decode-frame.js +57 -0
  230. package/src/media/decode-pool.js +188 -0
  231. package/src/media/ffmpeg-edit.js +344 -0
  232. package/src/media/ffmpeg-wasm-client.js +121 -0
  233. package/src/media/ffmpeg-wasm-session.js +79 -0
  234. package/src/media/ffmpeg-wasm.js +139 -0
  235. package/src/media/ffmpeg-worker.js +23 -0
  236. package/src/media/ffmpeg.js +903 -0
  237. package/src/media/helpers.js +419 -0
  238. package/src/media/keep.js +108 -0
  239. package/src/media/metadata-worker.js +16 -0
  240. package/src/media/metadata.js +2518 -0
  241. package/src/media/mime.js +102 -0
  242. package/src/media/page-decode.js +74 -0
  243. package/src/media/persist.js +114 -0
  244. package/src/media/png.js +226 -0
  245. package/src/media/sample-input.js +67 -0
  246. package/src/media/store.js +86 -0
  247. package/src/media/wav.js +109 -0
  248. package/src/midi/mappings.js +250 -0
  249. package/src/midi/message.js +125 -0
  250. package/src/model/action-hub.js +143 -0
  251. package/src/model/adapters.js +284 -0
  252. package/src/model/agent-runs.js +12 -0
  253. package/src/model/arrange.js +308 -0
  254. package/src/model/automation-clock.js +494 -0
  255. package/src/model/automation.js +653 -0
  256. package/src/model/batches.js +78 -0
  257. package/src/model/binary-view.js +195 -0
  258. package/src/model/breakpoints.js +392 -0
  259. package/src/model/calc-settings.js +65 -0
  260. package/src/model/calendar.js +254 -0
  261. package/src/model/canvas-id.js +5 -0
  262. package/src/model/canvas.js +5048 -0
  263. package/src/model/channel-names.js +29 -0
  264. package/src/model/channels.js +692 -0
  265. package/src/model/chart-clock.js +631 -0
  266. package/src/model/chart-code.js +69 -0
  267. package/src/model/codecs.js +60 -0
  268. package/src/model/companion-access.js +271 -0
  269. package/src/model/companion-pane.js +50 -0
  270. package/src/model/composite.js +324 -0
  271. package/src/model/context.js +380 -0
  272. package/src/model/controls.js +231 -0
  273. package/src/model/converter-presets.js +368 -0
  274. package/src/model/cost.js +580 -0
  275. package/src/model/curve-transform.js +122 -0
  276. package/src/model/cycles.js +176 -0
  277. package/src/model/debug-log.js +168 -0
  278. package/src/model/decision-clock.js +100 -0
  279. package/src/model/decisions.js +265 -0
  280. package/src/model/desk.js +87 -0
  281. package/src/model/device-hub.js +400 -0
  282. package/src/model/diff.js +445 -0
  283. package/src/model/emit-events.js +179 -0
  284. package/src/model/errors.js +238 -0
  285. package/src/model/event-presets.js +297 -0
  286. package/src/model/events.js +1303 -0
  287. package/src/model/explicit-setters.js +139 -0
  288. package/src/model/field-mapping.js +623 -0
  289. package/src/model/files-pane.js +263 -0
  290. package/src/model/flow-idle.js +89 -0
  291. package/src/model/foreach.js +549 -0
  292. package/src/model/frame-loop.js +71 -0
  293. package/src/model/frame-pressure.js +180 -0
  294. package/src/model/function-scaffold.js +1000 -0
  295. package/src/model/geometry-settings.js +54 -0
  296. package/src/model/goals.js +176 -0
  297. package/src/model/graph-settings.js +76 -0
  298. package/src/model/grid-widget.js +175 -0
  299. package/src/model/groups.js +332 -0
  300. package/src/model/hash.js +21 -0
  301. package/src/model/history.js +259 -0
  302. package/src/model/http-copy.js +88 -0
  303. package/src/model/http-send-companion.js +110 -0
  304. package/src/model/http-send.js +163 -0
  305. package/src/model/http-tap.js +521 -0
  306. package/src/model/http-tools.js +1138 -0
  307. package/src/model/import-lock.js +78 -0
  308. package/src/model/imports.js +258 -0
  309. package/src/model/infer-outputs.js +822 -0
  310. package/src/model/ink-connect.js +150 -0
  311. package/src/model/ink-diff.js +75 -0
  312. package/src/model/ink-gone.js +71 -0
  313. package/src/model/ink-route.js +120 -0
  314. package/src/model/ink-svg.js +206 -0
  315. package/src/model/ink.js +739 -0
  316. package/src/model/input-log-hub.js +456 -0
  317. package/src/model/input-split.js +69 -0
  318. package/src/model/json-schema-host.js +9 -0
  319. package/src/model/json-schema.js +368 -0
  320. package/src/model/jth.js +78 -0
  321. package/src/model/latex-expr.js +528 -0
  322. package/src/model/layout-history.js +120 -0
  323. package/src/model/lazy-map.js +88 -0
  324. package/src/model/ledger-pane.js +101 -0
  325. package/src/model/legacy-viaframe.js +90 -0
  326. package/src/model/lessons.js +448 -0
  327. package/src/model/links.js +981 -0
  328. package/src/model/live.js +411 -0
  329. package/src/model/math-widget.js +53 -0
  330. package/src/model/memory-settings.js +33 -0
  331. package/src/model/midi-controls.js +350 -0
  332. package/src/model/nl-time.js +408 -0
  333. package/src/model/notebook.js +137 -0
  334. package/src/model/pane-view-store.js +15 -0
  335. package/src/model/partial.js +115 -0
  336. package/src/model/pause-clock.js +53 -0
  337. package/src/model/peer-pane.js +32 -0
  338. package/src/model/persist-state.js +290 -0
  339. package/src/model/person-only.js +122 -0
  340. package/src/model/pin.js +209 -0
  341. package/src/model/plot-3d.js +213 -0
  342. package/src/model/plot-series.js +157 -0
  343. package/src/model/plot-settings.js +531 -0
  344. package/src/model/ports.js +312 -0
  345. package/src/model/presentation.js +222 -0
  346. package/src/model/preset-apply.js +316 -0
  347. package/src/model/preset-banks.js +335 -0
  348. package/src/model/preset-morph.js +263 -0
  349. package/src/model/preset-ops.js +205 -0
  350. package/src/model/preset-player.js +283 -0
  351. package/src/model/preset-states.js +172 -0
  352. package/src/model/profile-settings.js +109 -0
  353. package/src/model/promote.js +103 -0
  354. package/src/model/protected.js +10 -0
  355. package/src/model/proxy-log.js +230 -0
  356. package/src/model/proxy.js +367 -0
  357. package/src/model/quantity-widget.js +61 -0
  358. package/src/model/queue-book.js +359 -0
  359. package/src/model/quick-add.js +224 -0
  360. package/src/model/rate-limit.js +313 -0
  361. package/src/model/rate.js +95 -0
  362. package/src/model/recovery.js +216 -0
  363. package/src/model/rename-follow.js +113 -0
  364. package/src/model/repeater.js +1126 -0
  365. package/src/model/retention.js +664 -0
  366. package/src/model/route-edit.js +132 -0
  367. package/src/model/router.js +155 -0
  368. package/src/model/runaway.js +232 -0
  369. package/src/model/runlog.js +1033 -0
  370. package/src/model/runners/a2a.js +2 -0
  371. package/src/model/runners/acp.js +2 -0
  372. package/src/model/runners/actions.js +4 -0
  373. package/src/model/runners/agent.js +4 -0
  374. package/src/model/runners/audio.js +21 -0
  375. package/src/model/runners/automation.js +2 -0
  376. package/src/model/runners/calc.js +23 -0
  377. package/src/model/runners/catch.js +10 -0
  378. package/src/model/runners/codec.js +24 -0
  379. package/src/model/runners/companion-run.js +2 -0
  380. package/src/model/runners/device.js +7 -0
  381. package/src/model/runners/dom.js +13 -0
  382. package/src/model/runners/effects.js +2 -0
  383. package/src/model/runners/embed.js +11 -0
  384. package/src/model/runners/eval.js +2 -0
  385. package/src/model/runners/files.js +19 -0
  386. package/src/model/runners/geometry.js +23 -0
  387. package/src/model/runners/goals.js +18 -0
  388. package/src/model/runners/graph.js +23 -0
  389. package/src/model/runners/html.js +2 -0
  390. package/src/model/runners/http-proxy.js +185 -0
  391. package/src/model/runners/http-send.js +61 -0
  392. package/src/model/runners/http-static.js +83 -0
  393. package/src/model/runners/http-tap.js +26 -0
  394. package/src/model/runners/http.js +40 -0
  395. package/src/model/runners/import.js +2 -0
  396. package/src/model/runners/index.js +74 -0
  397. package/src/model/runners/input.js +14 -0
  398. package/src/model/runners/inputlog.js +7 -0
  399. package/src/model/runners/ledger.js +15 -0
  400. package/src/model/runners/machine.js +4 -0
  401. package/src/model/runners/mcp.js +2 -0
  402. package/src/model/runners/mcpapp.js +2 -0
  403. package/src/model/runners/media.js +18 -0
  404. package/src/model/runners/memory.js +28 -0
  405. package/src/model/runners/mesh-inspect.js +13 -0
  406. package/src/model/runners/peer.js +14 -0
  407. package/src/model/runners/plot.js +22 -0
  408. package/src/model/runners/render.js +14 -0
  409. package/src/model/runners/respond.js +2 -0
  410. package/src/model/runners/sample-soundfont.js +85 -0
  411. package/src/model/runners/sample.js +159 -0
  412. package/src/model/runners/scene.js +8 -0
  413. package/src/model/runners/score.js +24 -0
  414. package/src/model/runners/secret.js +10 -0
  415. package/src/model/runners/select.js +2 -0
  416. package/src/model/runners/shared.js +4 -0
  417. package/src/model/runners/shares.js +15 -0
  418. package/src/model/runners/shell.js +7 -0
  419. package/src/model/runners/skill.js +26 -0
  420. package/src/model/runners/state.js +2 -0
  421. package/src/model/runners/statechart.js +4 -0
  422. package/src/model/runners/subgraph.js +9 -0
  423. package/src/model/runners/tabs.js +25 -0
  424. package/src/model/runners/terminal.js +5 -0
  425. package/src/model/runners/text.js +4 -0
  426. package/src/model/runners/timer.js +7 -0
  427. package/src/model/runners/traffic.js +65 -0
  428. package/src/model/runners/trigger.js +2 -0
  429. package/src/model/runners/verdict.js +29 -0
  430. package/src/model/runners/vm.js +7 -0
  431. package/src/model/runners/wait.js +4 -0
  432. package/src/model/runners/ws-client.js +57 -0
  433. package/src/model/safe-regex.js +719 -0
  434. package/src/model/sample-settings.js +43 -0
  435. package/src/model/sample-source.js +47 -0
  436. package/src/model/saved-mapping.js +153 -0
  437. package/src/model/score-controllers.js +87 -0
  438. package/src/model/score-edit.js +399 -0
  439. package/src/model/score-instruments.js +300 -0
  440. package/src/model/score-library.js +407 -0
  441. package/src/model/score-markup.js +235 -0
  442. package/src/model/score-mix.js +248 -0
  443. package/src/model/score-patterns.js +276 -0
  444. package/src/model/score-selection.js +34 -0
  445. package/src/model/score-time.js +139 -0
  446. package/src/model/score-transforms.js +336 -0
  447. package/src/model/score-transport.js +192 -0
  448. package/src/model/selection.js +351 -0
  449. package/src/model/serial-controls.js +328 -0
  450. package/src/model/shares-pane.js +17 -0
  451. package/src/model/shell-pane.js +106 -0
  452. package/src/model/signature.js +1122 -0
  453. package/src/model/size-hints.js +106 -0
  454. package/src/model/size-ratio.js +12 -0
  455. package/src/model/skill-settings.js +23 -0
  456. package/src/model/snapping.js +466 -0
  457. package/src/model/split.js +375 -0
  458. package/src/model/spring-player.js +222 -0
  459. package/src/model/statecharts.js +1369 -0
  460. package/src/model/states-preset.js +208 -0
  461. package/src/model/static-route.js +100 -0
  462. package/src/model/step-words.js +45 -0
  463. package/src/model/subgraph.js +1042 -0
  464. package/src/model/switch.js +98 -0
  465. package/src/model/tabs-store.js +10 -0
  466. package/src/model/tensor-view.js +146 -0
  467. package/src/model/timer-clock.js +361 -0
  468. package/src/model/timers.js +422 -0
  469. package/src/model/timing.js +212 -0
  470. package/src/model/traffic-agent.js +111 -0
  471. package/src/model/traffic-store.js +20 -0
  472. package/src/model/traffic.js +665 -0
  473. package/src/model/transport.js +364 -0
  474. package/src/model/turns.js +86 -0
  475. package/src/model/types.js +425 -0
  476. package/src/model/value-path.js +138 -0
  477. package/src/model/versions.js +535 -0
  478. package/src/model/view-outputs.js +144 -0
  479. package/src/model/viewport-bookmarks.js +194 -0
  480. package/src/model/virtual-clock.js +85 -0
  481. package/src/model/vm-pane.js +258 -0
  482. package/src/model/wait-clock.js +715 -0
  483. package/src/model/wait-persist.js +248 -0
  484. package/src/model/waits.js +431 -0
  485. package/src/model/watch.js +80 -0
  486. package/src/model/webhook.js +496 -0
  487. package/src/model/when.js +48 -0
  488. package/src/model/widget-values.js +392 -0
  489. package/src/model/window-commands.js +278 -0
  490. package/src/model/windows.js +348 -0
  491. package/src/model/wire-inspect.js +343 -0
  492. package/src/model/wire-ops.js +324 -0
  493. package/src/model/wire-pipeline.js +378 -0
  494. package/src/model/wire-route.js +637 -0
  495. package/src/model/workspaces.js +122 -0
  496. package/src/model/ws-client.js +155 -0
  497. package/src/model/ws-demo.js +31 -0
  498. package/src/model/ws-frames.js +141 -0
  499. package/src/model/ws-hub.js +219 -0
  500. package/src/model/ws-served.js +13 -0
  501. package/src/model/xstate.js +374 -0
  502. package/src/narrative/narrative.js +1557 -0
  503. package/src/network/auth.js +224 -0
  504. package/src/network/csp-frame.js +197 -0
  505. package/src/network/declarative-shadow.js +27 -0
  506. package/src/network/frame-net-shim.js +962 -0
  507. package/src/network/hosts.js +157 -0
  508. package/src/network/policy.js +520 -0
  509. package/src/network/rtc-shim.js +418 -0
  510. package/src/network/secret-gate.js +78 -0
  511. package/src/network/secrets.js +261 -0
  512. package/src/network/sockets.js +287 -0
  513. package/src/network/store.js +186 -0
  514. package/src/network/streams.js +99 -0
  515. package/src/packages/asset-values.js +50 -0
  516. package/src/packages/assets.js +99 -0
  517. package/src/packages/deprecation.js +203 -0
  518. package/src/packages/fetch.js +152 -0
  519. package/src/packages/function-canvas.js +73 -0
  520. package/src/packages/module.js +120 -0
  521. package/src/packages/package.js +474 -0
  522. package/src/packages/published.js +27 -0
  523. package/src/packages/requires.js +83 -0
  524. package/src/packages/signing.js +145 -0
  525. package/src/packages/trust.js +107 -0
  526. package/src/panes/a2a.js +51 -0
  527. package/src/panes/acp.js +60 -0
  528. package/src/panes/actions.js +54 -0
  529. package/src/panes/agent.js +83 -0
  530. package/src/panes/audio.js +103 -0
  531. package/src/panes/automation.js +112 -0
  532. package/src/panes/calc.js +67 -0
  533. package/src/panes/catch.js +52 -0
  534. package/src/panes/codec.js +59 -0
  535. package/src/panes/colors.js +12 -0
  536. package/src/panes/companion.js +54 -0
  537. package/src/panes/decision.js +65 -0
  538. package/src/panes/device.js +56 -0
  539. package/src/panes/dom.js +37 -0
  540. package/src/panes/effects.js +118 -0
  541. package/src/panes/embed.js +30 -0
  542. package/src/panes/eval.js +186 -0
  543. package/src/panes/fields.js +299 -0
  544. package/src/panes/files.js +45 -0
  545. package/src/panes/gate.js +70 -0
  546. package/src/panes/geometry.js +64 -0
  547. package/src/panes/goals.js +75 -0
  548. package/src/panes/graph.js +66 -0
  549. package/src/panes/html.js +54 -0
  550. package/src/panes/http.js +82 -0
  551. package/src/panes/import.js +38 -0
  552. package/src/panes/input.js +124 -0
  553. package/src/panes/inputlog.js +66 -0
  554. package/src/panes/ledger.js +56 -0
  555. package/src/panes/machine.js +138 -0
  556. package/src/panes/mcp.js +85 -0
  557. package/src/panes/mcpapp.js +64 -0
  558. package/src/panes/media.js +38 -0
  559. package/src/panes/memory.js +46 -0
  560. package/src/panes/mesh-inspect.js +49 -0
  561. package/src/panes/note.js +38 -0
  562. package/src/panes/peer.js +44 -0
  563. package/src/panes/plot.js +196 -0
  564. package/src/panes/registry.js +475 -0
  565. package/src/panes/render.js +87 -0
  566. package/src/panes/respond.js +44 -0
  567. package/src/panes/router.js +84 -0
  568. package/src/panes/sample.js +75 -0
  569. package/src/panes/scene.js +55 -0
  570. package/src/panes/score.js +87 -0
  571. package/src/panes/secret.js +38 -0
  572. package/src/panes/select.js +67 -0
  573. package/src/panes/shader.js +166 -0
  574. package/src/panes/shared.js +33 -0
  575. package/src/panes/shares.js +43 -0
  576. package/src/panes/shell.js +47 -0
  577. package/src/panes/skill.js +44 -0
  578. package/src/panes/state.js +91 -0
  579. package/src/panes/statechart.js +63 -0
  580. package/src/panes/story.js +33 -0
  581. package/src/panes/subgraph.js +94 -0
  582. package/src/panes/tabs.js +52 -0
  583. package/src/panes/terminal.js +57 -0
  584. package/src/panes/text.js +36 -0
  585. package/src/panes/timer.js +55 -0
  586. package/src/panes/traffic.js +59 -0
  587. package/src/panes/verdict.js +62 -0
  588. package/src/panes/vm.js +46 -0
  589. package/src/panes/wait.js +61 -0
  590. package/src/panes/watch.js +57 -0
  591. package/src/panes/webhook.js +67 -0
  592. package/src/panes/ws-client.js +67 -0
  593. package/src/persist.js +281 -0
  594. package/src/plot/tex.js +19 -0
  595. package/src/plot/vendor.js +59 -0
  596. package/src/plot/view-vendor.js +5 -0
  597. package/src/privacy/levels.js +108 -0
  598. package/src/protocol/devtools.js +116 -0
  599. package/src/protocol/inspector.js +368 -0
  600. package/src/render/time.js +381 -0
  601. package/src/rooms/mesh-metrics.js +162 -0
  602. package/src/run/companion.js +355 -0
  603. package/src/run/describe.js +114 -0
  604. package/src/run/local-model.js +150 -0
  605. package/src/run/monitor.js +208 -0
  606. package/src/run/publish.js +360 -0
  607. package/src/run/respond-outcome.js +12 -0
  608. package/src/run/run.js +820 -0
  609. package/src/run/runner-pairing.js +243 -0
  610. package/src/run/values.js +122 -0
  611. package/src/runtime/compile.js +122 -0
  612. package/src/runtime/console-tag.js +64 -0
  613. package/src/runtime/frame-signals.js +126 -0
  614. package/src/runtime/iteration-push.js +19 -0
  615. package/src/runtime/keys.js +474 -0
  616. package/src/runtime/midi-input.js +170 -0
  617. package/src/runtime/person-waits.js +140 -0
  618. package/src/runtime/resource-timing.js +56 -0
  619. package/src/runtime/runtime.js +2150 -0
  620. package/src/runtime/sandbox-modules.js +163 -0
  621. package/src/runtime/spring.js +246 -0
  622. package/src/runtime/strict.js +215 -0
  623. package/src/runtime/transfer.js +75 -0
  624. package/src/runtime/tween.js +158 -0
  625. package/src/runtime/wasm-fuel.js +596 -0
  626. package/src/runtime/worker/00-prelude.js +88 -0
  627. package/src/runtime/worker/10-helpers.js +295 -0
  628. package/src/runtime/worker/20-io.js +645 -0
  629. package/src/runtime/worker/30-previews.js +210 -0
  630. package/src/runtime/worker/40-profile-lineage.js +278 -0
  631. package/src/runtime/worker/50-own-worker.js +233 -0
  632. package/src/runtime/worker/60-timers.js +172 -0
  633. package/src/runtime/worker/70-state-keyed.js +193 -0
  634. package/src/runtime/worker/80-each-compile-generators.js +619 -0
  635. package/src/runtime/worker/90-events-operators.js +655 -0
  636. package/src/runtime/worker/95-agents-batches.js +1820 -0
  637. package/src/runtime/worker/96-plot.js +47 -0
  638. package/src/runtime/worker/97-calc.js +28 -0
  639. package/src/runtime/worker/98-geometry.js +24 -0
  640. package/src/runtime/worker/99-graph.js +30 -0
  641. package/src/runtime/worker/99-shell.js +30 -0
  642. package/src/safety/config.js +57 -0
  643. package/src/safety/engine.js +324 -0
  644. package/src/scene/pixi-scene.js +806 -0
  645. package/src/scene/scene-assets.js +241 -0
  646. package/src/scene/scene-edit.js +319 -0
  647. package/src/secret/settings.js +41 -0
  648. package/src/security/multipart.js +257 -0
  649. package/src/security/redact.js +261 -0
  650. package/src/serial/broker.js +473 -0
  651. package/src/serial/config.js +185 -0
  652. package/src/serial/framers.js +389 -0
  653. package/src/serial/packets.js +64 -0
  654. package/src/shader/audio-texture.js +87 -0
  655. package/src/shader/channels.js +496 -0
  656. package/src/shader/common.js +90 -0
  657. package/src/shader/model.js +867 -0
  658. package/src/shader/passes.js +150 -0
  659. package/src/shader/shadertoy.js +198 -0
  660. package/src/shell/hub.js +287 -0
  661. package/src/sim/checkpoints.js +850 -0
  662. package/src/sim/compile.js +37 -0
  663. package/src/sim/fixed.js +377 -0
  664. package/src/sim/headless.js +205 -0
  665. package/src/sim/physics.js +399 -0
  666. package/src/smf-helper/vendor.js +2 -0
  667. package/src/sources/config.js +435 -0
  668. package/src/storage.js +153 -0
  669. package/src/table/table-geo.js +2344 -0
  670. package/src/table/table-lineage.js +808 -0
  671. package/src/table/table-quality.js +355 -0
  672. package/src/table/table-schema.js +392 -0
  673. package/src/table/table-sql.js +1650 -0
  674. package/src/table/table-stats.js +480 -0
  675. package/src/table/table.js +2102 -0
  676. package/src/tensor/tensor.js +1153 -0
  677. package/src/terminal/hub.js +715 -0
  678. package/src/terminal/screen.js +516 -0
  679. package/src/tests/capture.js +88 -0
  680. package/src/tests/compare.js +480 -0
  681. package/src/tests/dataset.js +170 -0
  682. package/src/tests/evaluate.js +286 -0
  683. package/src/tests/from-runs.js +99 -0
  684. package/src/tests/judge.js +134 -0
  685. package/src/tests/matchers.js +263 -0
  686. package/src/tests/matrix-spec.js +87 -0
  687. package/src/tests/matrix.js +397 -0
  688. package/src/tests/metrics.js +369 -0
  689. package/src/tests/no-value.js +42 -0
  690. package/src/tests/pane-check.js +45 -0
  691. package/src/tests/report.js +124 -0
  692. package/src/tests/reporters.js +140 -0
  693. package/src/tests/run.js +155 -0
  694. package/src/tilemap/tilemap.js +1122 -0
  695. package/src/units/units.js +3 -0
  696. package/src/util/bytes-text.js +21 -0
  697. package/src/util/num.js +10 -0
  698. package/src/util/regexp.js +2 -0
  699. package/src/util/text.js +38 -0
  700. package/src/verdict/engine.js +154 -0
  701. package/src/vm/guest-wsh.js +108 -0
  702. package/src/vm/hub.js +457 -0
  703. package/src/vm/image-files.js +4 -0
  704. package/src/vm/image.js +33 -0
  705. package/src/vm/image.lock.json +13 -0
  706. package/src/vm/link.js +266 -0
  707. package/src/vm/mount.js +212 -0
  708. package/src/vm/net.js +85 -0
  709. package/src/vm/pipe-ws.js +187 -0
  710. package/src/vm/v86-loader.js +11 -0
  711. package/src/webmcp/args.js +212 -0
  712. package/src/webmcp/hidden.js +218 -0
  713. package/src/webmcp/text.js +250 -0
  714. package/src/webmcp/tools/bookmark-tools.js +106 -0
  715. package/src/webmcp/tools/breakpoint-tools.js +48 -0
  716. package/src/webmcp/tools/canvases.js +208 -0
  717. package/src/webmcp/tools/context-tools.js +84 -0
  718. package/src/webmcp/tools/core.js +170 -0
  719. package/src/webmcp/tools/devices.js +41 -0
  720. package/src/webmcp/tools/edit.js +357 -0
  721. package/src/webmcp/tools/event-tools.js +145 -0
  722. package/src/webmcp/tools/image-tools.js +173 -0
  723. package/src/webmcp/tools/ink-tools.js +247 -0
  724. package/src/webmcp/tools/input-log-tools.js +163 -0
  725. package/src/webmcp/tools/live.js +166 -0
  726. package/src/webmcp/tools/machine-tools.js +74 -0
  727. package/src/webmcp/tools/media.js +161 -0
  728. package/src/webmcp/tools/midi-tools.js +32 -0
  729. package/src/webmcp/tools/preset-tools.js +184 -0
  730. package/src/webmcp/tools/quick-add-tools.js +95 -0
  731. package/src/webmcp/tools/reshape.js +152 -0
  732. package/src/webmcp/tools/run-tools.js +309 -0
  733. package/src/webmcp/tools/runs.js +101 -0
  734. package/src/webmcp/tools/scaffold-tools.js +161 -0
  735. package/src/webmcp/tools/serial-tools.js +36 -0
  736. package/src/webmcp/tools/shared.js +338 -0
  737. package/src/webmcp/tools/subgraphs.js +360 -0
  738. package/src/webmcp/tools/tests.js +170 -0
  739. package/src/webmcp/tools/traffic-tools.js +70 -0
  740. package/src/webmcp/tools/transport-tools.js +65 -0
  741. package/src/webmcp/tools/version-tools.js +126 -0
  742. package/src/webmcp/tools/versions.js +11 -0
  743. package/src/webmcp/tools/wire-tools.js +90 -0
  744. package/src/webmcp/tools/workspace-tools.js +93 -0
  745. package/src/webmcp/tools.js +1323 -0
  746. package/src/wsh/connect.js +347 -0
  747. package/src/wsh/demo-host.js +361 -0
  748. package/src/wsh/e2e.js +27 -0
  749. package/src/wsh/keys.js +154 -0
  750. package/src/wsh/known-hosts.js +39 -0
  751. package/src/wsh/private-key.js +95 -0
  752. package/src/wsh/reverse.js +34 -0
  753. package/src/wsh/settings.js +118 -0
  754. package/src/wsh/transfer.js +62 -0
  755. package/src/wsh/vendor.js +5 -0
  756. package/src/x402/challenge.js +171 -0
  757. package/src/x402/demo-server.js +127 -0
  758. package/src/x402/pay.js +125 -0
  759. package/src/x402/retry.js +95 -0
  760. package/src/x402/store.js +76 -0
@@ -0,0 +1,3417 @@
1
+ // clsh: a clean-room shell language over a virtual folder (CLW-SH-01, CLW-SH-02, CLW-SH-03; docs/guide/settings-and-storage.md "Shell pane"). It is written from clawser's DOCUMENTED behaviour (its CLI guide:
2
+ // pipes, redirects, `&&`/`||`/`;`, quoting, globs, about 60 builtins, `jq`, `snapshot`, `clawser session`), never from its source. It is pure and self-contained (it imports nothing,
3
+ // so it can be a sandbox module and the page can import the very same file), and it holds NO file system, network or clock of its own: `run()` is handed
4
+ // fs { list(path), read(path) -> Uint8Array, write(path, bytes), mkdir(path), remove(path, recursive), stat(path), exists(path) }, paths absolute inside ONE folder ("/" is its top)
5
+ // fetch (url, init) -> Response, the network policy's fetch for the pane (or none: `curl` then says there is no network)
6
+ // In mallory both are the page broker's calls (src/clsh/worker-glue is in src/runtime/worker/98-shell.js): the shell can touch only what the person granted, and nothing runs a program.
7
+ // There is no `exec`, no `eval`, no `new Function` here: a command is a builtin of this file or "command not found".
8
+ export const VERSION = "0.1.0";
9
+
10
+ export const LIMITS = Object.freeze({ line: 8192, steps: 20000, outBytes: 262144, ms: 8000, fileBytes: 4 * 1024 * 1024, vars: 200, varBytes: 65536, glob: 500, loop: 1000, depth: 8, history: 200, sleepMs: 3000, netBytes: 1024 * 1024, find: 2000, snapshotEntries: 500, snapshotBytes: 4 * 1024 * 1024, funcDepth: 64, funcs: 50, jobs: 16, heredocs: 8, brace: 1000, braceDepth: 20 });
11
+
12
+ const enc = new TextEncoder();
13
+ const dec = new TextDecoder("utf-8");
14
+
15
+ /** A limit was hit: the whole run stops, with this sentence. */
16
+ class Stop extends Error {}
17
+ class Exit extends Error {
18
+ constructor(code) {
19
+ super("exit");
20
+ this.code = code;
21
+ }
22
+ }
23
+ /** `return` out of a function (or a sourced file) with this code. */
24
+ class Return extends Error {
25
+ constructor(code) {
26
+ super("return");
27
+ this.code = code;
28
+ }
29
+ }
30
+ /** A background job was told to stop (`kill %n`). */
31
+ class Killed extends Error {}
32
+ /** Source that only stops too soon (an open quote or block, a trailing `|`, an unfinished here-document): more text would finish it. */
33
+ class Incomplete extends SyntaxError {}
34
+
35
+ // ── names and paths (the files pane's rules, mirrored; a test keeps them equal) ─────────────────────────
36
+
37
+ const EXECUTABLE_EXT = new Set(["exe", "dll", "msi", "bat", "cmd", "com", "scr", "pif", "ps1", "vbs", "vbe", "wsf", "lnk", "jar", "apk", "app", "dmg", "pkg", "deb", "rpm", "appimage", "sh", "bash", "command", "msix", "cpl", "reg", "hta"]);
38
+ const extOf = (name) => {
39
+ const i = String(name).lastIndexOf(".");
40
+ return i > 0 ? String(name).slice(i + 1).toLowerCase() : "";
41
+ };
42
+ export const executableName = (name) => (EXECUTABLE_EXT.has(extOf(name)) ? `.${extOf(name)} files are programs; this folder does not store them` : "");
43
+ export function executableBytes(head) {
44
+ const b = head instanceof Uint8Array ? head : new Uint8Array(0);
45
+ const is = (...x) => b.length >= x.length && x.every((v, i) => b[i] === v);
46
+ if (is(0x4d, 0x5a)) return "a Windows program (MZ)";
47
+ if (is(0x7f, 0x45, 0x4c, 0x46)) return "a Linux program (ELF)";
48
+ if (is(0xcf, 0xfa, 0xed, 0xfe) || is(0xce, 0xfa, 0xed, 0xfe) || is(0xfe, 0xed, 0xfa, 0xce) || is(0xfe, 0xed, 0xfa, 0xcf) || is(0xca, 0xfe, 0xba, 0xbe)) return "a macOS program (Mach-O)";
49
+ if (is(0x23, 0x21)) return "a script that starts with #!";
50
+ return "";
51
+ }
52
+ /** Why a name cannot be made (one segment), or "". */
53
+ export function nameProblem(name) {
54
+ if (typeof name !== "string" || name === "") return "a name is needed";
55
+ if (name.length > 120) return "a name is at most 120 characters";
56
+ if (/[\\/]/.test(name) || /%(2e|2f|5c)/i.test(name)) return "a name has no slashes";
57
+ if (/^\.+$/.test(name)) return "a name can't be only dots";
58
+ if (/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁠]/.test(name)) return "a name can't hold control or invisible characters";
59
+ if (name.includes(":")) return "a name can't hold a colon";
60
+ if (/[. ]$/.test(name) || /^ /.test(name)) return "a name can't start with a space or end in a dot or space";
61
+ return executableName(name);
62
+ }
63
+ /** `path` resolved against `cwd`: absolute, no `.` or `..` (a `..` at the top stays at the top: nothing is above the folder). */
64
+ export function resolvePath(cwd, path) {
65
+ const parts = [];
66
+ for (const part of `${String(path).startsWith("/") ? "" : `${cwd}/`}${path}`.split("/")) {
67
+ if (part === "" || part === ".") continue;
68
+ if (part === "..") parts.pop();
69
+ else parts.push(part);
70
+ }
71
+ return `/${parts.join("/")}`;
72
+ }
73
+ const baseOf = (p) => p.slice(p.lastIndexOf("/") + 1);
74
+ const dirOf = (p) => {
75
+ const i = p.lastIndexOf("/");
76
+ return i <= 0 ? "/" : p.slice(0, i);
77
+ };
78
+ const joinP = (dir, name) => (dir === "/" ? `/${name}` : `${dir}/${name}`);
79
+
80
+ // ── lexer ─────────────────────────────────────────────────────────────────────────────────────
81
+
82
+ const isSpace = (c) => c === " " || c === "\t" || c === "\r";
83
+ const OPCHARS = "|&;<>";
84
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
85
+ /** A function's name: a variable's rule, and also `-` and `.` (a person types `my-fn`). */
86
+ const FNAME = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
87
+
88
+ /** Read a balanced `(...)` starting after its opening paren; returns [text, indexAfterClose]. */
89
+ function balanced(src, i, open = "(", close = ")") {
90
+ let depth = 1;
91
+ let j = i;
92
+ while (j < src.length) {
93
+ const c = src[j];
94
+ if (c === "\\") j += 2;
95
+ else if (c === "'") j = src.indexOf("'", j + 1) < 0 ? src.length : src.indexOf("'", j + 1) + 1;
96
+ else if (c === '"') {
97
+ j++;
98
+ while (j < src.length && src[j] !== '"') j += src[j] === "\\" ? 2 : 1;
99
+ j++;
100
+ } else {
101
+ if (c === open) depth++;
102
+ else if (c === close && --depth === 0) return [src.slice(i, j), j + 1];
103
+ j++;
104
+ }
105
+ }
106
+ throw new Incomplete(`unclosed ${open}`);
107
+ }
108
+
109
+ /** One `$...` at src[i], pushed onto `segs` as a segment; returns the index after it. `q`: inside double quotes. */
110
+ function readDollar(src, i, q, segs) {
111
+ const n = src.length;
112
+ const c = src[i + 1];
113
+ if (c === "(" && src[i + 2] === "(") {
114
+ const [text, end] = balanced(src, i + 3);
115
+ if (src[end] !== ")") throw new Incomplete("unclosed $((");
116
+ segs.push({ k: "arith", src: text, q });
117
+ return end + 1;
118
+ }
119
+ if (c === "(") {
120
+ const [text, end] = balanced(src, i + 2);
121
+ segs.push({ k: "cmd", src: text, q });
122
+ return end;
123
+ }
124
+ if (c === "{") {
125
+ const end = src.indexOf("}", i + 2);
126
+ if (end < 0) throw new Incomplete("unclosed ${");
127
+ const body = src.slice(i + 2, end);
128
+ const m = /^(#?)([A-Za-z_][A-Za-z0-9_]*|\?|[0-9]+|[#@*!])(?:(:?[-+])(.*))?$/s.exec(body);
129
+ if (!m) throw new SyntaxError(`bad substitution: \${${body.slice(0, 20)}}`);
130
+ segs.push({ k: "var", name: m[2], len: m[1] === "#", mod: m[3] ?? "", arg: m[4] ?? "", q });
131
+ return end + 1;
132
+ }
133
+ if (c !== undefined && (/[A-Za-z_]/.test(c) || /[?0-9#@*!]/.test(c))) {
134
+ let j = i + 1;
135
+ if (/[?0-9#@*!]/.test(c)) j++; // a one-character name: $1 then 0 for $10, as in sh
136
+ else while (j < n && /[A-Za-z0-9_]/.test(src[j])) j++;
137
+ segs.push({ k: "var", name: src.slice(i + 1, j), len: false, mod: "", arg: "", q });
138
+ return j;
139
+ }
140
+ segs.push({ k: "lit", s: "$", q: true });
141
+ return i + 1;
142
+ }
143
+
144
+ /** The segments of an unquoted here-document's text: `$`, `$(...)`, `$((...))` and backticks expand; `\$ \` \\` and a backslash-newline are escapes; everything else is text. */
145
+ function heredocSegs(body) {
146
+ const segs = [];
147
+ let lit = "";
148
+ const flush = () => {
149
+ if (lit) segs.push({ k: "lit", s: lit, q: true });
150
+ lit = "";
151
+ };
152
+ let i = 0;
153
+ while (i < body.length) {
154
+ const d = body[i];
155
+ if (d === "\\" && i + 1 < body.length && "$`\\\n".includes(body[i + 1])) {
156
+ if (body[i + 1] !== "\n") lit += body[i + 1];
157
+ i += 2;
158
+ } else if (d === "$") {
159
+ flush();
160
+ i = readDollar(body, i, true, segs);
161
+ } else if (d === "`") {
162
+ const end = body.indexOf("`", i + 1);
163
+ if (end < 0) throw new Incomplete("unclosed `");
164
+ flush();
165
+ segs.push({ k: "cmd", src: body.slice(i + 1, end), q: true });
166
+ i = end + 1;
167
+ } else {
168
+ lit += d;
169
+ i++;
170
+ }
171
+ }
172
+ flush();
173
+ return segs;
174
+ }
175
+
176
+ /** The bodies of the here-documents opened on the line just ended, read from `from`; fills their words and returns the index after the last delimiter line. */
177
+ function readHeredocBodies(src, from, pending) {
178
+ let i = from;
179
+ for (const tok of pending.splice(0)) {
180
+ const { delim, quoted, strip } = tok.heredoc;
181
+ const lines = [];
182
+ let found = false;
183
+ while (i < src.length) {
184
+ const nl = src.indexOf("\n", i);
185
+ const raw = src.slice(i, nl < 0 ? src.length : nl).replace(/\r$/, "");
186
+ i = nl < 0 ? src.length : nl + 1;
187
+ if ((strip ? raw.replace(/^\t+/, "") : raw) === delim) {
188
+ found = true;
189
+ break;
190
+ }
191
+ lines.push(strip ? raw.replace(/^\t+/, "") : raw);
192
+ }
193
+ if (!found) throw new Incomplete(`here-document delimited by ${delim} is not finished`);
194
+ const body = lines.length ? `${lines.join("\n")}\n` : "";
195
+ tok.segs = quoted ? [{ k: "lit", s: body, q: true, ...(body === "" ? { empty: true } : {}) }] : heredocSegs(body);
196
+ delete tok.heredoc;
197
+ }
198
+ return i;
199
+ }
200
+
201
+ /** Tokens: { t: "w", segs } words and { t: "op", v } operators, each with its source span (p, e). A word is segments: lit (s, q: quoted), var, cmd, arith. */
202
+ export function lex(src) {
203
+ if (src.length > LIMITS.line) throw new SyntaxError(`a line is at most ${LIMITS.line} characters`);
204
+ const out = [];
205
+ const pending = []; // here-document words whose bodies follow the line's end
206
+ let i = 0;
207
+ const n = src.length;
208
+ const op = (v, p, e) => out.push({ t: "op", v, p, e });
209
+ while (i < n) {
210
+ const c = src[i];
211
+ if (isSpace(c)) {
212
+ i++;
213
+ continue;
214
+ }
215
+ if (c === "\\" && src[i + 1] === "\n") {
216
+ i += 2;
217
+ continue;
218
+ }
219
+ if (c === "\n") {
220
+ op("\n", i, i + 1);
221
+ i++;
222
+ if (pending.length) i = readHeredocBodies(src, i, pending);
223
+ continue;
224
+ }
225
+ if (c === "#") {
226
+ while (i < n && src[i] !== "\n") i++;
227
+ continue;
228
+ }
229
+ // operators (a digit before > is a file descriptor)
230
+ const fd = /^([12])(>>|>&1|>)/.exec(src.slice(i, i + 4));
231
+ if (fd && !(i > 0 && !isSpace(src[i - 1]) && !OPCHARS.includes(src[i - 1]) && src[i - 1] !== "\n")) {
232
+ op(`${fd[1]}${fd[2]}`, i, i + fd[0].length);
233
+ i += fd[0].length;
234
+ continue;
235
+ }
236
+ if (c === "<" && src[i + 1] === "<" && src[i + 2] === "<") {
237
+ op("<<<", i, i + 3);
238
+ i += 3;
239
+ continue;
240
+ }
241
+ if (c === "<" && src[i + 1] === "<") {
242
+ // a here-document: the delimiter word now, the body after this line's end
243
+ let j = i + 2;
244
+ const strip = src[j] === "-";
245
+ if (strip) j++;
246
+ while (j < n && (src[j] === " " || src[j] === "\t")) j++;
247
+ const start = j;
248
+ let delim = "";
249
+ let quoted = false;
250
+ while (j < n && !isSpace(src[j]) && src[j] !== "\n" && !OPCHARS.includes(src[j])) {
251
+ const d = src[j];
252
+ if (d === "'" || d === '"') {
253
+ const end = src.indexOf(d, j + 1);
254
+ if (end < 0) throw new Incomplete(`unclosed ${d}`);
255
+ delim += src.slice(j + 1, end);
256
+ j = end + 1;
257
+ quoted = true;
258
+ } else if (d === "\\") {
259
+ if (j + 1 < n) delim += src[j + 1];
260
+ j += 2;
261
+ quoted = true;
262
+ } else {
263
+ delim += d;
264
+ j++;
265
+ }
266
+ }
267
+ if (j === start) throw new SyntaxError("<<: a word that ends the here-document is needed");
268
+ if (pending.length >= LIMITS.heredocs) throw new SyntaxError(`at most ${LIMITS.heredocs} here-documents in one go`);
269
+ op("<<", i, j);
270
+ const word = { t: "w", segs: [], p: start, e: j, heredoc: { delim, quoted, strip } };
271
+ out.push(word);
272
+ pending.push(word);
273
+ i = j;
274
+ continue;
275
+ }
276
+ if (OPCHARS.includes(c)) {
277
+ const two = src.slice(i, i + 2);
278
+ if (two === "||" || two === "&&" || two === ">>" || two === "&>") {
279
+ op(two, i, i + 2);
280
+ i += 2;
281
+ } else {
282
+ op(c, i, i + 1);
283
+ i++;
284
+ }
285
+ continue;
286
+ }
287
+ const segs = [];
288
+ const wordStart = i;
289
+ const lit = (s, q) => {
290
+ const last = segs[segs.length - 1];
291
+ if (last && last.k === "lit" && last.q === q) last.s += s;
292
+ else segs.push({ k: "lit", s, q });
293
+ };
294
+ while (i < n && !isSpace(src[i]) && src[i] !== "\n" && !OPCHARS.includes(src[i])) {
295
+ const d = src[i];
296
+ if (d === "\\") {
297
+ if (i + 1 >= n) {
298
+ i++;
299
+ continue;
300
+ }
301
+ if (src[i + 1] === "\n") i += 2;
302
+ else {
303
+ lit(src[i + 1], true);
304
+ i += 2;
305
+ }
306
+ } else if (d === "'") {
307
+ const end = src.indexOf("'", i + 1);
308
+ if (end < 0) throw new Incomplete("unclosed '");
309
+ segs.push({ k: "lit", s: src.slice(i + 1, end), q: true });
310
+ i = end + 1;
311
+ if (segs.at(-1).s === "") segs.at(-1).empty = true;
312
+ } else if (d === '"') {
313
+ i++;
314
+ const before = segs.length;
315
+ while (i < n && src[i] !== '"') {
316
+ if (src[i] === "\\" && i + 1 < n && '$`"\\\n'.includes(src[i + 1])) {
317
+ if (src[i + 1] !== "\n") lit(src[i + 1], true);
318
+ i += 2;
319
+ } else if (src[i] === "$") i = readDollar(src, i, true, segs);
320
+ else if (src[i] === "`") {
321
+ const end = src.indexOf("`", i + 1);
322
+ if (end < 0) throw new Incomplete("unclosed `");
323
+ segs.push({ k: "cmd", src: src.slice(i + 1, end), q: true });
324
+ i = end + 1;
325
+ } else {
326
+ lit(src[i], true);
327
+ i++;
328
+ }
329
+ }
330
+ if (i >= n) throw new Incomplete('unclosed "');
331
+ i++;
332
+ if (segs.length === before) segs.push({ k: "lit", s: "", q: true, empty: true });
333
+ } else if (d === "$") i = readDollar(src, i, false, segs);
334
+ else if (d === "`") {
335
+ const end = src.indexOf("`", i + 1);
336
+ if (end < 0) throw new Incomplete("unclosed `");
337
+ segs.push({ k: "cmd", src: src.slice(i + 1, end), q: false });
338
+ i = end + 1;
339
+ } else {
340
+ lit(d, false);
341
+ i++;
342
+ }
343
+ }
344
+ out.push({ t: "w", segs, p: wordStart, e: i });
345
+ }
346
+ if (pending.length) throw new Incomplete(`here-document delimited by ${pending[0].heredoc.delim} is not finished`);
347
+ return out;
348
+ }
349
+
350
+ // ── parser ────────────────────────────────────────────────────────────────────────────────────
351
+
352
+ const KEYWORDS = new Set(["if", "then", "elif", "else", "fi", "for", "in", "do", "done", "while", "until", "!", "{", "}"]);
353
+ const REDIR_OPS = new Set(["<", ">", ">>", "1>", "1>>", "2>", "2>>", "&>", "2>&1", "<<", "<<<"]);
354
+ const plainWord = (tok) => (tok?.t === "w" && tok.segs.length === 1 && tok.segs[0].k === "lit" && !tok.segs[0].q ? tok.segs[0].s : null);
355
+ const kwOf = (tok) => {
356
+ const w = plainWord(tok);
357
+ return w !== null && KEYWORDS.has(w) ? w : null;
358
+ };
359
+
360
+ /** Source text -> AST. Throws SyntaxError with a sentence (an `Incomplete` one when the text only stops too soon: a person's next line would finish it). */
361
+ export function parse(src) {
362
+ const toks = lex(src);
363
+ let i = 0;
364
+ // a mistake at the very end is a wait for more text; one in the middle is a mistake
365
+ const fail = (message) => (i >= toks.length ? new Incomplete(message) : new SyntaxError(message));
366
+ const peek = () => toks[i];
367
+ const isOp = (v) => peek()?.t === "op" && peek().v === v;
368
+ const skipNl = () => {
369
+ while (isOp("\n")) i++;
370
+ };
371
+ const skipSeps = () => {
372
+ while (isOp("\n") || isOp(";")) i++;
373
+ };
374
+ const expectKw = (k) => {
375
+ skipSeps();
376
+ if (kwOf(peek()) !== k) throw fail(`expected "${k}"`);
377
+ i++;
378
+ };
379
+ function parseList(stops) {
380
+ const items = [];
381
+ skipSeps();
382
+ while (peek() && !stops.includes(kwOf(peek()))) {
383
+ const first = peek();
384
+ let item = parseAndOr();
385
+ let bg = false;
386
+ if (isOp("&")) {
387
+ // `cmd &`: a job, run cooperatively beside the lines that follow
388
+ item = { type: "bg", body: item, src: src.slice(first.p, toks[i - 1].e) };
389
+ i++;
390
+ bg = true;
391
+ if (isOp(";")) throw new SyntaxError('unexpected ";"');
392
+ }
393
+ items.push(item);
394
+ if (!bg && peek() && !isOp("\n") && !isOp(";") && !stops.includes(kwOf(peek()))) throw new SyntaxError(`unexpected ${peek().t === "op" ? `"${peek().v}"` : "word"}`);
395
+ skipSeps();
396
+ }
397
+ return { type: "list", items };
398
+ }
399
+ function parseAndOr() {
400
+ const first = parsePipeline();
401
+ const rest = [];
402
+ while (isOp("&&") || isOp("||")) {
403
+ const op = toks[i++].v;
404
+ skipNl();
405
+ rest.push([op, parsePipeline()]);
406
+ }
407
+ return { type: "andor", first, rest };
408
+ }
409
+ function parsePipeline() {
410
+ let neg = false;
411
+ if (plainWord(peek()) === "!") {
412
+ i++;
413
+ neg = true;
414
+ }
415
+ const cmds = [parseCommand()];
416
+ while (isOp("|")) {
417
+ i++;
418
+ skipNl();
419
+ cmds.push(parseCommand());
420
+ }
421
+ return { type: "pipe", neg, cmds };
422
+ }
423
+ /** One redirect at the cursor (the operator and its file or word), or null. */
424
+ function readRedir() {
425
+ const t = peek();
426
+ if (t?.t !== "op" || !REDIR_OPS.has(t.v)) return null;
427
+ i++;
428
+ if (t.v === "2>&1") return { op: "2>&1" };
429
+ const target = peek();
430
+ if (target?.t !== "w") throw fail(`${t.v}: a file name is needed`);
431
+ i++;
432
+ return { op: t.v, target };
433
+ }
434
+ /** Redirects after a compound command (`done < file`, `} > out`, `fi <<EOF`). */
435
+ function withRedirs(node) {
436
+ const redirs = [];
437
+ for (let r = readRedir(); r; r = readRedir()) redirs.push(r);
438
+ if (redirs.length) node.redirs = redirs;
439
+ return node;
440
+ }
441
+ /** `name() body`, `name () body` and `function name [()] body`: a function definition, or null when the cursor is not at one. */
442
+ function parseFunction() {
443
+ const w = plainWord(peek());
444
+ if (w === null) return null;
445
+ let name = null;
446
+ let take = 0;
447
+ if (w === "function") {
448
+ const named = plainWord(toks[i + 1]);
449
+ const bare = named === null ? null : named.replace(/\(\)$/, "");
450
+ if (bare === null || !FNAME.test(bare)) throw fail("function: a name is needed");
451
+ name = bare;
452
+ take = named.endsWith("()") ? 2 : plainWord(toks[i + 2]) === "()" ? 3 : 2;
453
+ } else {
454
+ const m = /^([A-Za-z_][A-Za-z0-9_.-]*)\(\)$/.exec(w);
455
+ if (m) (name = m[1]), (take = 1);
456
+ else if (FNAME.test(w) && plainWord(toks[i + 1]) === "()") (name = w), (take = 2);
457
+ }
458
+ if (name === null) return null;
459
+ i += take;
460
+ skipNl();
461
+ const head = peek();
462
+ if (!head) throw fail("function: a body is needed");
463
+ if (!["{", "if", "for", "while", "until"].includes(kwOf(head))) throw new SyntaxError(`function ${name}: the body is a { group }, an if, a for or a while`);
464
+ const body = parseCommand();
465
+ return { type: "funcdef", name, body, src: `${name}() ${src.slice(head.p, toks[i - 1].e)}` };
466
+ }
467
+ function parseCommand() {
468
+ const def = parseFunction();
469
+ if (def) return def;
470
+ const k = kwOf(peek());
471
+ if (k === "{") {
472
+ i++;
473
+ const body = parseList(["}"]);
474
+ if (!body.items.length && peek()) throw new SyntaxError('unexpected "}"'); // `{ ; }` has no command
475
+ expectKw("}");
476
+ return withRedirs({ type: "group", body });
477
+ }
478
+ if (k === "if") {
479
+ i++;
480
+ const branches = [];
481
+ let other = null;
482
+ let cond = parseList(["then"]);
483
+ expectKw("then");
484
+ let body = parseList(["elif", "else", "fi"]);
485
+ branches.push({ cond, body });
486
+ for (;;) {
487
+ const kk = kwOf(peek());
488
+ if (kk === "elif") {
489
+ i++;
490
+ cond = parseList(["then"]);
491
+ expectKw("then");
492
+ body = parseList(["elif", "else", "fi"]);
493
+ branches.push({ cond, body });
494
+ } else if (kk === "else") {
495
+ i++;
496
+ other = parseList(["fi"]);
497
+ } else break;
498
+ }
499
+ expectKw("fi");
500
+ return withRedirs({ type: "if", branches, other });
501
+ }
502
+ if (k === "for") {
503
+ i++;
504
+ const nameTok = plainWord(peek());
505
+ if (nameTok === null || !NAME.test(nameTok)) throw fail("for: a variable name");
506
+ i++;
507
+ let words = null;
508
+ skipNl();
509
+ if (kwOf(peek()) === "in") {
510
+ i++;
511
+ words = [];
512
+ while (peek()?.t === "w" && kwOf(peek()) !== "do") words.push(toks[i++]);
513
+ }
514
+ expectKw("do");
515
+ const body = parseList(["done"]);
516
+ expectKw("done");
517
+ return withRedirs({ type: "for", name: nameTok, words, body });
518
+ }
519
+ if (k === "while" || k === "until") {
520
+ i++;
521
+ const cond = parseList(["do"]);
522
+ expectKw("do");
523
+ const body = parseList(["done"]);
524
+ expectKw("done");
525
+ return withRedirs({ type: "while", until: k === "until", cond, body });
526
+ }
527
+ if (k && k !== "!") throw fail(`unexpected "${k}"`);
528
+ return parseSimple();
529
+ }
530
+ function parseSimple() {
531
+ const assigns = [];
532
+ const words = [];
533
+ const redirs = [];
534
+ while (peek()) {
535
+ const t = peek();
536
+ if (t.t === "op") {
537
+ if (["|", "||", "&&", ";", "\n", "&"].includes(t.v)) break;
538
+ const r = readRedir();
539
+ if (!r) break;
540
+ redirs.push(r);
541
+ continue;
542
+ }
543
+ if (words.length === 0 && kwOf(t) && !["!"].includes(kwOf(t)) && assigns.length === 0 && ["then", "elif", "else", "fi", "do", "done", "in", "}"].includes(kwOf(t))) break;
544
+ const first = t.segs[0];
545
+ if (words.length === 0 && first?.k === "lit" && !first.q) {
546
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=/.exec(first.s);
547
+ if (m) {
548
+ const segs = [{ ...first, s: first.s.slice(m[0].length) }, ...t.segs.slice(1)].filter((s) => s.k !== "lit" || s.s !== "" || s.empty);
549
+ assigns.push({ name: m[1], word: { t: "w", segs } });
550
+ i++;
551
+ continue;
552
+ }
553
+ }
554
+ words.push(t);
555
+ i++;
556
+ }
557
+ if (!words.length && !assigns.length && !redirs.length) throw fail(peek() ? `unexpected "${peek().v ?? "word"}"` : "a command is needed");
558
+ return { type: "cmd", assigns, words, redirs };
559
+ }
560
+ const tree = parseList([]);
561
+ if (i < toks.length) throw new SyntaxError(`unexpected "${kwOf(toks[i]) ?? toks[i].v ?? "word"}"`);
562
+ return tree;
563
+ }
564
+
565
+ /** Whether `src` only stops too soon (an open quote, block, `|`, `&&` or here-document): the next line a person types would finish it. A real mistake is not incomplete. */
566
+ export function incomplete(src) {
567
+ const text = String(src ?? "");
568
+ if (/(?:^|[^\\])(?:\\\\)*\\$/.test(text)) return true; // a trailing backslash continues the line
569
+ try {
570
+ parse(text);
571
+ return false;
572
+ } catch (error) {
573
+ return error instanceof Incomplete;
574
+ }
575
+ }
576
+
577
+ // ── what a line would do (before it runs): the machine tool asks the person before a write ─────────────────
578
+
579
+ const WRITERS = new Set(["mkdir", "rm", "rmdir", "cp", "mv", "touch", "tee"]);
580
+ const NETWORKERS = new Set(["curl", "wget"]);
581
+
582
+ const wordText = (tok) => (tok.segs.every((s) => s.k === "lit") ? tok.segs.map((s) => s.s).join("") : null);
583
+
584
+ /**
585
+ * What a line can do: `{ ok, writes, network, reasons }`. It is judged without running anything and leans to "writes": a command it can't read
586
+ * (a name from a variable), a redirect, a builtin that changes files, `curl` with a body or a method other than GET/HEAD, `sed -i`, `clawser session`
587
+ * changes or `source` of a file all count. A syntax error is `{ ok: false, error }`.
588
+ */
589
+ export function analyze(line) {
590
+ let tree;
591
+ try {
592
+ tree = parse(String(line));
593
+ } catch (error) {
594
+ return { ok: false, error: error.message, writes: true, network: false, reasons: [] };
595
+ }
596
+ const reasons = new Set();
597
+ let network = false;
598
+ const walkWord = (tok) => {
599
+ for (const s of tok.segs) if (s.k === "cmd") walk(parse(s.src));
600
+ };
601
+ const redirReasons = (redirs) => {
602
+ for (const r of redirs ?? []) {
603
+ if (r.target) walkWord(r.target);
604
+ if (!["<", "2>&1", "<<", "<<<"].includes(r.op)) reasons.add(`redirects output into a file (${r.op})`);
605
+ }
606
+ };
607
+ const walk = (node) => {
608
+ if (node.type === "list") node.items.forEach(walk);
609
+ else if (node.type === "andor") [node.first, ...node.rest.map((r) => r[1])].forEach(walk);
610
+ else if (node.type === "pipe") node.cmds.forEach(walk);
611
+ else if (node.type === "bg" || node.type === "funcdef" || node.type === "group") {
612
+ walk(node.body);
613
+ redirReasons(node.redirs);
614
+ } else if (node.type === "if") {
615
+ node.branches.forEach((b) => (walk(b.cond), walk(b.body)));
616
+ if (node.other) walk(node.other);
617
+ redirReasons(node.redirs);
618
+ } else if (node.type === "for") {
619
+ node.words?.forEach(walkWord);
620
+ walk(node.body);
621
+ redirReasons(node.redirs);
622
+ } else if (node.type === "while") {
623
+ walk(node.cond);
624
+ walk(node.body);
625
+ redirReasons(node.redirs);
626
+ } else if (node.type === "cmd") {
627
+ node.assigns.forEach((a) => walkWord(a.word));
628
+ node.words.forEach(walkWord);
629
+ redirReasons(node.redirs);
630
+ const texts = node.words.flatMap((tok) => braceWords(tok, LIMITS).map(wordText)); // `{rm,echo} x` is `rm echo x`
631
+ let at = 0;
632
+ if (!texts.length) return;
633
+ if (texts[0] === null) return void reasons.add("runs a command whose name comes from a variable");
634
+ let name = texts[0];
635
+ if (name === "xargs" || name === "command" || name === "time") {
636
+ const rest = texts.slice(1).filter((t) => t === null || !t.startsWith("-"));
637
+ if (rest[0] === undefined || rest[0] === null) return void reasons.add(`${name} runs another command`);
638
+ name = rest[0];
639
+ at = texts.indexOf(rest[0]);
640
+ }
641
+ if (WRITERS.has(name)) reasons.add(`${name} changes files`);
642
+ if (name === "sed" && texts.some((t) => t !== null && /^-[a-z]*i/.test(t))) reasons.add("sed -i changes a file");
643
+ if (name === "source" || name === ".") reasons.add("source runs a file's commands");
644
+ if (name === "alias" && texts.slice(at + 1).some((t) => t === null || t.includes("="))) reasons.add("an alias can hide a command from this check");
645
+ if (name === "clawser" || name === "snapshot") {
646
+ const sub = texts.slice(at + 1).filter((t) => t === null || !t.startsWith("-"));
647
+ const args = name === "clawser" ? (sub[0] === "snapshot" ? sub.slice(1) : null) : sub;
648
+ if (args && (args[0] === null || ["save", "restore", "delete", "clear"].includes(args[0]))) reasons.add("a snapshot changes files");
649
+ }
650
+ if (NETWORKERS.has(name)) {
651
+ network = true;
652
+ const flags = texts.slice(at + 1);
653
+ if (flags.some((t) => t === null)) reasons.add(`${name} with an argument that is not plain text`);
654
+ const sends = (t) => t !== null && (/^--(data|data-raw|data-binary|data-urlencode|form|upload-file|output)$/.test(t) || /^-[A-Za-z]*[dFToO]$/.test(t));
655
+ if (flags.some(sends)) reasons.add(`${name} sends data or writes a file`);
656
+ const m = flags.findIndex((t) => t === "-X" || t === "--request");
657
+ if (m >= 0 && !["GET", "HEAD"].includes(String(flags[m + 1]).toUpperCase())) reasons.add(`${name} makes a ${String(flags[m + 1]).toUpperCase()} request`);
658
+ }
659
+ }
660
+ };
661
+ try {
662
+ walk(tree);
663
+ } catch (error) {
664
+ return { ok: false, error: error.message, writes: true, network, reasons: [] };
665
+ }
666
+ return { ok: true, writes: reasons.size > 0, network, reasons: [...reasons] };
667
+ }
668
+
669
+ // ── the shell's state and its errors ────────────────────────────────────────────────────────────
670
+
671
+ const fsMessage = (error, path) => {
672
+ const name = error?.name;
673
+ if (name === "NotFoundError" || name === "ENOENT") return `${path}: No such file or directory`;
674
+ if (name === "TypeMismatchError") return `${path}: Not the right kind (a file where a folder is needed, or the other way round)`;
675
+ if (name === "EEXIST") return `${path}: File exists`;
676
+ if (name === "NotAllowedError") return `${path}: ${error.message || "not allowed"}`;
677
+ if (name === "QuotaExceededError") return `${path}: ${error.message || "no room"}`;
678
+ return `${path}: ${error?.message ?? String(error)}`;
679
+ };
680
+
681
+ const toText = (bytes) => dec.decode(bytes);
682
+ /** A command's standard input: text with a read position, so `read` in a loop takes one line at a time. */
683
+ const mkIn = (text) => ({ text, pos: 0 });
684
+ const slurp = (io) => {
685
+ if (!io.in) return "";
686
+ const t = io.in.text.slice(io.in.pos);
687
+ io.in.pos = io.in.text.length;
688
+ return t;
689
+ };
690
+ const sizeOf = (s) => enc.encode(s).byteLength;
691
+
692
+ function makeShell({ fs, fetch, sleep, state = {}, wired = {}, mode = "person", now = () => Date.now(), limits = LIMITS, history = [], views = {} }) {
693
+ const vars = new Map(Object.entries(state.vars ?? {}).filter(([k, v]) => NAME.test(k) && typeof v === "string"));
694
+ for (const [k, v] of Object.entries(wired)) if (NAME.test(k)) vars.set(k, String(v).slice(0, limits.varBytes));
695
+ const funcs = new Map();
696
+ if (mode === "person" && state.funcs && typeof state.funcs === "object") {
697
+ // functions kept from earlier lines are source text, parsed again here: a damaged one is dropped, never run
698
+ for (const [name, src] of Object.entries(state.funcs).slice(0, limits.funcs)) {
699
+ if (!FNAME.test(name) || typeof src !== "string" || src.length > limits.line) continue;
700
+ try {
701
+ const tree = parse(src);
702
+ const only = tree.items.length === 1 && tree.items[0].rest.length === 0 && tree.items[0].first.cmds.length === 1 ? tree.items[0].first.cmds[0] : null;
703
+ if (only?.type === "funcdef" && only.name === name) funcs.set(name, { body: only.body, src: only.src });
704
+ } catch {}
705
+ }
706
+ }
707
+ const sh = {
708
+ mode,
709
+ fs,
710
+ fetch,
711
+ sleep: sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),
712
+ vars,
713
+ exported: new Set(state.exported ?? []),
714
+ aliases: new Map(Object.entries(state.aliases ?? {}).filter(([k, v]) => NAME.test(k.replace(/-/g, "_")) && typeof v === "string").slice(0, 100)),
715
+ cwd: typeof state.cwd === "string" && state.cwd.startsWith("/") ? resolvePath("/", state.cwd) : "/",
716
+ last: Number.isInteger(state.last) ? state.last : 0,
717
+ history,
718
+ views: mode === "person" && views && typeof views === "object" ? views : {},
719
+ funcs,
720
+ frames: [], // function calls in progress: { name, args, locals }
721
+ jobs: [], // background jobs of this line
722
+ lastJob: undefined,
723
+ cancel: undefined, // set in a job's subshell: true once `kill` named it
724
+ effects: [],
725
+ chunks: [],
726
+ bytes: 0,
727
+ steps: 0,
728
+ depth: 0,
729
+ started: now(),
730
+ now,
731
+ limits,
732
+ truncated: false,
733
+ };
734
+ sh.abs = (p) => resolvePath(sh.cwd, p);
735
+ return sh;
736
+ }
737
+
738
+ const tick = (sh) => {
739
+ if (sh.cancel?.()) throw new Killed();
740
+ if (++sh.steps > sh.limits.steps) throw new Stop(`stopped: more than ${sh.limits.steps} commands in one line`);
741
+ if (sh.now() - sh.started > sh.limits.ms) throw new Stop(`stopped: this line ran longer than ${sh.limits.ms / 1000} seconds`);
742
+ };
743
+
744
+ function emit(sh, stream, text) {
745
+ if (!text) return;
746
+ const room = sh.limits.outBytes - sh.bytes;
747
+ if (room <= 0) throw new Stop("stopped: more output than can be shown");
748
+ let t = text;
749
+ if (sizeOf(t) > room) {
750
+ t = t.slice(0, Math.max(0, room));
751
+ sh.chunks.push({ s: stream, text: t });
752
+ sh.bytes = sh.limits.outBytes;
753
+ sh.truncated = true;
754
+ throw new Stop("stopped: more output than can be shown");
755
+ }
756
+ sh.bytes += sizeOf(t);
757
+ sh.chunks.push({ s: stream, text: t });
758
+ }
759
+
760
+ // ── expansion ──────────────────────────────────────────────────────────────────────────────────
761
+
762
+ /** `$(cmd)` inside `$((...))` runs first and is replaced by what it printed. */
763
+ async function arithSubstitutions(src, sh) {
764
+ let out = "";
765
+ let i = 0;
766
+ while (i < src.length) {
767
+ const at = src.indexOf("$(", i);
768
+ if (at < 0 || src[at + 2] === "(") {
769
+ if (at < 0) break;
770
+ out += src.slice(i, at + 2);
771
+ i = at + 2;
772
+ continue;
773
+ }
774
+ const [inner, end] = balanced(src, at + 2);
775
+ out += src.slice(i, at) + (await substitute(inner, sh));
776
+ i = end;
777
+ }
778
+ return out + src.slice(i);
779
+ }
780
+
781
+ function evalArith(src, sh) {
782
+ const s = src.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*|[0-9]+|#)\}?/g, (_, n) => String(variable(sh, n) ?? 0));
783
+ let i = 0;
784
+ const ws = () => {
785
+ while (s[i] === " ") i++;
786
+ };
787
+ const atom = () => {
788
+ ws();
789
+ if (s[i] === "(") {
790
+ i++;
791
+ const v = expr();
792
+ ws();
793
+ if (s[i++] !== ")") throw new SyntaxError("arithmetic: missing )");
794
+ return v;
795
+ }
796
+ if (s[i] === "-") return i++, -atom();
797
+ if (s[i] === "+") return i++, atom();
798
+ const m = /^[0-9]+/.exec(s.slice(i));
799
+ if (m) return (i += m[0].length), Number(m[0]);
800
+ const id = /^[A-Za-z_][A-Za-z0-9_]*/.exec(s.slice(i));
801
+ if (id) return (i += id[0].length), Number(sh.vars.get(id[0]) ?? 0) || 0;
802
+ throw new SyntaxError(`arithmetic: unexpected "${s[i] ?? "end"}"`);
803
+ };
804
+ const term = () => {
805
+ let v = atom();
806
+ for (;;) {
807
+ ws();
808
+ const op = s[i];
809
+ if (op !== "*" && op !== "/" && op !== "%") return v;
810
+ i++;
811
+ const r = atom();
812
+ if (op === "*") v *= r;
813
+ else if (r === 0) throw new SyntaxError("arithmetic: division by zero");
814
+ else v = op === "/" ? Math.trunc(v / r) : v % r;
815
+ }
816
+ };
817
+ function expr() {
818
+ let v = term();
819
+ for (;;) {
820
+ ws();
821
+ const op = s[i];
822
+ if (op !== "+" && op !== "-") return v;
823
+ i++;
824
+ const r = term();
825
+ v = op === "+" ? v + r : v - r;
826
+ }
827
+ }
828
+ const v = expr();
829
+ ws();
830
+ if (i < s.length) throw new SyntaxError(`arithmetic: unexpected "${s[i]}"`);
831
+ return String(v);
832
+ }
833
+
834
+ const argsOf = (sh) => sh.frames.at(-1)?.args ?? [];
835
+
836
+ function variable(sh, name) {
837
+ if (name === "?") return String(sh.last);
838
+ if (name === "#") return String(argsOf(sh).length);
839
+ if (name === "!") return sh.lastJob === undefined ? "" : String(sh.lastJob);
840
+ if (name === "@" || name === "*") return argsOf(sh).join(" ");
841
+ if (/^[1-9][0-9]*$/.test(name)) return argsOf(sh)[Number(name) - 1];
842
+ if (name === "PWD") return sh.cwd;
843
+ if (name === "HOME") return sh.vars.get("HOME") ?? "/";
844
+ if (name === "SHELL" || name === "0") return "clsh";
845
+ return sh.vars.get(name);
846
+ }
847
+
848
+ /** A copy of the shell for a substitution or a job: its own variables, functions, call frames and jobs, and the same files, network and limits. */
849
+ function subshell(sh) {
850
+ return {
851
+ ...sh,
852
+ vars: new Map(sh.vars),
853
+ exported: new Set(sh.exported),
854
+ funcs: new Map(sh.funcs),
855
+ frames: sh.frames.map((f) => ({ ...f, args: [...f.args], locals: new Map(f.locals) })),
856
+ jobs: [],
857
+ lastJob: undefined,
858
+ chunks: [],
859
+ effects: [],
860
+ };
861
+ }
862
+
863
+ async function substitute(src, sh) {
864
+ if (sh.depth >= sh.limits.depth) throw new Stop(`stopped: command substitutions nested more than ${sh.limits.depth} deep`);
865
+ const sub = { ...subshell(sh), depth: sh.depth + 1 };
866
+ const holder = { text: "" };
867
+ const io = { in: null, out: (t) => (holder.text += t), err: (t) => emit(sh, "err", t) };
868
+ const tree = parse(src);
869
+ sub.steps = sh.steps;
870
+ try {
871
+ await execList(tree, sub, io);
872
+ await settleJobs(sub, io);
873
+ } catch (error) {
874
+ if (!(error instanceof Return)) throw error; // `return` in a substitution ends only the substitution
875
+ } finally {
876
+ sh.steps = sub.steps;
877
+ }
878
+ return holder.text.replace(/\n+$/, "");
879
+ }
880
+
881
+ // ── brace expansion ────────────────────────────────────────────────────────────────────────────
882
+
883
+ const HELD0 = 0xe000; // private-use characters stand in for the parts of a word that braces must not look into
884
+ const HELD_MAX = 0x1800;
885
+ const SEQ_NUM = /^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/;
886
+ const SEQ_CHR = /^([A-Za-z])\.\.([A-Za-z])(?:\.\.(-?\d+))?$/;
887
+
888
+ const tooMany = (limits) => new Stop(`stopped: a brace pattern made more than ${limits.brace} words`);
889
+
890
+ /** The words a `{a,b}` or `{1..5}` makes from `s` (text with held characters); `[s]` when there is nothing to expand. */
891
+ function expandBraces(s, limits) {
892
+ for (let i = 0; i < s.length; i++) {
893
+ if (s[i] !== "{") continue;
894
+ let level = 0;
895
+ let deepest = 0;
896
+ let close = -1;
897
+ const commas = [];
898
+ for (let j = i; j < s.length; j++) {
899
+ const c = s[j];
900
+ if (c === "{") deepest = Math.max(deepest, ++level);
901
+ else if (c === "}") {
902
+ if (--level === 0) {
903
+ close = j;
904
+ break;
905
+ }
906
+ } else if (c === "," && level === 1) commas.push(j);
907
+ }
908
+ if (close < 0) continue; // never closed: a plain brace
909
+ if (deepest > limits.braceDepth) throw new Stop(`stopped: braces nested more than ${limits.braceDepth} deep`);
910
+ const body = s.slice(i + 1, close);
911
+ let items = null;
912
+ if (commas.length) {
913
+ const cuts = [i, ...commas, close];
914
+ items = cuts.slice(0, -1).map((from, k) => s.slice(from + 1, cuts[k + 1]));
915
+ } else {
916
+ const num = SEQ_NUM.exec(body);
917
+ const chr = num ? null : SEQ_CHR.exec(body);
918
+ const m = num ?? chr;
919
+ if (m && Number(m[3] ?? 1) !== 0) {
920
+ const step = Math.abs(Number(m[3] ?? 1));
921
+ const a = chr ? m[1].charCodeAt(0) : Number(m[1]);
922
+ const b = chr ? m[2].charCodeAt(0) : Number(m[2]);
923
+ const count = Math.floor(Math.abs(b - a) / step) + 1;
924
+ if (count > limits.brace) throw tooMany(limits);
925
+ const pad = num && (/^-?0\d/.test(m[1]) || /^-?0\d/.test(m[2])) ? Math.max(m[1].length, m[2].length) : 0;
926
+ items = Array.from({ length: count }, (_, k) => {
927
+ const v = a + (a <= b ? 1 : -1) * k * step;
928
+ if (chr) return String.fromCharCode(v);
929
+ const digits = String(Math.abs(v)).padStart(v < 0 ? pad - 1 : pad, "0");
930
+ return `${v < 0 ? "-" : ""}${digits}`;
931
+ });
932
+ }
933
+ }
934
+ if (!items) continue; // one alternative is no list: the braces stay
935
+ const pre = s.slice(0, i);
936
+ const post = expandBraces(s.slice(close + 1), limits);
937
+ const out = [];
938
+ for (const item of items) {
939
+ for (const mid of expandBraces(item, limits)) {
940
+ for (const tail of post) {
941
+ out.push(`${pre}${mid}${tail}`);
942
+ if (out.length > limits.brace) throw tooMany(limits);
943
+ }
944
+ }
945
+ }
946
+ return out;
947
+ }
948
+ return [s];
949
+ }
950
+
951
+ /** A word's brace expansion as words: `{a,b}` in its unquoted text. Quoted text, `${...}`, `$(...)` and escaped braces are never looked into. `[tok]` when nothing expands. */
952
+ function braceWords(tok, limits) {
953
+ if (!tok.segs.some((seg) => seg.k === "lit" && !seg.q && seg.s.includes("{"))) return [tok];
954
+ const held = [];
955
+ let text = "";
956
+ for (const seg of tok.segs) {
957
+ if (seg.k === "lit" && !seg.q) {
958
+ if (/[\ue000-\uf8ff]/.test(seg.s)) return [tok];
959
+ text += seg.s;
960
+ } else {
961
+ if (held.length >= HELD_MAX) return [tok];
962
+ held.push(seg);
963
+ text += String.fromCharCode(HELD0 + held.length - 1);
964
+ }
965
+ }
966
+ const made = expandBraces(text, limits);
967
+ if (made.length === 1 && made[0] === text) return [tok];
968
+ return made.map((str) => {
969
+ const segs = [];
970
+ let run = "";
971
+ for (const ch of str) {
972
+ const code = ch.charCodeAt(0);
973
+ if (code >= HELD0 && code < HELD0 + held.length) {
974
+ if (run) segs.push({ k: "lit", s: run, q: false });
975
+ run = "";
976
+ segs.push(held[code - HELD0]);
977
+ } else run += ch;
978
+ }
979
+ if (run) segs.push({ k: "lit", s: run, q: false });
980
+ return { t: "w", segs };
981
+ });
982
+ }
983
+
984
+ /** A word as fields: brace expansion, then variables, substitutions, arithmetic, field splitting and globs. `{ split: false }`: one string, no braces or globs (an assignment, a redirect target). */
985
+ async function expand(tok, sh, { split = true } = {}) {
986
+ if (split) {
987
+ const words = braceWords(tok, sh.limits);
988
+ if (words.length !== 1 || words[0] !== tok) {
989
+ const out = [];
990
+ for (const w of words) out.push(...(await expandWord(w, sh, true)));
991
+ return out;
992
+ }
993
+ }
994
+ return expandWord(tok, sh, split);
995
+ }
996
+
997
+ async function expandWord(tok, sh, split) {
998
+ const fields = [];
999
+ let cur = { s: "", m: "", quoted: false };
1000
+ const push = (s, literal) => {
1001
+ cur.s += s;
1002
+ cur.m += (literal ? "1" : "0").repeat(s.length);
1003
+ };
1004
+ const breakField = () => {
1005
+ if (cur.s !== "" || cur.quoted) fields.push(cur);
1006
+ cur = { s: "", m: "", quoted: false };
1007
+ };
1008
+ let first = true;
1009
+ for (const seg of tok.segs) {
1010
+ if (seg.k === "lit") {
1011
+ let s = seg.s;
1012
+ if (first && !seg.q && s.startsWith("~") && (s.length === 1 || s[1] === "/")) {
1013
+ push(sh.vars.get("HOME") ?? "/", true);
1014
+ s = s.slice(1);
1015
+ }
1016
+ if (seg.q) cur.quoted = true;
1017
+ push(s, seg.q);
1018
+ } else if (seg.k === "var" && seg.name === "@" && seg.q && split && !seg.len && !seg.mod) {
1019
+ // "$@": one field for each argument
1020
+ argsOf(sh).forEach((a, idx) => {
1021
+ if (idx > 0) breakField();
1022
+ cur.quoted = true;
1023
+ push(a, true);
1024
+ });
1025
+ } else {
1026
+ let v;
1027
+ if (seg.k === "var") {
1028
+ const raw = variable(sh, seg.name);
1029
+ if (seg.len) v = String((raw ?? "").length);
1030
+ else if (seg.mod === ":-") v = raw === undefined || raw === "" ? seg.arg : raw;
1031
+ else if (seg.mod === "-") v = raw === undefined ? seg.arg : raw;
1032
+ else if (seg.mod === ":+") v = raw === undefined || raw === "" ? "" : seg.arg;
1033
+ else if (seg.mod === "+") v = raw === undefined ? "" : seg.arg;
1034
+ else v = raw ?? "";
1035
+ } else if (seg.k === "cmd") v = await substitute(seg.src, sh);
1036
+ else v = evalArith(await arithSubstitutions(seg.src, sh), sh);
1037
+ if (seg.q || !split) {
1038
+ if (seg.q) cur.quoted = true;
1039
+ push(v, true);
1040
+ } else {
1041
+ const parts = v.split(/[ \t\n]+/);
1042
+ parts.forEach((p, idx) => {
1043
+ if (idx > 0) breakField();
1044
+ if (p !== "") push(p, false);
1045
+ });
1046
+ }
1047
+ }
1048
+ first = false;
1049
+ }
1050
+ breakField();
1051
+ if (!split) return [fields.map((f) => f.s).join("")];
1052
+ const out = [];
1053
+ for (const f of fields) {
1054
+ const hasGlob = [...f.s].some((ch, i) => "*?[".includes(ch) && f.m[i] === "0");
1055
+ if (!hasGlob) {
1056
+ out.push(f.s);
1057
+ continue;
1058
+ }
1059
+ const hits = await glob(f, sh);
1060
+ if (hits.length) out.push(...hits);
1061
+ else out.push(f.s);
1062
+ }
1063
+ return out;
1064
+ }
1065
+
1066
+ /** A glob segment as a RegExp (the mask says which characters are quoted and so literal). */
1067
+ function segmentRegex(s, m) {
1068
+ let re = "";
1069
+ for (let i = 0; i < s.length; i++) {
1070
+ const c = s[i];
1071
+ const lit = m[i] === "1";
1072
+ if (!lit && c === "*") re += "[^/]*";
1073
+ else if (!lit && c === "?") re += "[^/]";
1074
+ else if (!lit && c === "[") {
1075
+ const end = s.indexOf("]", i + 2);
1076
+ if (end < 0) re += "\\[";
1077
+ else {
1078
+ let body = s.slice(i + 1, end);
1079
+ let neg = false;
1080
+ if (body[0] === "!" || body[0] === "^") (neg = true), (body = body.slice(1));
1081
+ re += `[${neg ? "^" : ""}${body.replace(/[\\\]]/g, "\\$&")}]`;
1082
+ i = end;
1083
+ }
1084
+ } else re += c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1085
+ }
1086
+ return new RegExp(`^${re}$`, "s");
1087
+ }
1088
+
1089
+ async function glob(field, sh) {
1090
+ const absolute = field.s.startsWith("/");
1091
+ const segs = [];
1092
+ let at = 0;
1093
+ for (const part of field.s.split("/")) {
1094
+ segs.push({ s: part, m: field.m.slice(at, at + part.length) });
1095
+ at += part.length + 1;
1096
+ }
1097
+ const wild = (seg) => [...seg.s].some((ch, i) => "*?[".includes(ch) && seg.m[i] === "0");
1098
+ let bases = [{ real: absolute ? "/" : sh.cwd, shown: absolute ? "/" : "" }];
1099
+ for (let idx = 0; idx < segs.length; idx++) {
1100
+ const seg = segs[idx];
1101
+ if (seg.s === "" ) continue;
1102
+ const next = [];
1103
+ if (!wild(seg)) {
1104
+ for (const b of bases) next.push({ real: resolvePath(b.real, seg.s), shown: b.shown === "" ? seg.s : b.shown === "/" ? `/${seg.s}` : `${b.shown}/${seg.s}` });
1105
+ } else {
1106
+ const re = segmentRegex(seg.s, seg.m);
1107
+ const dots = seg.s.startsWith(".");
1108
+ for (const b of bases) {
1109
+ let entries;
1110
+ try {
1111
+ entries = await sh.fs.list(b.real);
1112
+ } catch {
1113
+ continue;
1114
+ }
1115
+ for (const e of entries) {
1116
+ if ((!dots && e.name.startsWith(".")) || !re.test(e.name)) continue;
1117
+ if (idx < segs.length - 1 && e.type !== "dir") continue;
1118
+ next.push({ real: joinP(b.real, e.name), shown: b.shown === "" ? e.name : b.shown === "/" ? `/${e.name}` : `${b.shown}/${e.name}` });
1119
+ if (next.length > sh.limits.glob) throw new Stop(`stopped: a pattern matched more than ${sh.limits.glob} names`);
1120
+ }
1121
+ }
1122
+ }
1123
+ bases = next;
1124
+ if (!bases.length) return [];
1125
+ }
1126
+ const out = [];
1127
+ for (const b of bases) if (await sh.fs.exists(b.real).catch(() => false)) out.push(b.shown);
1128
+ return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1129
+ }
1130
+
1131
+ // ── running the tree ────────────────────────────────────────────────────────────────────────────
1132
+
1133
+ async function execList(node, sh, io) {
1134
+ let code = sh.last;
1135
+ for (const item of node.items) {
1136
+ code = item.type === "bg" ? await startJob(item, sh, io) : await execAndOr(item, sh, io);
1137
+ sh.last = code;
1138
+ }
1139
+ return code;
1140
+ }
1141
+
1142
+ async function execAndOr(node, sh, io) {
1143
+ let code = await execPipe(node.first, sh, io);
1144
+ sh.last = code;
1145
+ for (const [op, next] of node.rest) {
1146
+ if ((op === "&&" && code !== 0) || (op === "||" && code === 0)) continue;
1147
+ code = await execPipe(next, sh, io);
1148
+ sh.last = code;
1149
+ }
1150
+ return code;
1151
+ }
1152
+
1153
+ async function execPipe(node, sh, io) {
1154
+ let input = io.in;
1155
+ let code = 0;
1156
+ for (let i = 0; i < node.cmds.length; i++) {
1157
+ const lastCmd = i === node.cmds.length - 1;
1158
+ let piped = "";
1159
+ const sub = { in: input, out: lastCmd ? io.out : (t) => (piped += t), err: io.err };
1160
+ code = await execCommand(node.cmds[i], sh, sub);
1161
+ sh.last = code;
1162
+ input = mkIn(piped);
1163
+ }
1164
+ return node.neg ? (code === 0 ? 1 : 0) : code;
1165
+ }
1166
+
1167
+ async function execCommand(node, sh, io) {
1168
+ tick(sh);
1169
+ if (node.type === "funcdef") {
1170
+ if (!sh.funcs.has(node.name) && sh.funcs.size >= sh.limits.funcs) throw new Stop(`stopped: more than ${sh.limits.funcs} functions`);
1171
+ sh.funcs.set(node.name, { body: node.body, src: node.src });
1172
+ return 0;
1173
+ }
1174
+ if (node.type === "bg") return startJob(node, sh, io);
1175
+ if (node.type === "cmd") return execSimple(node, sh, io);
1176
+ if (!node.redirs?.length) return execCompound(node, sh, io);
1177
+ const set = await applyRedirs(node.redirs, sh, io);
1178
+ if (set.failed) return 1;
1179
+ let code;
1180
+ try {
1181
+ code = await execCompound(node, sh, set.io);
1182
+ } finally {
1183
+ code = await flushSinks(set.sinks, sh, io, code);
1184
+ }
1185
+ return code;
1186
+ }
1187
+
1188
+ async function execCompound(node, sh, io) {
1189
+ if (node.type === "group") return execList(node.body, sh, io);
1190
+ if (node.type === "if") {
1191
+ for (const b of node.branches) if ((await execList(b.cond, sh, io)) === 0) return execList(b.body, sh, io);
1192
+ return node.other ? execList(node.other, sh, io) : 0;
1193
+ }
1194
+ if (node.type === "for") {
1195
+ const items = node.words ? (await Promise.all(node.words.map((w) => expand(w, sh)))).flat() : [];
1196
+ let code = 0;
1197
+ let n = 0;
1198
+ for (const v of items) {
1199
+ if (++n > sh.limits.loop) throw new Stop(`stopped: a loop ran more than ${sh.limits.loop} times`);
1200
+ sh.vars.set(node.name, v);
1201
+ code = await execList(node.body, sh, io);
1202
+ }
1203
+ return code;
1204
+ }
1205
+ if (node.type === "while") {
1206
+ let code = 0;
1207
+ let n = 0;
1208
+ for (;;) {
1209
+ if (++n > sh.limits.loop) throw new Stop(`stopped: a loop ran more than ${sh.limits.loop} times`);
1210
+ tick(sh);
1211
+ const c = await execList(node.cond, sh, io);
1212
+ if (node.until ? c === 0 : c !== 0) return code;
1213
+ code = await execList(node.body, sh, io);
1214
+ }
1215
+ }
1216
+ throw new Error(`clsh: cannot run a ${node.type}`);
1217
+ }
1218
+
1219
+ // ── functions ──────────────────────────────────────────────────────────────────────────────────
1220
+
1221
+ async function callFunction(name, fn, args, sh, io) {
1222
+ if (sh.frames.length >= sh.limits.funcDepth) throw new Stop(`stopped: functions nested more than ${sh.limits.funcDepth} deep`);
1223
+ const frame = { name, args: [...args], locals: new Map() };
1224
+ sh.frames.push(frame);
1225
+ try {
1226
+ return await execCommand(fn.body, sh, io);
1227
+ } catch (error) {
1228
+ if (error instanceof Return) return error.code;
1229
+ throw error;
1230
+ } finally {
1231
+ sh.frames.pop();
1232
+ for (const [k, v] of frame.locals) v === undefined ? sh.vars.delete(k) : sh.vars.set(k, v); // `local` ends with the call
1233
+ }
1234
+ }
1235
+
1236
+ // ── jobs: `cmd &` runs cooperatively (a promise on the same thread, interleaved at each wait), with no process ──────────
1237
+
1238
+ const jobStatus = (j) => (j.status === "running" ? "Running" : j.status === "killed" ? "Terminated" : j.code === 0 ? "Done" : `Exit ${j.code}`);
1239
+
1240
+ function startJob(node, sh, io) {
1241
+ const running = sh.jobs.filter((j) => j.status === "running").length;
1242
+ if (running >= sh.limits.jobs) {
1243
+ io.err(`clsh: too many background jobs (at most ${sh.limits.jobs} at once)\n`);
1244
+ return 1;
1245
+ }
1246
+ const job = { id: 1 + Math.max(0, ...sh.jobs.map((j) => j.id)), src: node.src, status: "running", code: 0, buf: [], bytes: 0, cancelled: false, kill: () => {} };
1247
+ const stopped = new Promise((_, reject) => (job.kill = () => reject(new Killed())));
1248
+ stopped.catch(() => {});
1249
+ const sub = subshell(sh);
1250
+ sub.cancel = () => job.cancelled;
1251
+ sub.sleep = (ms) => Promise.race([sh.sleep(ms), stopped]);
1252
+ sub.steps = sh.steps;
1253
+ const base = sh.steps;
1254
+ const put = (stream) => (text) => {
1255
+ if (!text) return;
1256
+ const room = sh.limits.outBytes - job.bytes;
1257
+ if (sizeOf(text) > room) {
1258
+ job.buf.push({ s: stream, text: text.slice(0, Math.max(0, room)) });
1259
+ job.bytes = sh.limits.outBytes;
1260
+ throw new Stop("stopped: more output than can be shown");
1261
+ }
1262
+ job.bytes += sizeOf(text);
1263
+ job.buf.push({ s: stream, text });
1264
+ };
1265
+ const jio = { in: null, out: put("out"), err: put("err") };
1266
+ const failed = (code, text) => ((job.status = "failed"), (job.code = code), job.buf.push({ s: "err", text: `clsh: ${text}\n` }));
1267
+ job.done = (async () => {
1268
+ try {
1269
+ job.code = await execAndOr(node.body, sub, jio);
1270
+ job.status = "done";
1271
+ } catch (error) {
1272
+ if (error instanceof Killed) (job.status = "killed"), (job.code = 143);
1273
+ else if (error instanceof Exit || error instanceof Return) (job.status = "done"), (job.code = error.code);
1274
+ else if (error instanceof Stop) failed(124, error.message);
1275
+ else if (error instanceof SyntaxError) failed(2, `syntax error: ${error.message}`);
1276
+ else failed(1, error?.message ?? String(error));
1277
+ } finally {
1278
+ if (job.cancelled && job.status === "done") (job.status = "killed"), (job.code = 143);
1279
+ sh.steps += Math.max(0, sub.steps - base);
1280
+ }
1281
+ })();
1282
+ sh.jobs.push(job);
1283
+ sh.lastJob = job.id;
1284
+ return 0;
1285
+ }
1286
+
1287
+ /** Wait for a job, show what it printed, and forget it. */
1288
+ async function joinJob(sh, job, io) {
1289
+ await job.done;
1290
+ for (const c of job.buf.splice(0)) (c.s === "err" ? io.err : io.out)(c.text);
1291
+ const at = sh.jobs.indexOf(job);
1292
+ if (at >= 0) sh.jobs.splice(at, 1);
1293
+ return job.code;
1294
+ }
1295
+
1296
+ /** The end of a line: its jobs are waited for, in order, and what they printed comes out. */
1297
+ async function settleJobs(sh, io) {
1298
+ for (const job of [...sh.jobs]) await joinJob(sh, job, io);
1299
+ }
1300
+
1301
+ /** `%n`, `%%`, `%+`, `%-` or a bare job number: the job it names, or null. */
1302
+ function jobBySpec(sh, spec) {
1303
+ const list = [...sh.jobs].sort((a, b) => a.id - b.id);
1304
+ if (spec === undefined || spec === "%%" || spec === "%+" || spec === "%") return list.at(-1) ?? null;
1305
+ if (spec === "%-") return list.at(-2) ?? null;
1306
+ const m = /^%?([0-9]+)$/.exec(spec);
1307
+ return m ? list.find((j) => j.id === Number(m[1])) ?? null : null;
1308
+ }
1309
+
1310
+ async function writeText(sh, path, text, append, who) {
1311
+ const bad = nameProblem(baseOf(path));
1312
+ if (bad) throw Object.assign(new Error(bad), { name: "TypeError" });
1313
+ const sniff = executableBytes(enc.encode(String(text).slice(0, 8)));
1314
+ if (sniff) throw Object.assign(new TypeError(`the text ${sniff}; this folder does not store programs`), { name: "TypeError" });
1315
+ let data = text;
1316
+ if (append && (await sh.fs.exists(path).catch(() => false))) data = toText(await sh.fs.read(path)) + text;
1317
+ if (sizeOf(data) > sh.limits.fileBytes) throw Object.assign(new Error(`a file is at most ${sh.limits.fileBytes} bytes`), { name: "QuotaExceededError" });
1318
+ const parent = dirOf(path);
1319
+ if (parent !== "/") {
1320
+ const st = await sh.fs.stat(parent).catch(() => null);
1321
+ if (!st) throw Object.assign(new Error("No such file or directory"), { name: "NotFoundError" });
1322
+ if (st.type !== "dir") throw Object.assign(new Error("Not a directory"), { name: "TypeMismatchError" });
1323
+ }
1324
+ await sh.fs.write(path, enc.encode(data));
1325
+ void who;
1326
+ }
1327
+
1328
+ /** Where a command's streams go: its redirects, applied. `{ io, sinks }`, or `{ failed: true }` when a file could not be read (already said). */
1329
+ async function applyRedirs(redirs, sh, io) {
1330
+ let stdin = io.in;
1331
+ let out = io.out;
1332
+ let err = io.err;
1333
+ const sinks = [];
1334
+ let errToOut = false;
1335
+ for (const r of redirs) {
1336
+ if (r.op === "2>&1") {
1337
+ errToOut = true;
1338
+ continue;
1339
+ }
1340
+ if (r.op === "<<" || r.op === "<<<") {
1341
+ // a here-document's text, or a here-string and its newline: expanded here, never split or globbed
1342
+ const text = (await expand(r.target, sh, { split: false }))[0] ?? "";
1343
+ stdin = mkIn(r.op === "<<<" ? `${text}\n` : text);
1344
+ continue;
1345
+ }
1346
+ const names = await expand(r.target, sh, { split: false });
1347
+ const p = sh.abs(names[0] ?? "");
1348
+ if (r.op === "<") {
1349
+ try {
1350
+ stdin = mkIn(toText(await sh.fs.read(p)));
1351
+ } catch (e) {
1352
+ io.err(`clsh: ${fsMessage(e, names[0])}\n`);
1353
+ return { failed: true, sinks: [] };
1354
+ }
1355
+ continue;
1356
+ }
1357
+ if (names[0] === "") {
1358
+ io.err("clsh: a redirect needs a file name\n");
1359
+ return { failed: true, sinks: [] };
1360
+ }
1361
+ const sink = { path: p, shown: names[0], text: "", append: r.op.endsWith(">>") };
1362
+ sinks.push(sink);
1363
+ const collect = (t) => (sink.text += t);
1364
+ if (r.op === ">" || r.op === ">>" || r.op === "1>" || r.op === "1>>") out = collect;
1365
+ else if (r.op === "2>" || r.op === "2>>") err = collect;
1366
+ else if (r.op === "&>") (out = collect), (err = collect);
1367
+ }
1368
+ if (errToOut) err = out;
1369
+ return { io: { in: stdin, out, err }, sinks };
1370
+ }
1371
+
1372
+ /** Write what the redirected files collected; a write that fails is said and makes the code 1. */
1373
+ async function flushSinks(sinks, sh, io, code) {
1374
+ for (const s of sinks) {
1375
+ try {
1376
+ await writeText(sh, s.path, s.text, s.append);
1377
+ } catch (e) {
1378
+ io.err(`clsh: ${fsMessage(e, s.shown)}\n`);
1379
+ code = 1;
1380
+ }
1381
+ }
1382
+ return code;
1383
+ }
1384
+
1385
+ async function execSimple(node, sh, io) {
1386
+ const set = await applyRedirs(node.redirs, sh, io);
1387
+ if (set.failed) return 1;
1388
+ let code;
1389
+ try {
1390
+ code = await runWords(node, sh, set.io);
1391
+ } finally {
1392
+ code = await flushSinks(set.sinks, sh, io, code);
1393
+ }
1394
+ return code;
1395
+ }
1396
+
1397
+ async function runWords(node, sh, io) {
1398
+ const argv = (await Promise.all(node.words.map((w) => expand(w, sh)))).flat();
1399
+ if (!argv.length) {
1400
+ for (const a of node.assigns) setVar(sh, a.name, (await expand(a.word, sh, { split: false }))[0]);
1401
+ return 0;
1402
+ }
1403
+ // `NAME=value cmd`: the value is for this command only
1404
+ const saved = [];
1405
+ for (const a of node.assigns) {
1406
+ saved.push([a.name, sh.vars.get(a.name)]);
1407
+ sh.vars.set(a.name, (await expand(a.word, sh, { split: false }))[0]);
1408
+ }
1409
+ try {
1410
+ return await callBuiltin(argv[0], argv.slice(1), sh, io);
1411
+ } finally {
1412
+ for (const [k, v] of saved) v === undefined ? sh.vars.delete(k) : sh.vars.set(k, v);
1413
+ }
1414
+ }
1415
+
1416
+ function setVar(sh, name, value) {
1417
+ if (!NAME.test(name)) throw new SyntaxError(`${name}: not a valid name`);
1418
+ if (!sh.vars.has(name) && sh.vars.size >= sh.limits.vars) throw new Stop(`stopped: more than ${sh.limits.vars} variables`);
1419
+ sh.vars.set(name, String(value).slice(0, sh.limits.varBytes));
1420
+ }
1421
+
1422
+ async function callBuiltin(name, args, sh, io, aliasDepth = 0) {
1423
+ tick(sh);
1424
+ const alias = aliasDepth < 8 ? sh.aliases?.get(name) : undefined;
1425
+ if (alias !== undefined) {
1426
+ const expanded = (await expand(lex(alias)[0] ?? { t: "w", segs: [] }, sh).catch(() => [])).concat((await Promise.all(lex(alias).slice(1).filter((t) => t.t === "w").map((t) => expand(t, sh)))).flat());
1427
+ if (expanded.length) return callBuiltin(expanded[0], [...expanded.slice(1), ...args], sh, io, aliasDepth + 1);
1428
+ }
1429
+ const defined = sh.funcs.get(name);
1430
+ if (defined) return callFunction(name, defined, args, sh, io);
1431
+ const fn = Object.hasOwn(BUILTINS, name) ? BUILTINS[name] : null;
1432
+ if (!fn) {
1433
+ io.err(`clsh: ${name}: command not found${name.includes("/") || name.startsWith(".") ? " (this shell runs no programs)" : ""}\n`);
1434
+ return 127;
1435
+ }
1436
+ try {
1437
+ return (await fn(args, sh, io)) ?? 0;
1438
+ } catch (e) {
1439
+ if (e instanceof Stop || e instanceof Exit || e instanceof Return || e instanceof Killed) throw e;
1440
+ io.err(`${name}: ${e instanceof SyntaxError || e instanceof TypeError ? e.message : fsMessage(e, "")}\n`.replace(": : ", ": ").replace(": : ", ": "));
1441
+ return 1;
1442
+ }
1443
+ }
1444
+
1445
+ // ── builtins ────────────────────────────────────────────────────────────────────────────────────
1446
+
1447
+ /** Short options: `flags` (no value) and `values` (take one); `-n5`, `-n 5`, clusters like `-la`, `--` ends them. A bare number is returned as `num` (`head -5`). */
1448
+ function getopts(args, { flags = "", values = "", long = [] } = {}) {
1449
+ const f = new Set();
1450
+ const v = {};
1451
+ const rest = [];
1452
+ let num;
1453
+ for (let i = 0; i < args.length; i++) {
1454
+ const a = args[i];
1455
+ if (a === "--") {
1456
+ rest.push(...args.slice(i + 1));
1457
+ break;
1458
+ }
1459
+ if (a.startsWith("--") && a.length > 2) {
1460
+ const name = a.slice(2).split("=")[0];
1461
+ if (!long.includes(name)) throw new TypeError(`unknown option ${a}`);
1462
+ f.add(name);
1463
+ continue;
1464
+ }
1465
+ if (a.length > 1 && a[0] === "-" && /^-[0-9]+$/.test(a)) {
1466
+ num = Number(a.slice(1));
1467
+ continue;
1468
+ }
1469
+ if (a.length > 1 && a[0] === "-") {
1470
+ for (let j = 1; j < a.length; j++) {
1471
+ const c = a[j];
1472
+ if (values.includes(c)) {
1473
+ const val = a.slice(j + 1) || args[++i];
1474
+ if (val === undefined) throw new TypeError(`option -${c} needs a value`);
1475
+ v[c] = val;
1476
+ break;
1477
+ }
1478
+ if (!flags.includes(c)) throw new TypeError(`unknown option -${c}`);
1479
+ f.add(c);
1480
+ }
1481
+ continue;
1482
+ }
1483
+ rest.push(a);
1484
+ }
1485
+ return { f, v, rest, num };
1486
+ }
1487
+
1488
+ /** A regular expression from a person's pattern (JavaScript syntax), refused when it could run away or doesn't compile. */
1489
+ export function safeRegex(pattern, flags = "") {
1490
+ if (pattern.length > 300) throw new SyntaxError("a pattern is at most 300 characters");
1491
+ if (/(\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\))[+*{]/.test(pattern) || /(\\[1-9])[+*{]/.test(pattern)) throw new SyntaxError("that pattern repeats a repeat, which can run for a very long time here");
1492
+ try {
1493
+ return new RegExp(pattern, flags);
1494
+ } catch (error) {
1495
+ throw new SyntaxError(`bad pattern: ${error.message}`);
1496
+ }
1497
+ }
1498
+
1499
+ async function readFiles(sh, io, files, who) {
1500
+ if (!files.length) return { items: [{ name: "-", text: slurp(io) }], bad: 0 };
1501
+ const items = [];
1502
+ let bad = 0;
1503
+ for (const f of files) {
1504
+ if (f === "-") {
1505
+ items.push({ name: "-", text: slurp(io) });
1506
+ continue;
1507
+ }
1508
+ try {
1509
+ const p = sh.abs(f);
1510
+ const bytes = await sh.fs.read(p);
1511
+ if (bytes.byteLength > sh.limits.fileBytes) throw Object.assign(new Error(`more than ${sh.limits.fileBytes} bytes`), { name: "QuotaExceededError" });
1512
+ items.push({ name: f, text: toText(bytes) });
1513
+ } catch (e) {
1514
+ io.err(`${who}: ${fsMessage(e, f)}\n`);
1515
+ bad++;
1516
+ }
1517
+ }
1518
+ return { items, bad };
1519
+ }
1520
+
1521
+ const lines = (text) => {
1522
+ if (text === "") return [];
1523
+ const l = text.split("\n");
1524
+ if (l.at(-1) === "") l.pop();
1525
+ return l;
1526
+ };
1527
+ const joinLines = (l) => (l.length ? `${l.join("\n")}\n` : "");
1528
+
1529
+ const ESC = { n: "\n", t: "\t", r: "\r", "\\": "\\", a: "\x07", b: "\b", f: "\f", v: "\v", e: "\x1b", 0: "\0" };
1530
+ const unescape = (s) => s.replace(/\\(x[0-9a-fA-F]{1,2}|u[0-9a-fA-F]{4}|[ntr\\abfve0])/g, (_, k) => (k[0] === "x" || k[0] === "u" ? String.fromCharCode(parseInt(k.slice(1), 16)) : ESC[k]));
1531
+
1532
+ function formatPrintf(fmt, args) {
1533
+ let ai = 0;
1534
+ let out = "";
1535
+ let used = false;
1536
+ const once = () => {
1537
+ used = false;
1538
+ out += fmt.replace(/%([-0 +#]*)(\d+)?(?:\.(\d+))?([sdixXofcb%])|\\(x[0-9a-fA-F]{1,2}|u[0-9a-fA-F]{4}|[ntr\\abfve0])/g, (m, flags, width, prec, conv, esc) => {
1539
+ if (esc !== undefined) return unescape(`\\${esc}`);
1540
+ if (conv === "%") return "%";
1541
+ used = true;
1542
+ const raw = args[ai++] ?? "";
1543
+ let s;
1544
+ if (conv === "s" || conv === "b") s = conv === "b" ? unescape(String(raw)) : String(raw);
1545
+ else if (conv === "c") s = String(raw)[0] ?? "";
1546
+ else {
1547
+ const num = Number(raw === "" ? 0 : raw);
1548
+ if (!Number.isFinite(num)) throw new TypeError(`printf: ${raw}: not a number`);
1549
+ s = conv === "d" || conv === "i" ? String(Math.trunc(num)) : conv === "x" ? Math.trunc(num).toString(16) : conv === "X" ? Math.trunc(num).toString(16).toUpperCase() : conv === "o" ? Math.trunc(num).toString(8) : num.toFixed(prec === undefined ? 6 : Number(prec));
1550
+ if (flags.includes("+") && num >= 0) s = `+${s}`;
1551
+ }
1552
+ if (prec !== undefined && conv === "s") s = s.slice(0, Number(prec));
1553
+ const w = Number(width ?? 0);
1554
+ if (s.length < w) s = flags.includes("-") ? s.padEnd(w) : flags.includes("0") && conv !== "s" ? s.padStart(w, "0") : s.padStart(w);
1555
+ return s;
1556
+ });
1557
+ };
1558
+ once();
1559
+ while (used && ai < args.length) once();
1560
+ return out;
1561
+ }
1562
+
1563
+ const pad2 = (n) => String(n).padStart(2, "0");
1564
+ const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
1565
+ const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
1566
+ function strftime(fmt, d, utc) {
1567
+ const g = (u, l) => (utc ? d[`getUTC${u}`]() : d[`get${l ?? u}`]());
1568
+ const Y = g("FullYear");
1569
+ const mo = g("Month");
1570
+ const day = g("Date");
1571
+ const H = g("Hours");
1572
+ const M = g("Minutes");
1573
+ const S = g("Seconds");
1574
+ const wd = g("Day");
1575
+ const start = Date.UTC(Y, 0, 1);
1576
+ const yday = Math.floor((Date.UTC(Y, mo, day) - start) / 86400000) + 1;
1577
+ return fmt.replace(/%([YymdHMSjFTbBaAZsyeIpD%])/g, (_, c) => {
1578
+ switch (c) {
1579
+ case "Y": return String(Y);
1580
+ case "y": return pad2(Y % 100);
1581
+ case "m": return pad2(mo + 1);
1582
+ case "d": return pad2(day);
1583
+ case "e": return String(day).padStart(2);
1584
+ case "H": return pad2(H);
1585
+ case "I": return pad2(H % 12 || 12);
1586
+ case "p": return H < 12 ? "AM" : "PM";
1587
+ case "M": return pad2(M);
1588
+ case "S": return pad2(S);
1589
+ case "j": return String(yday).padStart(3, "0");
1590
+ case "F": return `${Y}-${pad2(mo + 1)}-${pad2(day)}`;
1591
+ case "T": return `${pad2(H)}:${pad2(M)}:${pad2(S)}`;
1592
+ case "D": return `${pad2(mo + 1)}/${pad2(day)}/${pad2(Y % 100)}`;
1593
+ case "b": return MONTHS[mo].slice(0, 3);
1594
+ case "B": return MONTHS[mo];
1595
+ case "a": return DAYS[wd].slice(0, 3);
1596
+ case "A": return DAYS[wd];
1597
+ case "Z": return utc ? "UTC" : "local";
1598
+ case "s": return String(Math.floor(d.getTime() / 1000));
1599
+ default: return "%";
1600
+ }
1601
+ });
1602
+ }
1603
+
1604
+ async function walkTree(sh, root, { maxDepth = Infinity, limit = sh.limits.find } = {}) {
1605
+ const st = await sh.fs.stat(root);
1606
+ const out = [];
1607
+ const visit = async (path, type, size, depth) => {
1608
+ tick(sh);
1609
+ out.push({ path, type, size, depth });
1610
+ if (out.length > limit) throw new Stop(`stopped: more than ${limit} entries`);
1611
+ if (type !== "dir" || depth >= maxDepth) return;
1612
+ const entries = (await sh.fs.list(path)).slice().sort((a, b) => (a.name < b.name ? -1 : 1));
1613
+ for (const e of entries) await visit(joinP(path, e.name), e.type, e.size ?? 0, depth + 1);
1614
+ };
1615
+ await visit(root, st.type, st.size ?? 0, 0);
1616
+ return out;
1617
+ }
1618
+
1619
+ async function copyOne(sh, from, to, io, who) {
1620
+ const st = await sh.fs.stat(from);
1621
+ if (st.type === "dir") throw Object.assign(new Error(`${from}: is a folder (use -r)`), { name: "TypeError" });
1622
+ const bad = nameProblem(baseOf(to));
1623
+ if (bad) throw Object.assign(new Error(bad), { name: "TypeError" });
1624
+ const bytes = await sh.fs.read(from);
1625
+ if (bytes.byteLength > sh.limits.fileBytes) throw Object.assign(new Error(`a file is at most ${sh.limits.fileBytes} bytes`), { name: "QuotaExceededError" });
1626
+ const sniff = executableBytes(bytes.subarray(0, 8));
1627
+ if (sniff) throw Object.assign(new Error(`it looks like ${sniff}; this folder does not store programs`), { name: "TypeError" });
1628
+ await sh.fs.write(to, bytes);
1629
+ const back = await sh.fs.stat(to);
1630
+ if (back.size !== bytes.byteLength) throw new Error(`${to} was not written completely`);
1631
+ void io;
1632
+ void who;
1633
+ }
1634
+
1635
+ async function copyTree(sh, from, to, io, who) {
1636
+ const entries = await walkTree(sh, from, { limit: sh.limits.snapshotEntries });
1637
+ for (const e of entries) {
1638
+ const target = to + e.path.slice(from.length);
1639
+ if (e.type === "dir") await sh.fs.mkdir(target);
1640
+ else await copyOne(sh, e.path, target, io, who);
1641
+ }
1642
+ }
1643
+
1644
+ const testExpr = async (args, sh) => {
1645
+ const a = [...args];
1646
+ if (a.at(-1) === "]") a.pop();
1647
+ const evalAt = async () => {
1648
+ if (a[0] === "!") return a.shift(), !(await evalAt());
1649
+ if (a.length === 0) return false;
1650
+ if (a.length === 1) return a.shift() !== "";
1651
+ const unary = /^-([efdszn])$/.exec(a[0]);
1652
+ if (unary && a.length >= 2) {
1653
+ a.shift();
1654
+ const v = a.shift();
1655
+ if (unary[1] === "z") return v === "";
1656
+ if (unary[1] === "n") return v !== "";
1657
+ const st = await sh.fs.stat(sh.abs(v)).catch(() => null);
1658
+ if (!st) return false;
1659
+ if (unary[1] === "e") return true;
1660
+ if (unary[1] === "f") return st.type === "file";
1661
+ if (unary[1] === "d") return st.type === "dir";
1662
+ return (st.size ?? 0) > 0;
1663
+ }
1664
+ const l = a.shift();
1665
+ const op = a.shift();
1666
+ const r = a.shift();
1667
+ if (op === "=" || op === "==") return l === r;
1668
+ if (op === "!=") return l !== r;
1669
+ const ln = Number(l);
1670
+ const rn = Number(r);
1671
+ if (!["-eq", "-ne", "-lt", "-le", "-gt", "-ge"].includes(op)) throw new TypeError(`${op}: unknown test`);
1672
+ if (!Number.isFinite(ln) || !Number.isFinite(rn)) throw new TypeError("a number is needed");
1673
+ return { "-eq": ln === rn, "-ne": ln !== rn, "-lt": ln < rn, "-le": ln <= rn, "-gt": ln > rn, "-ge": ln >= rn }[op];
1674
+ };
1675
+ let v = await evalAt();
1676
+ while (a.length && (a[0] === "-a" || a[0] === "-o")) {
1677
+ const op = a.shift();
1678
+ const n = await evalAt();
1679
+ v = op === "-a" ? v && n : v || n;
1680
+ }
1681
+ if (a.length) throw new TypeError("too many arguments");
1682
+ return v;
1683
+ };
1684
+
1685
+ const cutList = (spec) => {
1686
+ const ranges = spec.split(",").map((p) => {
1687
+ const m = /^(\d*)-?(\d*)$/.exec(p);
1688
+ if (!m || (p === "" || p === "-")) throw new TypeError(`bad list: ${spec}`);
1689
+ const dash = p.includes("-");
1690
+ const lo = m[1] === "" ? 1 : Number(m[1]);
1691
+ const hi = dash ? (m[2] === "" ? Infinity : Number(m[2])) : lo;
1692
+ return [lo, hi];
1693
+ });
1694
+ return (i) => ranges.some(([lo, hi]) => i >= lo && i <= hi);
1695
+ };
1696
+
1697
+ function trSet(s) {
1698
+ const classes = { "[:upper:]": "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "[:lower:]": "abcdefghijklmnopqrstuvwxyz", "[:digit:]": "0123456789", "[:space:]": " \t\n\r\f\v", "[:alpha:]": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "[:alnum:]": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "[:punct:]": "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" };
1699
+ let out = "";
1700
+ const t = unescape(s);
1701
+ for (let i = 0; i < t.length; i++) {
1702
+ const cls = t.startsWith("[:", i) ? t.slice(i, t.indexOf(":]", i) + 2) : "";
1703
+ if (cls && classes[cls]) {
1704
+ out += classes[cls];
1705
+ i += cls.length - 1;
1706
+ } else if (t[i + 1] === "-" && i + 2 < t.length) {
1707
+ for (let c = t.charCodeAt(i); c <= t.charCodeAt(i + 2); c++) out += String.fromCharCode(c);
1708
+ i += 2;
1709
+ } else out += t[i];
1710
+ }
1711
+ return out;
1712
+ }
1713
+
1714
+ async function sedRun(script, text, { quiet }) {
1715
+ const cmds = [];
1716
+ const src = script.join("\n");
1717
+ let i = 0;
1718
+ const parseAddr = () => {
1719
+ let m;
1720
+ const rest = src.slice(i);
1721
+ if ((m = /^\$/.exec(rest))) return (i += 1), { last: true };
1722
+ if ((m = /^(\d+)/.exec(rest))) return (i += m[0].length), { n: Number(m[1]) };
1723
+ if (rest[0] === "/") {
1724
+ const end = rest.indexOf("/", 1);
1725
+ if (end < 0) throw new SyntaxError("sed: unterminated address");
1726
+ const re = safeRegex(rest.slice(1, end));
1727
+ i += end + 1;
1728
+ return { re };
1729
+ }
1730
+ return null;
1731
+ };
1732
+ while (i < src.length) {
1733
+ while (i < src.length && /[\s;]/.test(src[i])) i++;
1734
+ if (i >= src.length) break;
1735
+ const a1 = parseAddr();
1736
+ let a2 = null;
1737
+ if (a1 && src[i] === ",") (i++, (a2 = parseAddr()));
1738
+ while (src[i] === " ") i++;
1739
+ const c = src[i++];
1740
+ if (c === "d" || c === "p") cmds.push({ a1, a2, c });
1741
+ else if (c === "s") {
1742
+ const d = src[i++];
1743
+ const readPart = () => {
1744
+ let s = "";
1745
+ while (i < src.length && src[i] !== d) {
1746
+ if (src[i] === "\\" && i + 1 < src.length) {
1747
+ s += src[i + 1] === d ? d : `\\${src[i + 1]}`;
1748
+ i += 2;
1749
+ } else s += src[i++];
1750
+ }
1751
+ if (src[i] !== d) throw new SyntaxError("sed: unterminated s command");
1752
+ i++;
1753
+ return s;
1754
+ };
1755
+ const pat = readPart();
1756
+ const rep = readPart();
1757
+ let fl = "";
1758
+ while (i < src.length && /[gipI0-9]/.test(src[i])) fl += src[i++];
1759
+ cmds.push({ a1, a2, c: "s", re: safeRegex(pat, `${fl.includes("g") ? "g" : ""}${/[iI]/.test(fl) ? "i" : ""}`), rep, print: fl.includes("p") });
1760
+ } else throw new SyntaxError(`sed: unknown command "${c ?? ""}"`);
1761
+ }
1762
+ const all = lines(text);
1763
+ const out = [];
1764
+ const active = new Map();
1765
+ all.forEach((line, idx) => {
1766
+ const ln = idx + 1;
1767
+ let cur = line;
1768
+ let deleted = false;
1769
+ for (const [ci, cmd] of cmds.entries()) {
1770
+ const hit = (a) => (a.last ? ln === all.length : a.n !== undefined ? ln === a.n : a.re.test(cur));
1771
+ let on = true;
1772
+ if (cmd.a1 && !cmd.a2) on = hit(cmd.a1);
1773
+ else if (cmd.a1 && cmd.a2) {
1774
+ if (active.get(ci)) {
1775
+ on = true;
1776
+ if (hit(cmd.a2)) active.set(ci, false);
1777
+ } else if (hit(cmd.a1)) {
1778
+ on = true;
1779
+ if (!(cmd.a2.n !== undefined && cmd.a2.n <= ln) && !hit(cmd.a2)) active.set(ci, true);
1780
+ } else on = false;
1781
+ }
1782
+ if (!on) continue;
1783
+ if (cmd.c === "d") {
1784
+ deleted = true;
1785
+ break;
1786
+ }
1787
+ if (cmd.c === "p") out.push(cur);
1788
+ else if (cmd.c === "s") {
1789
+ const before = cur;
1790
+ cur = cur.replace(cmd.re, (...m) => {
1791
+ const groups = m.slice(0, -2).filter((x) => typeof x === "string" || x === undefined);
1792
+ return cmd.rep.replace(/\\([0-9nt&\\])|&/g, (k, g) => (k === "&" ? groups[0] : g === "n" ? "\n" : g === "t" ? "\t" : g === "&" ? "&" : g === "\\" ? "\\" : (groups[Number(g)] ?? "")));
1793
+ });
1794
+ if (cmd.print && cur !== before) out.push(cur);
1795
+ }
1796
+ }
1797
+ if (!deleted && !quiet) out.push(cur);
1798
+ });
1799
+ return joinLines(out.flatMap((l) => l.split("\n")));
1800
+ }
1801
+
1802
+ async function sha256Hex(bytes) {
1803
+ const d = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1804
+ return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
1805
+ }
1806
+
1807
+ const MD5_S = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
1808
+ const MD5_K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
1809
+
1810
+ /** MD5 of some bytes, as hex (WebCrypto has none: `md5sum` is for checking files that come with an MD5, not for anything secret). */
1811
+ function md5Hex(bytes) {
1812
+ const n = bytes.length;
1813
+ const padded = new Uint8Array(Math.ceil((n + 9) / 64) * 64);
1814
+ padded.set(bytes);
1815
+ padded[n] = 0x80;
1816
+ const view = new DataView(padded.buffer);
1817
+ view.setUint32(padded.length - 8, (n * 8) >>> 0, true);
1818
+ view.setUint32(padded.length - 4, Math.floor(n / 2 ** 29), true);
1819
+ let a0 = 0x67452301;
1820
+ let b0 = 0xefcdab89;
1821
+ let c0 = 0x98badcfe;
1822
+ let d0 = 0x10325476;
1823
+ const m = new Uint32Array(16);
1824
+ for (let at = 0; at < padded.length; at += 64) {
1825
+ for (let k = 0; k < 16; k++) m[k] = view.getUint32(at + k * 4, true);
1826
+ let [a, b, c, d] = [a0, b0, c0, d0];
1827
+ for (let i = 0; i < 64; i++) {
1828
+ let f;
1829
+ let g;
1830
+ if (i < 16) (f = (b & c) | (~b & d)), (g = i);
1831
+ else if (i < 32) (f = (d & b) | (~d & c)), (g = (5 * i + 1) % 16);
1832
+ else if (i < 48) (f = b ^ c ^ d), (g = (3 * i + 5) % 16);
1833
+ else (f = c ^ (b | ~d)), (g = (7 * i) % 16);
1834
+ f = (f + a + MD5_K[i] + m[g]) >>> 0;
1835
+ a = d;
1836
+ d = c;
1837
+ c = b;
1838
+ const r = MD5_S[(i >> 4) * 4 + (i % 4)];
1839
+ b = (b + ((f << r) | (f >>> (32 - r)))) >>> 0;
1840
+ }
1841
+ a0 = (a0 + a) >>> 0;
1842
+ b0 = (b0 + b) >>> 0;
1843
+ c0 = (c0 + c) >>> 0;
1844
+ d0 = (d0 + d) >>> 0;
1845
+ }
1846
+ return [a0, b0, c0, d0].map((w) => [0, 8, 16, 24].map((sh) => ((w >>> sh) & 255).toString(16).padStart(2, "0")).join("")).join("");
1847
+ }
1848
+
1849
+ const b64 = {
1850
+ enc: (bytes) => {
1851
+ let s = "";
1852
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
1853
+ return btoa(s);
1854
+ },
1855
+ dec: (text) => Uint8Array.from(atob(text.replace(/\s+/g, "")), (c) => c.charCodeAt(0)),
1856
+ };
1857
+
1858
+ /** What each builtin is for, one line, for `help` and the command list. */
1859
+ export const USAGE = Object.freeze({
1860
+ ":": ": do nothing, succeed",
1861
+ "[": "[ test ]: the same as test",
1862
+ base64: "base64 [-d] [file]: encode or decode",
1863
+ basename: "basename path [suffix]",
1864
+ cat: "cat [-n] [file...]: print files or the input",
1865
+ cd: "cd [dir]: change folder (no argument: the top)",
1866
+ clawser: "clawser help|version|status|tools|history|clear|session|snapshot|wsh|cost|memory|mcp|rpc: the clawser commands this shell has",
1867
+ clear: "clear: clear the screen",
1868
+ column: "column [-t] [-s chars] [-o sep] [-c width] [-x] [file...]: align columns (-t) or fill a screen's width",
1869
+ md5sum: "md5sum [file...]: MD5 of files or the input (for checking downloads, not for secrets)",
1870
+ local: "local NAME[=value]...: a variable that ends with the function",
1871
+ return: "return [n]: leave a function (or a sourced file) with this code",
1872
+ shift: "shift [n]: drop the first arguments of a function",
1873
+ jobs: "jobs: the background jobs of this line",
1874
+ wait: "wait [%n|n...]: wait for jobs, then their exit code",
1875
+ fg: "fg [%n]: wait for a job and show its output",
1876
+ bg: "bg [%n]: jobs already run in the background; this says so",
1877
+ kill: "kill [-signal] %n...: stop a background job (no other process exists)",
1878
+ cost: "cost: what unattended agent runs spent today and this month (read-only; the person's own ledger)",
1879
+ memory: "memory: this shell has no grant to read memory notes; it says how to give one",
1880
+ mcp: "mcp: the MCP servers of this canvas, their state and tools (read-only; no addresses or keys)",
1881
+ rpc: "rpc: the agent-to-agent peers of this canvas (A2A, ACP); this shell opens no socket and serves nothing",
1882
+ command: "command -v name: say whether a command exists",
1883
+ cp: "cp [-r] source... target",
1884
+ curl: "curl [-sSiILf] [-X method] [-H header] [-d data] [-o file] url: a request through the canvas's network rules",
1885
+ cut: "cut -d sep -f list | -c list: pick fields or characters",
1886
+ date: "date [-u] [+format]: the time",
1887
+ dirname: "dirname path",
1888
+ echo: "echo [-n] [-e] [text...]",
1889
+ env: "env: list the exported variables",
1890
+ exit: "exit [n]: end the shell's line with this code",
1891
+ export: "export NAME[=value]...: mark variables exported",
1892
+ false: "false: fail",
1893
+ find: "find [path...] [-name pattern] [-type f|d] [-maxdepth n]",
1894
+ grep: "grep [-ivncloEFwr] pattern [file...]: JavaScript regular expressions",
1895
+ head: "head [-n N] [file...]",
1896
+ help: "help [command]: list commands, or say what one does",
1897
+ history: "history: the lines you typed",
1898
+ jq: "jq [-rcsn] filter [file]: a small jq (paths, [], |, select, map, length, keys, sort, join, ...)",
1899
+ ls: "ls [-a] [-l] [-1] [-F] [path...]",
1900
+ mkdir: "mkdir [-p] dir...",
1901
+ mv: "mv source... target",
1902
+ printenv: "printenv [name]",
1903
+ printf: "printf format [args...]",
1904
+ pwd: "pwd: the current folder",
1905
+ read: "read [-r] name...: read a line of input into variables",
1906
+ rev: "rev: reverse each line",
1907
+ rm: "rm [-rf] path...",
1908
+ rmdir: "rmdir dir...: remove empty folders",
1909
+ sed: "sed [-n] [-i] [-e] script [file...]: s///, d, p with line, $ and /re/ addresses",
1910
+ seq: "seq [first [step]] last",
1911
+ set: "set [NAME=value]: list or set shell variables",
1912
+ sha256sum: "sha256sum [file...]",
1913
+ sleep: "sleep seconds (at most 3 per call)",
1914
+ snapshot: "snapshot save [name]|list|info id|restore id|delete id|clear: copies of this folder, kept inside it",
1915
+ sort: "sort [-rnuf] [-t sep] [-k n] [file...]",
1916
+ source: "source file: run a file's commands here",
1917
+ stat: "stat path...",
1918
+ tac: "tac: lines in reverse order",
1919
+ tail: "tail [-n N] [file...]",
1920
+ tee: "tee [-a] file...: copy input to files and output",
1921
+ test: "test expression (-e -f -d -s -z -n = != -eq -ne -lt -le -gt -ge ! -a -o)",
1922
+ touch: "touch file...: make an empty file if it isn't there",
1923
+ tr: "tr [-ds] set1 [set2]",
1924
+ true: "true: succeed",
1925
+ type: "type name: say what a name is",
1926
+ unset: "unset NAME...",
1927
+ uniq: "uniq [-c] [-d] [-u]",
1928
+ unalias: "unalias name...",
1929
+ alias: "alias [name=value]: a name for a command line",
1930
+ realpath: "realpath path...",
1931
+ nl: "nl [file...]: number the lines",
1932
+ paste: "paste [-d sep] file...: join lines side by side",
1933
+ fold: "fold [-w N] [file...]: wrap lines",
1934
+ du: "du [-sh] [path...]: bytes under a path",
1935
+ tree: "tree [dir]: the folder as a tree",
1936
+ diff: "diff a b: lines only in a (<) or b (>); exit 1 when they differ",
1937
+ yes: "yes [text]: repeat a line (at most 1000)",
1938
+ xxd: "xxd [file]: a hex dump",
1939
+ time: "time command...: run it and say how long",
1940
+ wc: "wc [-lwc] [file...]",
1941
+ which: "which name: say whether a command exists",
1942
+ xargs: "xargs [-n N] [-I str] command [args]: run a command on the input's words",
1943
+ });
1944
+
1945
+ const CLAWSER_SUBS = ["help", "version", "status", "tools", "history", "clear", "session", "snapshot", "wsh", "cost", "memory", "mcp", "rpc"];
1946
+
1947
+ // ── read-only views of what the person owns ───────────────────────────────────────────────────────
1948
+ // `cost`, `mcp`, `rpc` and `memory` show the person their own page's state in text. The page hands a snapshot to each line it runs (`views`, src/shell/views.js); nothing here reaches a store, a
1949
+ // connection or a socket, a machine run never gets one (`sh.mode`), and a view that holds a secret, an address or a note simply is not in the snapshot.
1950
+
1951
+ const usd = (n) => (n > 0 && n < 0.01 ? `$${Number(n).toFixed(4)}` : `$${Number(n || 0).toFixed(2)}`);
1952
+ const cell = (v, n = 60) => String(v ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, n);
1953
+
1954
+ function viewGate(name, sh, io) {
1955
+ if (sh.mode === "person") return true;
1956
+ io.err(`${name}: this is the person's own view; a machine run does not get it\n`);
1957
+ return false;
1958
+ }
1959
+
1960
+ function viewCost(args, sh, io) {
1961
+ if (!viewGate("cost", sh, io)) return 1;
1962
+ const o = getopts(args, { long: ["json"] });
1963
+ const v = sh.views?.cost;
1964
+ if (!v) {
1965
+ io.err("cost: this page has no cost ledger to show\n");
1966
+ return 1;
1967
+ }
1968
+ if (v.ok === false) {
1969
+ io.err(`cost: ${cell(v.why || "the ledger cannot be read", 200)}\n`);
1970
+ return 1;
1971
+ }
1972
+ const n = (x) => (Number.isFinite(x) ? x : 0);
1973
+ if (o.f.has("json")) return io.out(`${JSON.stringify({ spentToday: n(v.spentToday), spentMonth: n(v.spentMonth), reserved: n(v.reserved), dailyUsd: n(v.dailyUsd), monthlyUsd: n(v.monthlyUsd), dailyLeft: n(v.dailyLeft), monthlyLeft: n(v.monthlyLeft) })}\n`), 0;
1974
+ io.out(`today: ${usd(n(v.spentToday))} of ${usd(n(v.dailyUsd))} (${usd(n(v.dailyLeft))} left)\nthis month: ${usd(n(v.spentMonth))} of ${usd(n(v.monthlyUsd))} (${usd(n(v.monthlyLeft))} left)\n`);
1975
+ if (n(v.reserved) > 0) io.out(`held by runs in flight: ${usd(n(v.reserved))}\n`);
1976
+ io.out("Only unattended agent runs count here. Change the ceilings in settings, autonomy and costs.\n");
1977
+ return 0;
1978
+ }
1979
+
1980
+ function viewMemory(args, sh, io) {
1981
+ if (!viewGate("memory", sh, io)) return 1;
1982
+ io.err("memory: this shell has no grant to read your memory notes, and there is no way to give it one yet. A note is read only by a memory pane you press 'allow this pane to read' in; wire that pane's text to another pane to use it.\n");
1983
+ return 1;
1984
+ }
1985
+
1986
+ function viewMcp(args, sh, io) {
1987
+ if (!viewGate("mcp", sh, io)) return 1;
1988
+ const servers = sh.views?.mcp;
1989
+ if (!Array.isArray(servers)) {
1990
+ io.err("mcp: this page has no MCP servers to show\n");
1991
+ return 1;
1992
+ }
1993
+ const [sub = "list", name] = args;
1994
+ if (sub !== "list" && sub !== "tools") throw new TypeError("mcp [list | tools [server]]");
1995
+ if (!servers.length) return io.out("no MCP server panes on this canvas\n"), 0;
1996
+ if (sub === "list") {
1997
+ const rows = servers.slice(0, 50).map((x) => [cell(x.name, 30), cell(x.state, 12), cell(x.server, 30), `${Array.isArray(x.tools) ? x.tools.length : 0} tools`]);
1998
+ const w = [0, 1, 2].map((k) => Math.max(...rows.map((r) => r[k].length)));
1999
+ for (const r of rows) io.out(`${r[0].padEnd(w[0])} ${r[1].padEnd(w[1])} ${r[2].padEnd(w[2])} ${r[3]}\n`.replace(/ +\n$/, "\n"));
2000
+ return 0;
2001
+ }
2002
+ const pick = servers.filter((x) => name === undefined || x.name === name);
2003
+ if (!pick.length) throw new TypeError(`no MCP server named ${cell(name, 30)}`);
2004
+ for (const x of pick.slice(0, 50)) {
2005
+ io.out(`${cell(x.name, 30)}\n`);
2006
+ for (const t of (Array.isArray(x.tools) ? x.tools : []).slice(0, 200)) io.out(` ${cell(t, 60)}\n`);
2007
+ }
2008
+ return 0;
2009
+ }
2010
+
2011
+ function viewRpc(args, sh, io) {
2012
+ if (!viewGate("rpc", sh, io)) return 1;
2013
+ const peers = sh.views?.rpc;
2014
+ if (!Array.isArray(peers)) {
2015
+ io.err("rpc: this page has no agent-to-agent panes to show\n");
2016
+ return 1;
2017
+ }
2018
+ if (args.length && args[0] !== "list") throw new TypeError("rpc [list]: this shell opens no socket and serves no JSON-RPC");
2019
+ if (!peers.length) io.out("no A2A or ACP agent panes on this canvas\n");
2020
+ else {
2021
+ const rows = peers.slice(0, 50).map((x) => [cell(x.name, 30), cell(x.kind, 8), cell(x.state, 14)]);
2022
+ const w = [0, 1].map((k) => Math.max(...rows.map((r) => r[k].length)));
2023
+ for (const r of rows) io.out(`${r[0].padEnd(w[0])} ${r[1].padEnd(w[1])} ${r[2]}\n`.replace(/ +\n$/, "\n"));
2024
+ }
2025
+ io.out("This shell opens no socket and serves nothing: a canvas is served to outside agents with `mallory serve --mcp` from a terminal.\n");
2026
+ return 0;
2027
+ }
2028
+ const SNAP_DIR = "/.snapshots";
2029
+ const snapId = (name) => `${new Date().toISOString().replace(/[-:]/g, "").replace(/\..*/, "").replace("T", "-")}${name ? `-${name.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 40)}` : ""}`;
2030
+ const SNAP_ID = /^[0-9]{8}-[0-9]{6}(?:-[A-Za-z0-9_-]{1,40})?$/;
2031
+
2032
+ async function snapshotCmd(args, sh, io) {
2033
+ const [sub = "list", ...rest] = args;
2034
+ const exists = (p) => sh.fs.exists(p).catch(() => false);
2035
+ if (sub === "list") {
2036
+ if (!(await exists(SNAP_DIR))) return io.out("no snapshots\n"), 0;
2037
+ const entries = (await sh.fs.list(SNAP_DIR)).filter((e) => e.type === "dir" && SNAP_ID.test(e.name)).map((e) => e.name).sort().reverse();
2038
+ io.out(entries.length ? `${entries.join("\n")}\n` : "no snapshots\n");
2039
+ return 0;
2040
+ }
2041
+ if (sub === "save") {
2042
+ const id = snapId(rest[0] ?? "");
2043
+ const root = `${SNAP_DIR}/${id}`;
2044
+ const all = (await walkTree(sh, "/", { limit: sh.limits.snapshotEntries })).filter((e) => e.path !== "/" && e.path !== SNAP_DIR && !e.path.startsWith(`${SNAP_DIR}/`));
2045
+ const bytes = all.reduce((n, e) => n + (e.type === "dir" ? 0 : e.size), 0);
2046
+ if (bytes > sh.limits.snapshotBytes) throw Object.assign(new Error(`${bytes} bytes is more than a snapshot may hold (${sh.limits.snapshotBytes})`), { name: "QuotaExceededError" });
2047
+ await sh.fs.mkdir(SNAP_DIR).catch(() => {});
2048
+ await sh.fs.mkdir(root);
2049
+ await sh.fs.mkdir(`${root}/files`);
2050
+ for (const e of all) {
2051
+ const target = `${root}/files${e.path}`;
2052
+ if (e.type === "dir") await sh.fs.mkdir(target);
2053
+ else await sh.fs.write(target, await sh.fs.read(e.path));
2054
+ }
2055
+ await sh.fs.write(`${root}/meta.json`, enc.encode(JSON.stringify({ id, files: all.filter((e) => e.type !== "dir").length, bytes, at: new Date(sh.now()).toISOString() })));
2056
+ io.out(`saved ${id} (${all.filter((e) => e.type !== "dir").length} files)\n`);
2057
+ return 0;
2058
+ }
2059
+ const id = rest[0];
2060
+ if (sub === "clear") {
2061
+ if (await exists(SNAP_DIR)) await sh.fs.remove(SNAP_DIR, true);
2062
+ io.out("snapshots cleared\n");
2063
+ return 0;
2064
+ }
2065
+ if (!id || !SNAP_ID.test(id)) throw new TypeError(`snapshot ${sub}: a snapshot id (see snapshot list)`);
2066
+ const root = `${SNAP_DIR}/${id}`;
2067
+ if (!(await exists(root))) throw Object.assign(new Error("no such snapshot"), { name: "NotFoundError" });
2068
+ if (sub === "info") return io.out(`${toText(await sh.fs.read(`${root}/meta.json`)).trim()}\n`), 0;
2069
+ if (sub === "delete") return await sh.fs.remove(root, true), io.out(`deleted ${id}\n`), 0;
2070
+ if (sub === "restore") {
2071
+ const all = (await walkTree(sh, `${root}/files`, { limit: sh.limits.snapshotEntries })).filter((e) => e.path !== `${root}/files`);
2072
+ for (const e of all) {
2073
+ const target = e.path.slice(`${root}/files`.length);
2074
+ if (e.type === "dir") await sh.fs.mkdir(target).catch(() => {});
2075
+ else await sh.fs.write(target, await sh.fs.read(e.path));
2076
+ }
2077
+ io.out(`restored ${id} (files that are in it are put back; files made since are left)\n`);
2078
+ return 0;
2079
+ }
2080
+ throw new TypeError(`snapshot: unknown subcommand ${sub} (save, list, info, restore, delete, clear)`);
2081
+ }
2082
+
2083
+ async function clawserCmd(args, sh, io) {
2084
+ const [sub, ...rest] = args;
2085
+ const person = sh.mode === "person";
2086
+ if (!sub || sub === "help") {
2087
+ io.out(`clawser: the clawser commands this shell has\n clawser status this shell: folder, session, last exit\n clawser tools the commands\n clawser history the lines you typed\n clawser clear clear the screen\n clawser session ... list | new [name] | switch name | rename name | delete name | fork [name] | export [--md|--json|--script] | save\n clawser snapshot ... same as snapshot\n clawser wsh how to reach a remote shell (the terminal pane)\n clawser cost|mcp|rpc read-only views: the cost ledger, the MCP servers, the agent peers (also as cost, mcp, rpc)\n clawser memory says why this shell cannot read memory notes\n clawser version\nNot here: prompts to an agent, model, config, andbox and schedule. Those change what an agent may do, so they stay in the panes you grant them in.\n`);
2088
+ return 0;
2089
+ }
2090
+ if (sub === "version") return io.out(`clsh ${VERSION} (clawser compatible subset)\n`), 0;
2091
+ if (sub === "tools") return io.out(`${Object.keys(BUILTINS).filter((n) => USAGE[n]).sort().join(" ")}\n`), 0;
2092
+ if (sub === "history") return await BUILTINS.history([], sh, io);
2093
+ if (sub === "status") {
2094
+ io.out(`shell: clsh ${VERSION}\nfolder: ${sh.cwd}\nlast exit: ${sh.last}\nvariables: ${sh.vars.size}\nsession: ${person ? "see clawser session" : "a machine run (no session)"}\n`);
2095
+ return 0;
2096
+ }
2097
+ if (sub === "snapshot") return snapshotCmd(rest, sh, io);
2098
+ if (["cost", "memory", "mcp", "rpc"].includes(sub)) return BUILTINS[sub](rest, sh, io);
2099
+ if (sub === "wsh") {
2100
+ io.out("wsh: a remote shell is a terminal pane on a wsh server you run; it connects only when you click Connect. This local shell has no network sockets.\n");
2101
+ return 0;
2102
+ }
2103
+ if (sub === "clear") return sh.effects.push({ type: "clear" }), 0;
2104
+ if (sub === "session") {
2105
+ if (!person) {
2106
+ io.err("clawser session: sessions belong to the person's own shell; a machine run has none\n");
2107
+ return 1;
2108
+ }
2109
+ const op = rest[0] ?? "list";
2110
+ if (!["list", "new", "switch", "rename", "delete", "fork", "export", "save"].includes(op)) throw new TypeError(`clawser session: unknown ${op}`);
2111
+ sh.effects.push({ type: "session", op, args: rest.slice(1).map(String).slice(0, 4) });
2112
+ return 0;
2113
+ }
2114
+ if (["do", "chat", "exit", "config", "model", "compact", "andbox", "schedule", "cron", "-p", "--print"].includes(sub)) {
2115
+ io.err(`clawser ${sub}: not in this shell. ${["model", "config", "andbox", "schedule", "cron"].includes(sub) ? "It would change what an agent can do, which only you do in the panes' settings." : "Talk to an agent in an agent pane; its tools are gated there."}\n`);
2116
+ return 1;
2117
+ }
2118
+ io.err(`clawser: unknown subcommand ${String(sub).slice(0, 30)} (${CLAWSER_SUBS.join(", ")})\n`);
2119
+ return 2;
2120
+ }
2121
+
2122
+ const sortLines = (l, o) => {
2123
+ const key = (s) => {
2124
+ let v = s;
2125
+ if (o.k) v = v.split(o.t ?? /\s+/).filter((x, i) => o.t || x !== "" || i > 0)[o.k - 1] ?? "";
2126
+ return o.f ? v.toLowerCase() : v;
2127
+ };
2128
+ const cmp = o.n ? (a, b) => (Number.parseFloat(key(a)) || 0) - (Number.parseFloat(key(b)) || 0) : (a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0);
2129
+ const sorted = [...l].sort((a, b) => cmp(a, b) || (a < b ? -1 : a > b ? 1 : 0));
2130
+ if (o.r) sorted.reverse();
2131
+ return o.u ? sorted.filter((x, i) => i === 0 || cmp(x, sorted[i - 1]) !== 0) : sorted;
2132
+ };
2133
+
2134
+ async function curlCmd(args, sh, io) {
2135
+ if (!sh.fetch) return io.err("curl: this run has no network (only the page has one, through the canvas's network rules)\n"), 6;
2136
+ let method = "";
2137
+ const headers = {};
2138
+ let data;
2139
+ let outFile = "";
2140
+ let url = "";
2141
+ const f = new Set();
2142
+ for (let i = 0; i < args.length; i++) {
2143
+ const a = args[i];
2144
+ const next = () => {
2145
+ if (i + 1 >= args.length) throw new TypeError(`curl: ${a} needs a value`);
2146
+ return args[++i];
2147
+ };
2148
+ if (a === "-X" || a === "--request") method = next().toUpperCase();
2149
+ else if (a === "-H" || a === "--header") {
2150
+ const h = next();
2151
+ const c = h.indexOf(":");
2152
+ if (c <= 0) throw new TypeError(`curl: bad header ${h.slice(0, 30)}`);
2153
+ headers[h.slice(0, c).trim()] = h.slice(c + 1).trim();
2154
+ } else if (a === "-d" || a === "--data" || a === "--data-raw" || a === "--data-binary") data = (data === undefined ? "" : `${data}&`) + next();
2155
+ else if (a === "-o" || a === "--output") outFile = next();
2156
+ else if (a === "-A" || a === "--user-agent") headers["User-Agent"] = next();
2157
+ else if (a === "-I" || a === "--head") f.add("I");
2158
+ else if (/^-[sSiILkfv]+$/.test(a)) [...a.slice(1)].forEach((c) => f.add(c));
2159
+ else if (a === "--silent" || a === "--show-error" || a === "--location" || a === "--include" || a === "--fail") f.add(a.slice(2, 3) === "f" ? "f" : a.slice(2, 3) === "i" ? "i" : "s");
2160
+ else if (a.startsWith("-")) throw new TypeError(`curl: unsupported option ${a.slice(0, 20)}`);
2161
+ else url = a;
2162
+ }
2163
+ if (!/^https?:\/\//i.test(url)) throw new TypeError("curl: a URL starting with http:// or https:// is needed");
2164
+ const verb = method || (f.has("I") ? "HEAD" : data !== undefined ? "POST" : "GET");
2165
+ let res;
2166
+ try {
2167
+ res = await sh.fetch(url, { method: verb, headers, ...(data !== undefined && verb !== "GET" && verb !== "HEAD" ? { body: data } : {}) });
2168
+ } catch (error) {
2169
+ io.err(`curl: (7) ${error?.message ?? String(error)}\n`);
2170
+ return 7;
2171
+ }
2172
+ const buf = new Uint8Array(await res.arrayBuffer());
2173
+ if (buf.byteLength > sh.limits.netBytes) {
2174
+ io.err(`curl: the response is more than ${sh.limits.netBytes} bytes\n`);
2175
+ return 63;
2176
+ }
2177
+ if (f.has("i") || f.has("I")) {
2178
+ io.out(`HTTP ${res.status} ${res.statusText ?? ""}\n`.replace(/ \n$/, "\n"));
2179
+ for (const [k, v] of res.headers?.entries?.() ?? []) io.out(`${k}: ${v}\n`);
2180
+ io.out("\n");
2181
+ }
2182
+ if (f.has("f") && !res.ok) return io.err(`curl: (22) the server answered ${res.status}\n`), 22;
2183
+ if (verb === "HEAD") return 0;
2184
+ if (outFile) {
2185
+ const p = sh.abs(outFile);
2186
+ const bad = nameProblem(baseOf(p)) || (executableBytes(buf.subarray(0, 8)) && `it looks like ${executableBytes(buf.subarray(0, 8))}; this folder does not store programs`);
2187
+ if (bad) throw Object.assign(new Error(bad), { name: "TypeError" });
2188
+ await sh.fs.write(p, buf);
2189
+ if (!f.has("s")) io.err(`saved ${buf.byteLength} bytes to ${outFile}\n`);
2190
+ } else io.out(toText(buf));
2191
+ return 0;
2192
+ }
2193
+
2194
+ const BUILTINS = {
2195
+ ":": () => 0,
2196
+ true: () => 0,
2197
+ false: () => 1,
2198
+ echo: (args, sh, io) => {
2199
+ let nl = true;
2200
+ let esc = false;
2201
+ while (args[0] && /^-[neE]+$/.test(args[0])) {
2202
+ const a = args.shift();
2203
+ if (a.includes("n")) nl = false;
2204
+ if (a.includes("e")) esc = true;
2205
+ }
2206
+ const t = args.join(" ");
2207
+ io.out((esc ? unescape(t) : t) + (nl ? "\n" : ""));
2208
+ },
2209
+ printf: (args, sh, io) => {
2210
+ if (!args.length) throw new TypeError("printf: a format is needed");
2211
+ io.out(formatPrintf(args[0], args.slice(1)));
2212
+ },
2213
+ pwd: (a, sh, io) => io.out(`${sh.cwd}\n`),
2214
+ cd: async (args, sh, io) => {
2215
+ const target = args[0] === "-" ? (sh.vars.get("OLDPWD") ?? "/") : sh.abs(args[0] ?? "/");
2216
+ const st = await sh.fs.stat(target).catch(() => null);
2217
+ if (!st) return io.err(`cd: ${args[0]}: No such file or directory\n`), 1;
2218
+ if (st.type !== "dir") return io.err(`cd: ${args[0]}: Not a directory\n`), 1;
2219
+ sh.vars.set("OLDPWD", sh.cwd);
2220
+ sh.cwd = target;
2221
+ },
2222
+ ls: async (args, sh, io) => {
2223
+ const o = getopts(args, { flags: "al1dFR" });
2224
+ const targets = o.rest.length ? o.rest : ["."];
2225
+ let code = 0;
2226
+ const many = targets.length > 1;
2227
+ for (const t of targets) {
2228
+ const p = sh.abs(t);
2229
+ const st = await sh.fs.stat(p).catch(() => null);
2230
+ if (!st) {
2231
+ io.err(`ls: ${t}: No such file or directory\n`);
2232
+ code = 1;
2233
+ continue;
2234
+ }
2235
+ let entries;
2236
+ if (st.type === "dir" && !o.f.has("d")) {
2237
+ entries = (await sh.fs.list(p)).map((e) => ({ name: e.name, type: e.type, size: e.size ?? 0 }));
2238
+ if (!o.f.has("a")) entries = entries.filter((e) => !e.name.startsWith("."));
2239
+ else entries.unshift({ name: ".", type: "dir", size: 0 }, { name: "..", type: "dir", size: 0 });
2240
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
2241
+ if (many) io.out(`${t}:\n`);
2242
+ } else entries = [{ name: t, type: st.type, size: st.size ?? 0 }];
2243
+ for (const e of entries) {
2244
+ const label = o.f.has("F") && e.type === "dir" ? `${e.name}/` : e.name;
2245
+ io.out(o.f.has("l") ? `${e.type === "dir" ? "d" : "-"} ${String(e.size).padStart(9)} ${label}\n` : `${label}\n`);
2246
+ }
2247
+ if (many) io.out("\n");
2248
+ }
2249
+ return code;
2250
+ },
2251
+ cat: async (args, sh, io) => {
2252
+ const o = getopts(args, { flags: "n" });
2253
+ const { items, bad } = await readFiles(sh, io, o.rest, "cat");
2254
+ let n = 0;
2255
+ for (const it of items) io.out(o.f.has("n") ? lines(it.text).map((l) => `${String(++n).padStart(6)}\t${l}`).join("\n") + (it.text ? "\n" : "") : it.text);
2256
+ return bad ? 1 : 0;
2257
+ },
2258
+ head: async (args, sh, io) => {
2259
+ const o = getopts(args, { values: "n" });
2260
+ const n = Number(o.v.n ?? o.num ?? 10);
2261
+ const { items, bad } = await readFiles(sh, io, o.rest, "head");
2262
+ for (const it of items) io.out(joinLines(lines(it.text).slice(0, n)));
2263
+ return bad ? 1 : 0;
2264
+ },
2265
+ tail: async (args, sh, io) => {
2266
+ const o = getopts(args, { values: "n" });
2267
+ const n = Number(o.v.n ?? o.num ?? 10);
2268
+ const { items, bad } = await readFiles(sh, io, o.rest, "tail");
2269
+ for (const it of items) io.out(joinLines(n === 0 ? [] : lines(it.text).slice(-n)));
2270
+ return bad ? 1 : 0;
2271
+ },
2272
+ wc: async (args, sh, io) => {
2273
+ const o = getopts(args, { flags: "lwc" });
2274
+ const { items, bad } = await readFiles(sh, io, o.rest, "wc");
2275
+ const all = !o.f.size;
2276
+ const row = (t, name) => `${[all || o.f.has("l") ? (t.match(/\n/g) ?? []).length : null, all || o.f.has("w") ? (t.trim() ? t.trim().split(/\s+/).length : 0) : null, all || o.f.has("c") ? sizeOf(t) : null].filter((x) => x !== null).map((x) => String(x).padStart(7)).join(" ")}${name === "-" ? "" : ` ${name}`}\n`;
2277
+ for (const it of items) io.out(row(it.text, it.name));
2278
+ if (items.length > 1) io.out(row(items.map((i) => i.text).join(""), "total"));
2279
+ return bad ? 1 : 0;
2280
+ },
2281
+ grep: async (args, sh, io) => {
2282
+ const o = getopts(args, { flags: "ivncloEFwrHh", values: "e", long: ["color", "colour", "line-number", "ignore-case"] });
2283
+ const patterns = o.v.e !== undefined ? [o.v.e] : [o.rest.shift()];
2284
+ if (patterns[0] === undefined) throw new TypeError("grep: a pattern is needed");
2285
+ const src = o.f.has("F") ? patterns[0].replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : patterns[0];
2286
+ const re = safeRegex(o.f.has("w") ? `\\b(?:${src})\\b` : src, o.f.has("i") || o.f.has("ignore-case") ? "i" : "");
2287
+ let files = o.rest;
2288
+ if (o.f.has("r")) {
2289
+ files = [];
2290
+ for (const t of o.rest.length ? o.rest : ["."]) {
2291
+ const p = sh.abs(t);
2292
+ for (const e of await walkTree(sh, p).catch(() => [])) if (e.type === "file") files.push(t === "." || t === "./" ? e.path.slice(sh.cwd === "/" ? 1 : sh.cwd.length + 1) : e.path.replace(p, t.replace(/\/$/, "")));
2293
+ }
2294
+ }
2295
+ const { items, bad } = await readFiles(sh, io, files, "grep");
2296
+ const showName = (files.length > 1 || o.f.has("r") || o.f.has("H")) && !o.f.has("h");
2297
+ let any = false;
2298
+ for (const it of items) {
2299
+ let count = 0;
2300
+ lines(it.text).forEach((line, idx) => {
2301
+ const hit = re.test(line) !== o.f.has("v");
2302
+ if (!hit) return;
2303
+ count++;
2304
+ any = true;
2305
+ if (o.f.has("c") || o.f.has("l")) return;
2306
+ io.out(`${showName ? `${it.name}:` : ""}${o.f.has("n") || o.f.has("line-number") ? `${idx + 1}:` : ""}${o.f.has("o") && !o.f.has("v") ? (line.match(new RegExp(re.source, re.flags.replace("g", "") + "g")) ?? []).join("\n") : line}\n`);
2307
+ });
2308
+ if (o.f.has("c")) io.out(`${showName ? `${it.name}:` : ""}${count}\n`);
2309
+ else if (o.f.has("l") && count) io.out(`${it.name}\n`);
2310
+ }
2311
+ return bad ? 2 : any ? 0 : 1;
2312
+ },
2313
+ sort: async (args, sh, io) => {
2314
+ const o = getopts(args, { flags: "rnuf", values: "tk" });
2315
+ const { items, bad } = await readFiles(sh, io, o.rest, "sort");
2316
+ io.out(joinLines(sortLines(items.flatMap((i) => lines(i.text)), { r: o.f.has("r"), n: o.f.has("n"), u: o.f.has("u"), f: o.f.has("f"), t: o.v.t, k: o.v.k ? Number(o.v.k.split(",")[0]) : 0 })));
2317
+ return bad ? 2 : 0;
2318
+ },
2319
+ uniq: async (args, sh, io) => {
2320
+ const o = getopts(args, { flags: "cdu" });
2321
+ const { items, bad } = await readFiles(sh, io, o.rest.slice(0, 1), "uniq");
2322
+ const runs = [];
2323
+ for (const l of items.flatMap((i) => lines(i.text))) (runs.at(-1)?.l === l ? runs.at(-1).n++ : runs.push({ l, n: 1 }));
2324
+ for (const r of runs) {
2325
+ if (o.f.has("d") && r.n < 2) continue;
2326
+ if (o.f.has("u") && r.n > 1) continue;
2327
+ io.out(o.f.has("c") ? `${String(r.n).padStart(7)} ${r.l}\n` : `${r.l}\n`);
2328
+ }
2329
+ return bad ? 1 : 0;
2330
+ },
2331
+ cut: async (args, sh, io) => {
2332
+ const o = getopts(args, { flags: "s", values: "dfc" });
2333
+ if (!o.v.f && !o.v.c) throw new TypeError("cut: -f or -c is needed");
2334
+ const pick = cutList(o.v.f ?? o.v.c);
2335
+ const d = o.v.d ?? "\t";
2336
+ const { items, bad } = await readFiles(sh, io, o.rest, "cut");
2337
+ for (const it of items)
2338
+ for (const l of lines(it.text)) {
2339
+ if (o.v.c) io.out(`${[...l].filter((_, i) => pick(i + 1)).join("")}\n`);
2340
+ else if (!l.includes(d)) o.f.has("s") || io.out(`${l}\n`);
2341
+ else io.out(`${l.split(d).filter((_, i) => pick(i + 1)).join(d)}\n`);
2342
+ }
2343
+ return bad ? 1 : 0;
2344
+ },
2345
+ tr: (args, sh, io) => {
2346
+ const o = getopts(args, { flags: "ds" });
2347
+ if (!o.rest.length) throw new TypeError("tr: a set is needed");
2348
+ const a = trSet(o.rest[0]);
2349
+ const b = o.rest[1] === undefined ? "" : trSet(o.rest[1]);
2350
+ const text = slurp(io);
2351
+ let out = "";
2352
+ let prev = "";
2353
+ for (const ch of text) {
2354
+ const at = a.indexOf(ch);
2355
+ let r = ch;
2356
+ if (at >= 0) {
2357
+ if (o.f.has("d")) continue;
2358
+ r = b === "" ? ch : (b[Math.min(at, b.length - 1)] ?? ch);
2359
+ }
2360
+ if (o.f.has("s") && at >= 0 && r === prev) continue;
2361
+ out += r;
2362
+ prev = at >= 0 ? r : "";
2363
+ }
2364
+ io.out(out);
2365
+ },
2366
+ rev: async (args, sh, io) => {
2367
+ const { items, bad } = await readFiles(sh, io, args, "rev");
2368
+ for (const it of items) io.out(joinLines(lines(it.text).map((l) => [...l].reverse().join(""))));
2369
+ return bad ? 1 : 0;
2370
+ },
2371
+ tac: async (args, sh, io) => {
2372
+ const { items, bad } = await readFiles(sh, io, args, "tac");
2373
+ for (const it of items) io.out(joinLines(lines(it.text).reverse()));
2374
+ return bad ? 1 : 0;
2375
+ },
2376
+ sed: async (args, sh, io) => {
2377
+ const script = [];
2378
+ const rest = [];
2379
+ let quiet = false;
2380
+ let inPlace = false;
2381
+ for (let i = 0; i < args.length; i++) {
2382
+ const a = args[i];
2383
+ if (a === "-n") quiet = true;
2384
+ else if (a === "-i") inPlace = true;
2385
+ else if (a === "-e") script.push(args[++i] ?? "");
2386
+ else if (a === "-E" || a === "-r") continue;
2387
+ else if (/^-[nEri]+$/.test(a)) [...a.slice(1)].forEach((c) => (c === "n" ? (quiet = true) : c === "i" ? (inPlace = true) : 0));
2388
+ else if (!script.length && !rest.length) script.push(a);
2389
+ else rest.push(a);
2390
+ }
2391
+ if (!script.length) throw new TypeError("sed: a script is needed");
2392
+ const { items, bad } = await readFiles(sh, io, rest, "sed");
2393
+ for (const it of items) {
2394
+ const out = await sedRun(script, it.text, { quiet });
2395
+ if (inPlace && it.name !== "-") await writeText(sh, sh.abs(it.name), out, false);
2396
+ else io.out(out);
2397
+ }
2398
+ return bad ? 1 : 0;
2399
+ },
2400
+ tee: async (args, sh, io) => {
2401
+ const o = getopts(args, { flags: "a" });
2402
+ const text = slurp(io);
2403
+ io.out(text);
2404
+ for (const f of o.rest) await writeText(sh, sh.abs(f), text, o.f.has("a"));
2405
+ },
2406
+ find: async (args, sh, io) => {
2407
+ const paths = [];
2408
+ let name = "";
2409
+ let type = "";
2410
+ let maxDepth = Infinity;
2411
+ for (let i = 0; i < args.length; i++) {
2412
+ if (args[i] === "-name") name = args[++i] ?? "";
2413
+ else if (args[i] === "-type") type = args[++i] ?? "";
2414
+ else if (args[i] === "-maxdepth") maxDepth = Number(args[++i]);
2415
+ else if (args[i].startsWith("-")) throw new TypeError(`find: unsupported ${args[i]}`);
2416
+ else paths.push(args[i]);
2417
+ }
2418
+ const re = name ? segmentRegex(name, "0".repeat(name.length)) : null;
2419
+ for (const t of paths.length ? paths : ["."]) {
2420
+ const base = sh.abs(t);
2421
+ const st = await sh.fs.stat(base).catch(() => null);
2422
+ if (!st) {
2423
+ io.err(`find: ${t}: No such file or directory\n`);
2424
+ continue;
2425
+ }
2426
+ for (const e of await walkTree(sh, base, { maxDepth })) {
2427
+ if (type === "f" && e.type !== "file") continue;
2428
+ if (type === "d" && e.type !== "dir") continue;
2429
+ if (re && !re.test(baseOf(e.path))) continue;
2430
+ io.out(`${t === "." ? (e.path === sh.cwd ? "." : `./${e.path.slice(sh.cwd === "/" ? 1 : sh.cwd.length + 1)}`) : t.replace(/\/$/, "") + e.path.slice(base === "/" ? 0 : base.length)}\n`.replace(/^\.\/\.\//, "./"));
2431
+ }
2432
+ }
2433
+ },
2434
+ basename: (args, sh, io) => {
2435
+ let b = baseOf(args[0] ?? "");
2436
+ if (args[1] && b.endsWith(args[1]) && b !== args[1]) b = b.slice(0, -args[1].length);
2437
+ io.out(`${b}\n`);
2438
+ },
2439
+ dirname: (args, sh, io) => io.out(`${dirOf(args[0] ?? ".")}\n`.replace(/^\/\n$/, "/\n")),
2440
+ test: async (args, sh) => ((await testExpr(args, sh)) ? 0 : 1),
2441
+ "[": async (args, sh, io) => {
2442
+ if (args.at(-1) !== "]") return io.err("[: missing ]\n"), 2;
2443
+ return (await testExpr(args, sh)) ? 0 : 1;
2444
+ },
2445
+ env: (a, sh, io) => io.out(joinLines([...sh.exported].sort().filter((k) => sh.vars.has(k)).map((k) => `${k}=${sh.vars.get(k)}`))),
2446
+ printenv: (args, sh, io) => {
2447
+ if (args[0]) return sh.exported.has(args[0]) && sh.vars.has(args[0]) ? io.out(`${sh.vars.get(args[0])}\n`) : 1;
2448
+ return BUILTINS.env([], sh, io);
2449
+ },
2450
+ export: (args, sh) => {
2451
+ for (const a of args) {
2452
+ const [k, ...v] = a.split("=");
2453
+ if (v.length) setVar(sh, k, v.join("="));
2454
+ if (!NAME.test(k)) throw new TypeError(`${k}: not a valid name`);
2455
+ sh.exported.add(k);
2456
+ }
2457
+ },
2458
+ set: (args, sh, io) => {
2459
+ if (!args.length) return io.out(joinLines([...sh.vars].sort().map(([k, v]) => `${k}=${v}`)));
2460
+ for (const a of args) {
2461
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(a);
2462
+ if (!m) throw new TypeError(`set: NAME=value (got ${a.slice(0, 20)})`);
2463
+ setVar(sh, m[1], m[2]);
2464
+ }
2465
+ },
2466
+ unset: (args, sh) => {
2467
+ let fns = false;
2468
+ for (const k of args) {
2469
+ if (k === "-f") fns = true;
2470
+ else if (k === "-v") fns = false;
2471
+ else if (fns) sh.funcs.delete(k);
2472
+ else (sh.vars.delete(k), sh.exported.delete(k));
2473
+ }
2474
+ },
2475
+ local: (args, sh) => {
2476
+ const frame = sh.frames.at(-1);
2477
+ if (!frame) throw new TypeError("can only be used in a function");
2478
+ for (const a of args) {
2479
+ const eq = a.indexOf("=");
2480
+ const name = eq < 0 ? a : a.slice(0, eq);
2481
+ if (!NAME.test(name)) throw new TypeError(`${a.slice(0, 30)}: not a valid name`);
2482
+ if (!frame.locals.has(name)) frame.locals.set(name, sh.vars.get(name)); // what to put back when the call ends
2483
+ if (eq < 0) sh.vars.delete(name);
2484
+ else setVar(sh, name, a.slice(eq + 1));
2485
+ }
2486
+ },
2487
+ return: (args, sh) => {
2488
+ if (!sh.frames.length && !sh.sourcing) throw new TypeError("can only `return' from a function or a sourced file");
2489
+ const n = args[0] === undefined ? sh.last : Number(args[0]);
2490
+ if (!Number.isInteger(n)) throw new TypeError(`${String(args[0]).slice(0, 30)}: a number is needed`);
2491
+ throw new Return(n & 255);
2492
+ },
2493
+ shift: (args, sh) => {
2494
+ const n = args[0] === undefined ? 1 : Number(args[0]);
2495
+ if (!Number.isInteger(n) || n < 0) throw new TypeError("a count is needed");
2496
+ const frame = sh.frames.at(-1);
2497
+ if (!frame || n > frame.args.length) return 1;
2498
+ frame.args = frame.args.slice(n);
2499
+ return 0;
2500
+ },
2501
+ jobs: (args, sh, io) => {
2502
+ const list = [...sh.jobs].sort((a, b) => a.id - b.id);
2503
+ const cur = list.at(-1);
2504
+ const prev = list.at(-2);
2505
+ for (const j of list) {
2506
+ const mark = j === cur ? "+" : j === prev ? "-" : " ";
2507
+ io.out(`[${j.id}]${mark} ${jobStatus(j).padEnd(24)}${j.src}${j.status === "running" ? " &" : ""}\n`);
2508
+ }
2509
+ for (const j of list) if (j.status !== "running") sh.jobs.splice(sh.jobs.indexOf(j), 1); // a finished job is shown once
2510
+ return 0;
2511
+ },
2512
+ wait: async (args, sh, io) => {
2513
+ if (!args.length) {
2514
+ await settleJobs(sh, io);
2515
+ return 0;
2516
+ }
2517
+ let code = 0;
2518
+ for (const a of args) {
2519
+ const job = jobBySpec(sh, a);
2520
+ if (!job) {
2521
+ io.err(`wait: ${a.slice(0, 30)}: no such job\n`);
2522
+ code = 127;
2523
+ } else code = await joinJob(sh, job, io);
2524
+ }
2525
+ return code;
2526
+ },
2527
+ fg: async (args, sh, io) => {
2528
+ const job = jobBySpec(sh, args[0]);
2529
+ if (!job) {
2530
+ io.err(args[0] === undefined ? "fg: no current job\n" : `fg: ${args[0].slice(0, 30)}: no such job\n`);
2531
+ return 1;
2532
+ }
2533
+ io.out(`${job.src}\n`);
2534
+ return joinJob(sh, job, io);
2535
+ },
2536
+ bg: (args, sh, io) => {
2537
+ const job = jobBySpec(sh, args[0]);
2538
+ if (!job) {
2539
+ io.err(args[0] === undefined ? "bg: no current job\n" : `bg: ${args[0].slice(0, 30)}: no such job\n`);
2540
+ return 1;
2541
+ }
2542
+ if (job.status !== "running") {
2543
+ io.err(`bg: job ${job.id} has ended\n`);
2544
+ return 1;
2545
+ }
2546
+ io.err(`bg: job ${job.id} already running in the background (a job here starts running at once)\n`);
2547
+ return 0;
2548
+ },
2549
+ kill: (args, sh, io) => {
2550
+ let code = 0;
2551
+ const specs = [];
2552
+ for (let k = 0; k < args.length; k++) {
2553
+ if (args[k] === "-s" || args[k] === "-n") k++;
2554
+ else if (!/^-/.test(args[k])) specs.push(args[k]);
2555
+ }
2556
+ if (!specs.length) throw new TypeError("kill [-signal] %n...");
2557
+ for (const a of specs) {
2558
+ if (!a.startsWith("%")) {
2559
+ io.err(`kill: ${a.slice(0, 30)}: only a background job (%n) of this shell can be stopped; there are no other processes\n`);
2560
+ code = 1;
2561
+ continue;
2562
+ }
2563
+ const job = jobBySpec(sh, a);
2564
+ if (!job) {
2565
+ io.err(`kill: ${a.slice(0, 30)}: no such job\n`);
2566
+ code = 1;
2567
+ } else if (job.status === "running") {
2568
+ job.cancelled = true;
2569
+ job.kill();
2570
+ }
2571
+ }
2572
+ return code;
2573
+ },
2574
+ column: async (args, sh, io) => {
2575
+ const o = getopts(args, { flags: "tx", values: "sco" });
2576
+ const { items, bad } = await readFiles(sh, io, o.rest, "column");
2577
+ const rows = items.flatMap((it) => lines(it.text)).filter((l) => l.trim() !== "");
2578
+ const osep = o.v.o ?? " ";
2579
+ if (o.f.has("t")) {
2580
+ const set = o.v.s;
2581
+ const cells = rows.map((l) => (set === undefined ? l.trim().split(/[ \t]+/) : l.split(new RegExp(`[${[...set].map((c) => c.replace(/[\\\]^-]/g, "\\$&")).join("")}]`))));
2582
+ const w = [];
2583
+ for (const r of cells) r.forEach((c, k) => (w[k] = Math.max(w[k] ?? 0, c.length)));
2584
+ for (const r of cells) io.out(`${r.map((c, k) => (k === r.length - 1 ? c : c.padEnd(w[k]))).join(osep).trimEnd()}\n`);
2585
+ return bad ? 1 : 0;
2586
+ }
2587
+ if (!rows.length) return bad ? 1 : 0;
2588
+ const width = Number(o.v.c) > 0 ? Number(o.v.c) : 80;
2589
+ const cw = Math.max(...rows.map((r) => r.length)) + 2;
2590
+ let ncol = Math.max(1, Math.min(rows.length, Math.floor(width / cw)));
2591
+ const nrow = Math.ceil(rows.length / ncol);
2592
+ ncol = Math.ceil(rows.length / nrow);
2593
+ for (let r = 0; r < nrow; r++) {
2594
+ const row = [];
2595
+ for (let c = 0; c < ncol; c++) {
2596
+ const e = rows[o.f.has("x") ? r * ncol + c : c * nrow + r];
2597
+ if (e !== undefined) row.push(e);
2598
+ }
2599
+ io.out(`${row.map((e, k) => (k === row.length - 1 ? e : e.padEnd(cw))).join("").trimEnd()}\n`);
2600
+ }
2601
+ return bad ? 1 : 0;
2602
+ },
2603
+ md5sum: async (args, sh, io) => {
2604
+ if (!args.length) return io.out(`${md5Hex(enc.encode(slurp(io)))} -\n`), 0;
2605
+ let code = 0;
2606
+ for (const a of args) {
2607
+ try {
2608
+ const bytes = a === "-" ? enc.encode(slurp(io)) : await sh.fs.read(sh.abs(a));
2609
+ if (bytes.byteLength > sh.limits.fileBytes) throw Object.assign(new Error(`more than ${sh.limits.fileBytes} bytes`), { name: "QuotaExceededError" });
2610
+ io.out(`${md5Hex(bytes)} ${a}\n`);
2611
+ } catch (e) {
2612
+ io.err(`md5sum: ${fsMessage(e, a)}\n`);
2613
+ code = 1;
2614
+ }
2615
+ }
2616
+ return code;
2617
+ },
2618
+ cost: (args, sh, io) => viewCost(args, sh, io),
2619
+ memory: (args, sh, io) => viewMemory(args, sh, io),
2620
+ mcp: (args, sh, io) => viewMcp(args, sh, io),
2621
+ rpc: (args, sh, io) => viewRpc(args, sh, io),
2622
+ date: (args, sh, io) => {
2623
+ const utc = args.includes("-u");
2624
+ const fmt = args.find((a) => a.startsWith("+"));
2625
+ const d = new Date(sh.now());
2626
+ io.out(`${args.includes("-I") ? strftime("%F", d, utc) : fmt ? strftime(fmt.slice(1), d, utc) : strftime("%a %b %e %T %Z %Y", d, utc)}\n`);
2627
+ },
2628
+ sleep: async (args, sh) => {
2629
+ const s = Number(args[0]);
2630
+ if (!Number.isFinite(s) || s < 0) throw new TypeError("sleep: seconds");
2631
+ const ms = Math.min(s * 1000, sh.limits.sleepMs);
2632
+ const t0 = sh.now();
2633
+ await sh.sleep(ms);
2634
+ sh.started += sh.now() - t0; // a wait is not work: it does not use up the line's time
2635
+ },
2636
+ seq: (args, sh, io) => {
2637
+ const n = args.map(Number);
2638
+ if (!n.length || n.length > 3 || n.some((x) => !Number.isFinite(x))) throw new TypeError("seq: [first [step]] last");
2639
+ const [first, step, last] = n.length === 1 ? [1, 1, n[0]] : n.length === 2 ? [n[0], 1, n[1]] : n;
2640
+ if (step === 0) throw new TypeError("seq: a step of 0");
2641
+ const out = [];
2642
+ for (let v = first; step > 0 ? v <= last : v >= last; v += step) if (out.push(String(v)) > sh.limits.loop * 10) throw new Stop("stopped: seq is too long");
2643
+ io.out(joinLines(out));
2644
+ },
2645
+ jq: async (args, sh, io) => {
2646
+ const o = getopts(args, { flags: "rcsnR", long: ["raw-output", "compact-output", "slurp", "null-input"] });
2647
+ const filter = o.rest.shift();
2648
+ if (filter === undefined) throw new TypeError("jq: a filter is needed");
2649
+ const { items, bad } = await readFiles(sh, io, o.rest, "jq");
2650
+ const raw = o.f.has("r") || o.f.has("raw-output");
2651
+ const compact = o.f.has("c") || o.f.has("compact-output");
2652
+ const program = jqCompile(filter);
2653
+ const docs = o.f.has("n") || o.f.has("null-input") ? [null] : items.flatMap((i) => jqParseDocs(i.text));
2654
+ const inputs = o.f.has("s") || o.f.has("slurp") ? [docs] : docs;
2655
+ for (const doc of inputs) {
2656
+ for (const v of program(doc)) io.out(`${raw && typeof v === "string" ? v : JSON.stringify(v, null, compact ? undefined : 2)}\n`);
2657
+ }
2658
+ return bad ? 2 : 0;
2659
+ },
2660
+ curl: curlCmd,
2661
+ xargs: async (args, sh, io) => {
2662
+ const v = {};
2663
+ let at = 0;
2664
+ for (; at < args.length && args[at].startsWith("-") && args[at] !== "--"; at++) {
2665
+ if (args[at] === "-n" || args[at] === "-I") v[args[at][1]] = args[++at];
2666
+ else if (/^-[nI]./.test(args[at])) v[args[at][1]] = args[at].slice(2);
2667
+ else if (args[at] !== "-r" && args[at] !== "-0") throw new TypeError(`xargs: unknown option ${args[at]}`);
2668
+ }
2669
+ if (args[at] === "--") at++;
2670
+ const cmd = args.length > at ? args.slice(at) : ["echo"];
2671
+ const items = slurp(io).split(/\s+/).filter(Boolean);
2672
+ if (!items.length) return 0;
2673
+ const n = Number(v.n);
2674
+ if (v.n !== undefined && !(n >= 1)) throw new TypeError("xargs: -n needs a number");
2675
+ const groups = v.I ? items.map((x) => [x]) : v.n ? Array.from({ length: Math.ceil(items.length / n) }, (_, i) => items.slice(i * n, (i + 1) * n)) : [items];
2676
+ let code = 0;
2677
+ for (const g of groups) {
2678
+ const argv = v.I ? cmd.map((c) => c.split(v.I).join(g[0])) : [...cmd, ...g];
2679
+ code = (await callBuiltin(argv[0], argv.slice(1), sh, { in: null, out: io.out, err: io.err })) || code;
2680
+ }
2681
+ return code;
2682
+ },
2683
+ which: (args, sh, io, say = (a) => `${a}: shell function`) => {
2684
+ let code = 0;
2685
+ for (const a of args) {
2686
+ if (sh.funcs.has(a)) io.out(`${say(a)}\n`);
2687
+ else Object.hasOwn(BUILTINS, a) ? io.out(`${a}: shell builtin\n`) : (io.err(`${a}: not found\n`), (code = 1));
2688
+ }
2689
+ return code;
2690
+ },
2691
+ type: (args, sh, io) => BUILTINS.which(args, sh, io, (a) => `${a} is a function`),
2692
+ command: (args, sh, io) => (args[0] === "-v" ? BUILTINS.which(args.slice(1), sh, io) : callBuiltin(args[0] ?? ":", args.slice(1), sh, io)),
2693
+ help: (args, sh, io) => {
2694
+ if (args[0]) {
2695
+ const u = USAGE[args[0]];
2696
+ return u ? io.out(`${u}\n`) : (io.err(`help: no help for ${args[0].slice(0, 30)}\n`), 1);
2697
+ }
2698
+ io.out(`clsh ${VERSION}: pipes |, && || ; &, > >> < << <<< 2> 2>&1, quotes, $VAR $(cmd) $((1+2)), * ? [..] {a,b} globs and braces, if/for/while, name() { ...; } functions.\nIt runs in the sandbox over this canvas's folder, and nothing here runs a program.\nCommands: ${Object.keys(BUILTINS).filter((n) => USAGE[n]).sort().join(" ")}\n"help name" says what one does.\n`);
2699
+ },
2700
+ history: (a, sh, io) => io.out(joinLines(sh.history.map((l, i) => `${String(i + 1).padStart(5)} ${l}`))),
2701
+ clear: (a, sh) => void sh.effects.push({ type: "clear" }),
2702
+ exit: (args) => {
2703
+ throw new Exit(Number.isFinite(Number(args[0])) ? Number(args[0]) & 255 : 0);
2704
+ },
2705
+ read: (args, sh, io) => {
2706
+ const names = args.filter((a) => !a.startsWith("-"));
2707
+ if (!io.in || io.in.pos >= io.in.text.length) return 1;
2708
+ const end = io.in.text.indexOf("\n", io.in.pos);
2709
+ const line = io.in.text.slice(io.in.pos, end < 0 ? undefined : end);
2710
+ io.in.pos = end < 0 ? io.in.text.length : end + 1;
2711
+ const words = line.split(/[ \t]+/).filter((_, i) => true);
2712
+ (names.length ? names : ["REPLY"]).forEach((n, i, all) => setVar(sh, n, i === all.length - 1 ? words.slice(i).join(" ") : (words[i] ?? "")));
2713
+ },
2714
+ source: async (args, sh, io) => {
2715
+ if (!args[0]) throw new TypeError("source: a file");
2716
+ if (sh.depth >= sh.limits.depth) throw new Stop(`stopped: source nested more than ${sh.limits.depth} deep`);
2717
+ const text = toText(await sh.fs.read(sh.abs(args[0])));
2718
+ sh.depth++;
2719
+ sh.sourcing = (sh.sourcing ?? 0) + 1;
2720
+ try {
2721
+ return await execList(parse(text), sh, io);
2722
+ } catch (error) {
2723
+ if (error instanceof Return) return error.code; // `return` ends a sourced file
2724
+ throw error;
2725
+ } finally {
2726
+ sh.depth--;
2727
+ sh.sourcing--;
2728
+ }
2729
+ },
2730
+ stat: async (args, sh, io) => {
2731
+ let code = 0;
2732
+ for (const a of args) {
2733
+ const st = await sh.fs.stat(sh.abs(a)).catch(() => null);
2734
+ if (!st) (io.err(`stat: ${a}: No such file or directory\n`), (code = 1));
2735
+ else io.out(` File: ${a}\n Type: ${st.type === "dir" ? "folder" : "file"}\n Size: ${st.size ?? 0}\n`);
2736
+ }
2737
+ return code;
2738
+ },
2739
+ touch: async (args, sh) => {
2740
+ for (const a of args) if (!(await sh.fs.exists(sh.abs(a)).catch(() => false))) await writeText(sh, sh.abs(a), "", false);
2741
+ },
2742
+ mkdir: async (args, sh, io) => {
2743
+ const o = getopts(args, { flags: "p" });
2744
+ let code = 0;
2745
+ for (const a of o.rest) {
2746
+ const p = sh.abs(a);
2747
+ const bad = nameProblem(baseOf(p).replace(/\.(sh|bash)$/i, "_"));
2748
+ if (bad) (io.err(`mkdir: ${a}: ${bad}\n`), (code = 1));
2749
+ else if (o.f.has("p")) {
2750
+ let at = "";
2751
+ for (const part of p.split("/").filter(Boolean)) {
2752
+ at += `/${part}`;
2753
+ if (!(await sh.fs.exists(at).catch(() => false))) await sh.fs.mkdir(at);
2754
+ }
2755
+ } else if (await sh.fs.exists(p).catch(() => false)) (io.err(`mkdir: ${a}: File exists\n`), (code = 1));
2756
+ else if (!(await sh.fs.stat(dirOf(p)).catch(() => null))) (io.err(`mkdir: ${a}: No such file or directory\n`), (code = 1));
2757
+ else await sh.fs.mkdir(p);
2758
+ }
2759
+ return code;
2760
+ },
2761
+ rmdir: async (args, sh, io) => {
2762
+ let code = 0;
2763
+ for (const a of args) {
2764
+ const p = sh.abs(a);
2765
+ const list = await sh.fs.list(p).catch(() => null);
2766
+ if (list === null) (io.err(`rmdir: ${a}: No such folder\n`), (code = 1));
2767
+ else if (list.length) (io.err(`rmdir: ${a}: Folder not empty\n`), (code = 1));
2768
+ else if (p === "/") (io.err("rmdir: the folder itself can't be removed\n"), (code = 1));
2769
+ else await sh.fs.remove(p, false);
2770
+ }
2771
+ return code;
2772
+ },
2773
+ rm: async (args, sh, io) => {
2774
+ const o = getopts(args, { flags: "rRf" });
2775
+ let code = 0;
2776
+ for (const a of o.rest) {
2777
+ const p = sh.abs(a);
2778
+ if (p === "/") (io.err("rm: the folder itself can't be removed, only what is in it\n"), (code = 1));
2779
+ else {
2780
+ const st = await sh.fs.stat(p).catch(() => null);
2781
+ if (!st) o.f.has("f") || (io.err(`rm: ${a}: No such file or directory\n`), (code = 1));
2782
+ else if (st.type === "dir" && !(o.f.has("r") || o.f.has("R"))) (io.err(`rm: ${a}: is a folder (use -r)\n`), (code = 1));
2783
+ else {
2784
+ await sh.fs.remove(p, st.type === "dir");
2785
+ if (sh.cwd === p || sh.cwd.startsWith(`${p}/`)) sh.cwd = dirOf(p);
2786
+ }
2787
+ }
2788
+ }
2789
+ return code;
2790
+ },
2791
+ cp: async (args, sh, io) => {
2792
+ const o = getopts(args, { flags: "rR" });
2793
+ if (o.rest.length < 2) throw new TypeError("cp: source and target");
2794
+ const dest = sh.abs(o.rest.at(-1));
2795
+ const dst = await sh.fs.stat(dest).catch(() => null);
2796
+ const srcs = o.rest.slice(0, -1);
2797
+ if (srcs.length > 1 && dst?.type !== "dir") throw new TypeError("cp: the target must be a folder");
2798
+ for (const s of srcs) {
2799
+ const from = sh.abs(s);
2800
+ const st = await sh.fs.stat(from);
2801
+ const to = dst?.type === "dir" ? joinP(dest, baseOf(from)) : dest;
2802
+ if (to === from || to.startsWith(`${from}/`)) throw new TypeError(`cp: ${s}: can't copy into itself`);
2803
+ if (st.type === "dir") {
2804
+ if (!(o.f.has("r") || o.f.has("R"))) throw new TypeError(`cp: ${s} is a folder (use -r)`);
2805
+ await copyTree(sh, from, to, io, "cp");
2806
+ } else await copyOne(sh, from, to, io, "cp");
2807
+ }
2808
+ },
2809
+ mv: async (args, sh, io) => {
2810
+ if (args.length < 2) throw new TypeError("mv: source and target");
2811
+ const dest = sh.abs(args.at(-1));
2812
+ const dst = await sh.fs.stat(dest).catch(() => null);
2813
+ const srcs = args.slice(0, -1);
2814
+ if (srcs.length > 1 && dst?.type !== "dir") throw new TypeError("mv: the target must be a folder");
2815
+ for (const s of srcs) {
2816
+ const from = sh.abs(s);
2817
+ if (from === "/") throw new TypeError("mv: the folder itself can't be moved");
2818
+ const st = await sh.fs.stat(from);
2819
+ const to = dst?.type === "dir" ? joinP(dest, baseOf(from)) : dest;
2820
+ if (to === from) continue;
2821
+ if (to.startsWith(`${from}/`)) throw new TypeError("mv: a folder can't be moved into itself");
2822
+ if (dst && dst.type !== "dir") await sh.fs.remove(to, false);
2823
+ if (st.type === "dir") await copyTree(sh, from, to, io, "mv");
2824
+ else await copyOne(sh, from, to, io, "mv");
2825
+ await sh.fs.remove(from, st.type === "dir");
2826
+ }
2827
+ },
2828
+ base64: async (args, sh, io) => {
2829
+ const o = getopts(args, { flags: "d" });
2830
+ if (o.f.has("d")) {
2831
+ const { items } = await readFiles(sh, io, o.rest, "base64");
2832
+ io.out(toText(b64.dec(items.map((i) => i.text).join(""))));
2833
+ } else {
2834
+ if (o.rest.length) {
2835
+ const bytes = await sh.fs.read(sh.abs(o.rest[0]));
2836
+ io.out(`${b64.enc(bytes)}\n`);
2837
+ } else io.out(`${b64.enc(enc.encode(slurp(io)))}\n`);
2838
+ }
2839
+ },
2840
+ sha256sum: async (args, sh, io) => {
2841
+ if (!args.length) return io.out(`${await sha256Hex(enc.encode(slurp(io)))} -\n`), 0;
2842
+ for (const a of args) io.out(`${await sha256Hex(await sh.fs.read(sh.abs(a)))} ${a}\n`);
2843
+ },
2844
+ realpath: (args, sh, io) => args.forEach((a) => io.out(`${sh.abs(a)}\n`)),
2845
+ nl: async (args, sh, io) => {
2846
+ const { items, bad } = await readFiles(sh, io, args, "nl");
2847
+ let n = 0;
2848
+ for (const it of items) for (const l of lines(it.text)) io.out(l === "" ? "\n" : `${String(++n).padStart(6)}\t${l}\n`);
2849
+ return bad ? 1 : 0;
2850
+ },
2851
+ paste: async (args, sh, io) => {
2852
+ const o = getopts(args, { values: "d" });
2853
+ const { items, bad } = await readFiles(sh, io, o.rest, "paste");
2854
+ const cols = items.map((i) => lines(i.text));
2855
+ const d = o.v.d ?? "\t";
2856
+ for (let i = 0; i < Math.max(0, ...cols.map((c) => c.length)); i++) io.out(`${cols.map((c) => c[i] ?? "").join(d)}\n`);
2857
+ return bad ? 1 : 0;
2858
+ },
2859
+ fold: async (args, sh, io) => {
2860
+ const o = getopts(args, { values: "w" });
2861
+ const w = Number(o.v.w ?? 80);
2862
+ if (!(w >= 1)) throw new TypeError("fold: -w needs a number");
2863
+ const { items, bad } = await readFiles(sh, io, o.rest, "fold");
2864
+ for (const it of items) for (const l of lines(it.text)) for (let i = 0; i === 0 || i < l.length; i += w) io.out(`${l.slice(i, i + w)}\n`);
2865
+ return bad ? 1 : 0;
2866
+ },
2867
+ du: async (args, sh, io) => {
2868
+ const o = getopts(args, { flags: "sh" });
2869
+ for (const t of o.rest.length ? o.rest : ["."]) {
2870
+ const entries = await walkTree(sh, sh.abs(t)).catch((e) => (io.err(`du: ${fsMessage(e, t)}\n`), []));
2871
+ const total = entries.reduce((n, e) => n + (e.type === "dir" ? 0 : e.size), 0);
2872
+ io.out(`${o.f.has("h") ? (total < 1024 ? `${total}B` : total < 1048576 ? `${(total / 1024).toFixed(1)}K` : `${(total / 1048576).toFixed(1)}M`) : total}\t${t}\n`);
2873
+ }
2874
+ },
2875
+ tree: async (args, sh, io) => {
2876
+ const root = sh.abs(args[0] ?? ".");
2877
+ const walk = async (dir, prefix, depth) => {
2878
+ if (depth > 8) return;
2879
+ tick(sh);
2880
+ const entries = (await sh.fs.list(dir)).filter((e) => !e.name.startsWith(".")).sort((a, b) => (a.name < b.name ? -1 : 1));
2881
+ for (const [i, e] of entries.entries()) {
2882
+ io.out(`${prefix}${i === entries.length - 1 ? "└── " : "├── "}${e.name}${e.type === "dir" ? "/" : ""}\n`);
2883
+ if (e.type === "dir") await walk(joinP(dir, e.name), `${prefix}${i === entries.length - 1 ? " " : "│ "}`, depth + 1);
2884
+ }
2885
+ };
2886
+ io.out(`${args[0] ?? "."}\n`);
2887
+ await walk(root, "", 0);
2888
+ },
2889
+ diff: async (args, sh, io) => {
2890
+ if (args.length !== 2) throw new TypeError("diff: two files");
2891
+ const { items, bad } = await readFiles(sh, io, args, "diff");
2892
+ if (bad) return 2;
2893
+ const [a, b] = items.map((i) => lines(i.text));
2894
+ if (a.length * b.length > 4_000_000) throw new Stop("stopped: those files are too long to compare here");
2895
+ const m = Array.from({ length: a.length + 1 }, () => new Int32Array(b.length + 1));
2896
+ for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) m[i][j] = a[i] === b[j] ? m[i + 1][j + 1] + 1 : Math.max(m[i + 1][j], m[i][j + 1]);
2897
+ let i = 0;
2898
+ let j = 0;
2899
+ let differs = false;
2900
+ while (i < a.length || j < b.length) {
2901
+ if (i < a.length && j < b.length && a[i] === b[j]) (i++, j++);
2902
+ else if (j >= b.length || (i < a.length && m[i + 1][j] >= m[i][j + 1])) (io.out(`< ${a[i++]}\n`), (differs = true));
2903
+ else (io.out(`> ${b[j++]}\n`), (differs = true));
2904
+ }
2905
+ return differs ? 1 : 0;
2906
+ },
2907
+ yes: (args, sh, io) => {
2908
+ const t = `${args.join(" ") || "y"}\n`;
2909
+ for (let i = 0; i < sh.limits.loop; i++) io.out(t);
2910
+ },
2911
+ xxd: async (args, sh, io) => {
2912
+ const bytes = args.length ? await sh.fs.read(sh.abs(args[0])) : enc.encode(slurp(io));
2913
+ for (let off = 0; off < Math.min(bytes.length, 65536); off += 16) {
2914
+ const row = bytes.subarray(off, off + 16);
2915
+ io.out(`${off.toString(16).padStart(8, "0")}: ${[...row].map((b, k) => b.toString(16).padStart(2, "0") + (k % 2 ? " " : "")).join("").padEnd(40)} ${[...row].map((b) => (b >= 32 && b < 127 ? String.fromCharCode(b) : ".")).join("")}\n`);
2916
+ }
2917
+ },
2918
+ time: async (args, sh, io) => {
2919
+ const t0 = sh.now();
2920
+ const code = args.length ? await callBuiltin(args[0], args.slice(1), sh, io) : 0;
2921
+ io.err(`\nreal ${((sh.now() - t0) / 1000).toFixed(3)}s\n`);
2922
+ return code;
2923
+ },
2924
+ alias: (args, sh, io) => {
2925
+ sh.aliases ??= new Map();
2926
+ if (!args.length) return io.out(joinLines([...sh.aliases].sort().map(([k, v]) => `alias ${k}='${v}'`)));
2927
+ for (const a of args) {
2928
+ const m = /^([A-Za-z_][A-Za-z0-9_-]*)=(.*)$/s.exec(a);
2929
+ if (!m) {
2930
+ if (!sh.aliases.has(a)) return io.err(`alias: ${a}: not found\n`), 1;
2931
+ io.out(`alias ${a}='${sh.aliases.get(a)}'\n`);
2932
+ } else if (sh.aliases.size >= 100) throw new Stop("stopped: at most 100 aliases");
2933
+ else sh.aliases.set(m[1], m[2].slice(0, 1000));
2934
+ }
2935
+ },
2936
+ unalias: (args, sh) => args.forEach((a) => sh.aliases?.delete(a)),
2937
+ clawser: clawserCmd,
2938
+ snapshot: snapshotCmd,
2939
+ };
2940
+ BUILTINS[".."] = undefined;
2941
+ delete BUILTINS[".."];
2942
+ BUILTINS["."] = BUILTINS.source;
2943
+ export const COMMANDS = Object.freeze(Object.keys(BUILTINS).filter((n) => n !== "." && n !== ":" && n !== "["));
2944
+
2945
+ // ── jq (a small subset, written from jq's manual) ───────────────────────────────────────────────────
2946
+
2947
+ /** The JSON documents in some text (one or several, whitespace-separated). */
2948
+ export function jqParseDocs(text) {
2949
+ const t = text.trim();
2950
+ if (!t) return [];
2951
+ try {
2952
+ return [JSON.parse(t)];
2953
+ } catch (first) {
2954
+ const docs = [];
2955
+ let i = 0;
2956
+ while (i < t.length) {
2957
+ while (i < t.length && /\s/.test(t[i])) i++;
2958
+ if (i >= t.length) break;
2959
+ let depth = 0;
2960
+ let j = i;
2961
+ let inStr = false;
2962
+ for (; j < t.length; j++) {
2963
+ const c = t[j];
2964
+ if (inStr) {
2965
+ if (c === "\\") j++;
2966
+ else if (c === '"') inStr = false;
2967
+ } else if (c === '"') inStr = true;
2968
+ else if (c === "{" || c === "[") depth++;
2969
+ else if (c === "}" || c === "]") depth--;
2970
+ else if (depth === 0 && /\s/.test(c)) break;
2971
+ if (depth === 0 && !inStr && (c === "}" || c === "]" || (c === '"' && j > i))) {
2972
+ j++;
2973
+ break;
2974
+ }
2975
+ }
2976
+ try {
2977
+ docs.push(JSON.parse(t.slice(i, j)));
2978
+ } catch {
2979
+ throw new SyntaxError(`jq: the input is not JSON (${first.message})`);
2980
+ }
2981
+ i = j;
2982
+ }
2983
+ return docs;
2984
+ }
2985
+ }
2986
+
2987
+ const jqTruthy = (v) => v !== null && v !== false;
2988
+ const jqType = (v) => (v === null ? "null" : Array.isArray(v) ? "array" : typeof v);
2989
+ const jqOrder = (v) => ({ null: 0, boolean: 1, number: 2, string: 3, array: 4, object: 5 })[jqType(v)];
2990
+ function jqCompare(a, b) {
2991
+ const ta = jqOrder(a);
2992
+ const tb = jqOrder(b);
2993
+ if (ta !== tb) return ta - tb;
2994
+ if (Array.isArray(a)) {
2995
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
2996
+ const c = jqCompare(a[i], b[i]);
2997
+ if (c) return c;
2998
+ }
2999
+ return a.length - b.length;
3000
+ }
3001
+ if (jqType(a) === "object") return jqCompare(Object.keys(a).sort().map((k) => [k, a[k]]), Object.keys(b).sort().map((k) => [k, b[k]]));
3002
+ return a === b ? 0 : a < b ? -1 : 1;
3003
+ }
3004
+ const jqErr = (m) => Object.assign(new TypeError(`jq: ${m}`), { name: "TypeError" });
3005
+
3006
+ const JQ_FUNCS = {
3007
+ length: (v) => [v === null ? 0 : typeof v === "string" ? [...v].length : Array.isArray(v) ? v.length : typeof v === "object" ? Object.keys(v).length : Math.abs(v)],
3008
+ keys: (v) => [Array.isArray(v) ? v.map((_, i) => i) : Object.keys(v ?? {}).sort()],
3009
+ values: (v) => (v === null ? [] : [v]),
3010
+ not: (v) => [!jqTruthy(v)],
3011
+ empty: () => [],
3012
+ add: (v) => [(Array.isArray(v) ? v : Object.values(v ?? {})).reduce((a, b) => (a === null ? b : b === null ? a : Array.isArray(a) ? a.concat(b) : typeof a === "object" && typeof b === "object" ? { ...a, ...b } : a + b), null)],
3013
+ sort: (v) => [[...v].sort(jqCompare)],
3014
+ unique: (v) => [[...v].sort(jqCompare).filter((x, i, a) => i === 0 || jqCompare(x, a[i - 1]) !== 0)],
3015
+ reverse: (v) => [typeof v === "string" ? [...v].reverse().join("") : [...v].reverse()],
3016
+ first: (v) => [v[0] ?? null],
3017
+ last: (v) => [v.at(-1) ?? null],
3018
+ min: (v) => [v.length ? [...v].sort(jqCompare)[0] : null],
3019
+ max: (v) => [v.length ? [...v].sort(jqCompare).at(-1) : null],
3020
+ type: (v) => [jqType(v)],
3021
+ tostring: (v) => [typeof v === "string" ? v : JSON.stringify(v)],
3022
+ tonumber: (v) => {
3023
+ const n = typeof v === "number" ? v : Number(v);
3024
+ if (!Number.isFinite(n)) throw jqErr(`cannot convert ${JSON.stringify(v)} to a number`);
3025
+ return [n];
3026
+ },
3027
+ tojson: (v) => [JSON.stringify(v)],
3028
+ fromjson: (v) => [JSON.parse(v)],
3029
+ to_entries: (v) => [Object.entries(v).map(([key, value]) => ({ key, value }))],
3030
+ from_entries: (v) => [Object.fromEntries(v.map((e) => [String(e.key ?? e.name ?? e.k), e.value ?? e.v ?? null]))],
3031
+ flatten: (v) => [v.flat(Infinity)],
3032
+ ascii_downcase: (v) => [v.toLowerCase()],
3033
+ ascii_upcase: (v) => [v.toUpperCase()],
3034
+ floor: (v) => [Math.floor(v)],
3035
+ ceil: (v) => [Math.ceil(v)],
3036
+ round: (v) => [Math.round(v)],
3037
+ abs: (v) => [Math.abs(v)],
3038
+ any: (v) => [v.some(jqTruthy)],
3039
+ all: (v) => [v.every(jqTruthy)],
3040
+ };
3041
+ const JQ_FUNCS_ARGS = {
3042
+ map: (f) => (v) => [(Array.isArray(v) ? v : Object.values(v)).flatMap((x) => f(x))],
3043
+ select: (f) => (v) => (f(v).some(jqTruthy) ? [v] : []),
3044
+ sort_by: (f) => (v) => [[...v].sort((a, b) => jqCompare(f(a)[0], f(b)[0]))],
3045
+ group_by: (f) => (v) => {
3046
+ const sorted = [...v].sort((a, b) => jqCompare(f(a)[0], f(b)[0]));
3047
+ const out = [];
3048
+ for (const x of sorted) (out.length && jqCompare(f(out.at(-1)[0])[0], f(x)[0]) === 0 ? out.at(-1).push(x) : out.push([x]));
3049
+ return [out];
3050
+ },
3051
+ unique_by: (f) => (v) => [[...v].sort((a, b) => jqCompare(f(a)[0], f(b)[0])).filter((x, i, a) => i === 0 || jqCompare(f(x)[0], f(a[i - 1])[0]) !== 0)],
3052
+ min_by: (f) => (v) => [v.length ? [...v].sort((a, b) => jqCompare(f(a)[0], f(b)[0]))[0] : null],
3053
+ max_by: (f) => (v) => [v.length ? [...v].sort((a, b) => jqCompare(f(a)[0], f(b)[0])).at(-1) : null],
3054
+ has: (f) => (v) => f(v).map((k) => (Array.isArray(v) ? Number.isInteger(k) && k >= 0 && k < v.length : v !== null && typeof v === "object" && Object.hasOwn(v, k))),
3055
+ join: (f) => (v) => f(v).map((s) => v.map((x) => (x === null ? "" : typeof x === "string" ? x : JSON.stringify(x))).join(s)),
3056
+ split: (f) => (v) => f(v).map((s) => v.split(s)),
3057
+ startswith: (f) => (v) => f(v).map((s) => v.startsWith(s)),
3058
+ endswith: (f) => (v) => f(v).map((s) => v.endsWith(s)),
3059
+ ltrimstr: (f) => (v) => f(v).map((s) => (typeof v === "string" && v.startsWith(s) ? v.slice(s.length) : v)),
3060
+ rtrimstr: (f) => (v) => f(v).map((s) => (typeof v === "string" && s !== "" && v.endsWith(s) ? v.slice(0, -s.length) : v)),
3061
+ contains: (f) => (v) => f(v).map((s) => (typeof v === "string" ? v.includes(s) : Array.isArray(v) ? s.every((x) => v.some((y) => jqCompare(x, y) === 0)) : JSON.stringify(v) === JSON.stringify(s))),
3062
+ test: (f) => (v) => f(v).map((s) => safeRegex(s).test(v)),
3063
+ range: (f) => (v) => f(v).flatMap((n) => Array.from({ length: Math.min(Math.max(0, n), 100000) }, (_, i) => i)),
3064
+ limit: null,
3065
+ del: null,
3066
+ };
3067
+
3068
+ /** A jq filter as a function: input -> array of outputs. */
3069
+ export function jqCompile(src) {
3070
+ const toks = [];
3071
+ for (let i = 0; i < src.length; ) {
3072
+ const c = src[i];
3073
+ if (/\s/.test(c)) i++;
3074
+ else if (c === '"') {
3075
+ let s = "";
3076
+ i++;
3077
+ while (i < src.length && src[i] !== '"') {
3078
+ if (src[i] === "\\") {
3079
+ const n = src[i + 1];
3080
+ s += n === "n" ? "\n" : n === "t" ? "\t" : n === "u" ? String.fromCharCode(parseInt(src.slice(i + 2, i + 6), 16)) : n;
3081
+ i += n === "u" ? 6 : 2;
3082
+ } else s += src[i++];
3083
+ }
3084
+ if (src[i] !== '"') throw new SyntaxError("jq: unclosed string");
3085
+ i++;
3086
+ toks.push({ t: "str", v: s });
3087
+ } else if (/[0-9]/.test(c)) {
3088
+ const m = /^[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?/.exec(src.slice(i));
3089
+ toks.push({ t: "num", v: Number(m[0]) });
3090
+ i += m[0].length;
3091
+ } else if (c === "." && /[A-Za-z_]/.test(src[i + 1] ?? "")) {
3092
+ const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(src.slice(i + 1));
3093
+ toks.push({ t: "field", v: m[0] });
3094
+ i += 1 + m[0].length;
3095
+ } else if (/[A-Za-z_]/.test(c)) {
3096
+ const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(src.slice(i));
3097
+ toks.push({ t: "id", v: m[0] });
3098
+ i += m[0].length;
3099
+ } else {
3100
+ const three = src.slice(i, i + 2);
3101
+ if (["==", "!=", "<=", ">=", "//", ".."].includes(three)) (toks.push({ t: "op", v: three }), (i += 2));
3102
+ else (toks.push({ t: "op", v: c }), i++);
3103
+ }
3104
+ }
3105
+ let p = 0;
3106
+ const peek = () => toks[p];
3107
+ const op = (v) => peek()?.t === "op" && peek().v === v;
3108
+ const eat = (v) => {
3109
+ if (!op(v)) throw new SyntaxError(`jq: expected "${v}"`);
3110
+ p++;
3111
+ };
3112
+ const guard = (() => {
3113
+ let n = 0;
3114
+ return () => {
3115
+ if (++n > 200000) throw new Stop("stopped: jq ran too long");
3116
+ };
3117
+ })();
3118
+ const parsePipe = () => {
3119
+ let l = parseComma();
3120
+ while (op("|")) (p++, (l = pipe(l, parseComma())));
3121
+ return l;
3122
+ };
3123
+ const pipe = (a, b) => (v) => a(v).flatMap((x) => (guard(), b(x)));
3124
+ const parseComma = () => {
3125
+ let l = parseAlt();
3126
+ while (op(",")) {
3127
+ p++;
3128
+ const a = l;
3129
+ const b = parseAlt();
3130
+ l = (v) => [...a(v), ...b(v)];
3131
+ }
3132
+ return l;
3133
+ };
3134
+ const bin = (a, b, f) => (v) => b(v).flatMap((y) => a(v).map((x) => f(x, y)));
3135
+ const parseAlt = () => {
3136
+ let l = parseOr();
3137
+ while (op("//")) {
3138
+ p++;
3139
+ const a = l;
3140
+ const b = parseOr();
3141
+ l = (v) => {
3142
+ let r;
3143
+ try {
3144
+ r = a(v).filter(jqTruthy);
3145
+ } catch {
3146
+ r = [];
3147
+ }
3148
+ return r.length ? r : b(v);
3149
+ };
3150
+ }
3151
+ return l;
3152
+ };
3153
+ const kw = (w) => peek()?.t === "id" && peek().v === w;
3154
+ const parseOr = () => {
3155
+ let l = parseAnd();
3156
+ while (kw("or")) (p++, (l = bin(l, parseAnd(), (x, y) => jqTruthy(x) || jqTruthy(y))));
3157
+ return l;
3158
+ };
3159
+ const parseAnd = () => {
3160
+ let l = parseCmp();
3161
+ while (kw("and")) (p++, (l = bin(l, parseCmp(), (x, y) => jqTruthy(x) && jqTruthy(y))));
3162
+ return l;
3163
+ };
3164
+ const parseCmp = () => {
3165
+ const l = parseAdd();
3166
+ const t = peek();
3167
+ if (t?.t === "op" && ["==", "!=", "<", ">", "<=", ">="].includes(t.v)) {
3168
+ p++;
3169
+ const r = parseAdd();
3170
+ const f = { "==": (c) => c === 0, "!=": (c) => c !== 0, "<": (c) => c < 0, ">": (c) => c > 0, "<=": (c) => c <= 0, ">=": (c) => c >= 0 }[t.v];
3171
+ return bin(l, r, (x, y) => f(jqCompare(x, y)));
3172
+ }
3173
+ return l;
3174
+ };
3175
+ const arith = (x, y, o) => {
3176
+ if (o === "+") return x === null ? y : y === null ? x : Array.isArray(x) && Array.isArray(y) ? x.concat(y) : jqType(x) === "object" && jqType(y) === "object" ? { ...x, ...y } : typeof x === "number" && typeof y === "number" ? x + y : typeof x === "string" && typeof y === "string" ? x + y : (() => { throw jqErr(`${jqType(x)} and ${jqType(y)} cannot be added`); })();
3177
+ if (typeof x === "string" && typeof y === "string" && o === "-") throw jqErr("strings cannot be subtracted");
3178
+ if (o === "-" && Array.isArray(x) && Array.isArray(y)) return x.filter((a) => !y.some((b) => jqCompare(a, b) === 0));
3179
+ if (typeof x !== "number" || typeof y !== "number") throw jqErr(`${jqType(x)} and ${jqType(y)} cannot be ${o === "-" ? "subtracted" : o === "*" ? "multiplied" : "divided"}`);
3180
+ if ((o === "/" || o === "%") && y === 0) throw jqErr("division by zero");
3181
+ return o === "-" ? x - y : o === "*" ? x * y : o === "/" ? x / y : x % y;
3182
+ };
3183
+ const parseAdd = () => {
3184
+ let l = parseMul();
3185
+ while (op("+") || op("-")) {
3186
+ const o = toks[p++].v;
3187
+ l = bin(l, parseMul(), (x, y) => arith(x, y, o));
3188
+ }
3189
+ return l;
3190
+ };
3191
+ const parseMul = () => {
3192
+ let l = parsePostfix();
3193
+ while (op("*") || op("/") || op("%")) {
3194
+ const o = toks[p++].v;
3195
+ l = bin(l, parsePostfix(), (x, y) => (o === "/" && typeof x === "string" ? x.split(y) : arith(x, y, o)));
3196
+ }
3197
+ return l;
3198
+ };
3199
+ const index = (v, k) => {
3200
+ if (v === null) return null;
3201
+ if (Array.isArray(v) && typeof k === "number") return v[k < 0 ? v.length + k : k] ?? null;
3202
+ if (jqType(v) === "object" && typeof k === "string") return Object.hasOwn(v, k) ? v[k] : null;
3203
+ throw jqErr(`cannot index ${jqType(v)} with ${typeof k === "string" ? `"${k}"` : jqType(k)}`);
3204
+ };
3205
+ const parsePostfix = () => {
3206
+ let t = parseTerm();
3207
+ for (;;) {
3208
+ if (peek()?.t === "field") {
3209
+ const name = toks[p++].v;
3210
+ const a = t;
3211
+ t = (v) => a(v).map((x) => index(x, name));
3212
+ } else if (op(".") && toks[p + 1]?.t === "str") {
3213
+ p++;
3214
+ const name = toks[p++].v;
3215
+ const a = t;
3216
+ t = (v) => a(v).map((x) => index(x, name));
3217
+ } else if (op("[") || (op(".") && toks[p + 1]?.v === "[")) {
3218
+ if (op(".")) p++;
3219
+ p++;
3220
+ const a = t;
3221
+ if (op("]")) {
3222
+ p++;
3223
+ t = (v) => a(v).flatMap((x) => (Array.isArray(x) ? x : jqType(x) === "object" ? Object.values(x) : (() => { throw jqErr(`cannot iterate over ${jqType(x)}`); })()));
3224
+ } else {
3225
+ const first = op(":") ? null : parsePipe();
3226
+ if (op(":")) {
3227
+ p++;
3228
+ const second = op("]") ? null : parsePipe();
3229
+ eat("]");
3230
+ t = (v) => a(v).map((x) => {
3231
+ const lo = first ? first(x)[0] : 0;
3232
+ const hi = second ? second(x)[0] : undefined;
3233
+ return typeof x === "string" || Array.isArray(x) ? x.slice(lo, hi) : null;
3234
+ });
3235
+ } else {
3236
+ eat("]");
3237
+ t = (v) => a(v).flatMap((x) => first(x).map((k) => index(x, k)));
3238
+ }
3239
+ }
3240
+ } else if (op("?")) {
3241
+ p++;
3242
+ const a = t;
3243
+ t = (v) => {
3244
+ try {
3245
+ return a(v);
3246
+ } catch {
3247
+ return [];
3248
+ }
3249
+ };
3250
+ } else return t;
3251
+ }
3252
+ };
3253
+ const parseTerm = () => {
3254
+ const t = toks[p++];
3255
+ if (!t) throw new SyntaxError("jq: the filter ends too soon");
3256
+ if (t.t === "num" || t.t === "str") return () => [t.v];
3257
+ if (t.t === "field") return (v) => [index(v, t.v)];
3258
+ if (t.t === "op") {
3259
+ if (t.v === ".") {
3260
+ if (peek()?.t === "str") return ((s) => (v) => [index(v, s)])(toks[p++].v);
3261
+ return (v) => [v];
3262
+ }
3263
+ if (t.v === "..") return (v) => {
3264
+ const out = [];
3265
+ const walk = (x) => (guard(), out.push(x), Array.isArray(x) ? x.forEach(walk) : jqType(x) === "object" && Object.values(x).forEach(walk));
3266
+ walk(v);
3267
+ return out;
3268
+ };
3269
+ if (t.v === "-") {
3270
+ const a = parsePostfix();
3271
+ return (v) => a(v).map((x) => -x);
3272
+ }
3273
+ if (t.v === "(") {
3274
+ const e = parsePipe();
3275
+ eat(")");
3276
+ return e;
3277
+ }
3278
+ if (t.v === "[") {
3279
+ if (op("]")) return p++, () => [[]];
3280
+ const e = parsePipe();
3281
+ eat("]");
3282
+ return (v) => [e(v)];
3283
+ }
3284
+ if (t.v === "{") {
3285
+ const fields = [];
3286
+ while (!op("}")) {
3287
+ let key;
3288
+ const k = toks[p++];
3289
+ if (k.t === "id" || k.t === "str") key = () => [k.v];
3290
+ else if (k.t === "field") key = () => [k.v];
3291
+ else if (k.t === "op" && k.v === "(") (key = parsePipe()), eat(")");
3292
+ else throw new SyntaxError("jq: a key in {…}");
3293
+ let val;
3294
+ if (op(":")) (p++, (val = parseAlt()));
3295
+ else val = (v) => [index(v, k.v)];
3296
+ fields.push([key, val]);
3297
+ if (op(",")) p++;
3298
+ else if (!op("}")) throw new SyntaxError('jq: "," or "}" in {…}');
3299
+ }
3300
+ p++;
3301
+ return (v) => {
3302
+ let acc = [{}];
3303
+ for (const [kf, vf] of fields) acc = acc.flatMap((o) => kf(v).flatMap((k) => vf(v).map((x) => ({ ...o, [String(k)]: x }))));
3304
+ return acc;
3305
+ };
3306
+ }
3307
+ throw new SyntaxError(`jq: unexpected "${t.v}"`);
3308
+ }
3309
+ if (t.t === "id") {
3310
+ if (t.v === "true") return () => [true];
3311
+ if (t.v === "false") return () => [false];
3312
+ if (t.v === "null") return () => [null];
3313
+ if (t.v === "if") {
3314
+ const c = parsePipe();
3315
+ if (!kw("then")) throw new SyntaxError("jq: expected then");
3316
+ p++;
3317
+ const a = parsePipe();
3318
+ let b = (v) => [v];
3319
+ if (kw("else")) (p++, (b = parsePipe()));
3320
+ if (!kw("end")) throw new SyntaxError("jq: expected end");
3321
+ p++;
3322
+ return (v) => c(v).flatMap((x) => (jqTruthy(x) ? a(v) : b(v)));
3323
+ }
3324
+ if (Object.hasOwn(JQ_FUNCS_ARGS, t.v) && JQ_FUNCS_ARGS[t.v]) {
3325
+ eat("(");
3326
+ const arg = parsePipe();
3327
+ eat(")");
3328
+ return JQ_FUNCS_ARGS[t.v](arg);
3329
+ }
3330
+ if (Object.hasOwn(JQ_FUNCS, t.v)) {
3331
+ const f = JQ_FUNCS[t.v];
3332
+ return (v) => f(v);
3333
+ }
3334
+ throw new SyntaxError(`jq: unknown function ${t.v}`);
3335
+ }
3336
+ throw new SyntaxError("jq: unexpected token");
3337
+ };
3338
+ const program = parsePipe();
3339
+ if (p < toks.length) throw new SyntaxError(`jq: unexpected "${toks[p].v}"`);
3340
+ return (v) => program(v);
3341
+ }
3342
+
3343
+ // ── tab completion ──────────────────────────────────────────────────────────────────────────────────
3344
+
3345
+ /**
3346
+ * Completions for the word before `cursor`: `{ from, to, candidates, common }`. `list(dir)` -> [{ name, type }] (the page's broker listing; a refusal is no candidates).
3347
+ * A first word completes to a command name, `$na` to a variable, and anything else to a name in a folder; a folder ends in "/".
3348
+ */
3349
+ export async function complete(line, cursor, { list, cwd = "/", vars = [], funcs = [] } = {}) {
3350
+ const before = String(line).slice(0, cursor);
3351
+ const m = /[^\s|&;<>]*$/.exec(before);
3352
+ const word = m[0];
3353
+ const from = cursor - word.length;
3354
+ const head = before.slice(0, from).trimEnd();
3355
+ const first = head === "" || /[|;&{(]$/.test(head) || /\b(?:then|do|else)$/.test(head);
3356
+ const done = (cands) => {
3357
+ const uniq = [...new Set(cands)].sort();
3358
+ let common = uniq[0] ?? "";
3359
+ for (const c of uniq) while (!c.startsWith(common)) common = common.slice(0, -1);
3360
+ return { from, to: cursor, candidates: uniq, common };
3361
+ };
3362
+ if (word.startsWith("$")) return done(vars.filter((v) => v.startsWith(word.slice(1))).map((v) => `$${v}`));
3363
+ if (first && !word.includes("/")) return done([...COMMANDS, ...funcs].filter((c) => c.startsWith(word)));
3364
+ const slash = word.lastIndexOf("/");
3365
+ const dirPart = slash >= 0 ? word.slice(0, slash + 1) : "";
3366
+ const prefix = word.slice(slash + 1);
3367
+ let entries = [];
3368
+ try {
3369
+ entries = (await list(resolvePath(cwd, dirPart || "."))) ?? [];
3370
+ } catch {
3371
+ entries = [];
3372
+ }
3373
+ const subs = /^\s*clawser\s+\S*$/.test(head + (head ? " x" : "")) && /^\s*clawser\s*$/.test(head) ? CLAWSER_SUBS.filter((s) => s.startsWith(word)) : [];
3374
+ if (subs.length) return done(subs);
3375
+ return done(entries.filter((e) => e.name.startsWith(prefix) && (prefix.startsWith(".") || !e.name.startsWith("."))).map((e) => `${dirPart}${e.name}${e.type === "dir" ? "/" : ""}`));
3376
+ }
3377
+
3378
+ // ── one line, run ────────────────────────────────────────────────────────────────────────────────────
3379
+
3380
+ /**
3381
+ * Run one line. `state` is what the last line left ({ cwd, vars, exported, last }); `wired` are variables from wired panes (text); `mode` is "person" (their shell: sessions and
3382
+ * `clear` take effect) or "machine" (a machine tool state: no session). Never throws for a line's own mistakes: they are the output and the exit code.
3383
+ * Returns `{ chunks: [{ s: "out"|"err", text }], code, state, effects, truncated, ms }`.
3384
+ */
3385
+ export async function run({ line, state, fs, fetch, sleep, wired, mode = "person", now, limits, history, views } = {}) {
3386
+ const sh = makeShell({ fs, fetch, sleep, state, wired, mode, now, limits: { ...LIMITS, ...(limits ?? {}) }, history: Array.isArray(history) ? history.slice(-LIMITS.history) : [], views });
3387
+ const io = { in: null, out: (t) => emit(sh, "out", t), err: (t) => emit(sh, "err", t) };
3388
+ let code = 0;
3389
+ try {
3390
+ if (typeof line !== "string") throw new SyntaxError("a line of text is needed");
3391
+ code = await execList(parse(line), sh, io);
3392
+ await settleJobs(sh, io); // a line ends when its jobs have
3393
+ } catch (error) {
3394
+ for (const job of sh.jobs) (job.cancelled = true), job.kill(); // the line is over: its jobs stop with it
3395
+ await Promise.allSettled(sh.jobs.map((job) => job.done)); // and are gone before the reply, so nothing runs on after it
3396
+ if (error instanceof Exit) code = error.code;
3397
+ else if (error instanceof Stop) {
3398
+ sh.chunks.push({ s: "err", text: `clsh: ${error.message}\n` });
3399
+ code = 124;
3400
+ } else if (error instanceof SyntaxError) {
3401
+ sh.chunks.push({ s: "err", text: `clsh: syntax error: ${error.message}\n` });
3402
+ code = 2;
3403
+ } else {
3404
+ sh.chunks.push({ s: "err", text: `clsh: ${error?.message ?? String(error)}\n` });
3405
+ code = 1;
3406
+ }
3407
+ }
3408
+ sh.last = code;
3409
+ return {
3410
+ chunks: sh.chunks,
3411
+ code,
3412
+ state: { cwd: sh.cwd, vars: Object.fromEntries([...sh.vars].filter(([k]) => !(wired && Object.hasOwn(wired, k)) && k !== "OLDPWD" || k === "OLDPWD")), exported: [...sh.exported], aliases: Object.fromEntries(sh.aliases), funcs: Object.fromEntries([...sh.funcs].map(([k, f]) => [k, f.src])), last: code },
3413
+ effects: mode === "person" ? sh.effects : [],
3414
+ truncated: sh.truncated,
3415
+ ms: sh.now() - sh.started,
3416
+ };
3417
+ }