@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,2150 @@
1
+ // The page side of mallory's sandbox: one andbox Worker that holds every pane's
2
+ // live value. The page only ever receives previews. A pane set to "Run in its
3
+ // own Worker" runs its code in a Worker of its own, so a timeout there
4
+ // restarts only that Worker; its value is still kept in the shared one.
5
+ //
6
+ // The sandbox's own code (worker-runtime.js and inspectable's serializer) is
7
+ // passed in as text (`sources`): the page imports it with Vite's `?raw`
8
+ // (./sources.js), the headless runner reads the files (src/headless/node.js).
9
+ import { createSandbox } from "@johnhenry/andbox";
10
+
11
+ import { checkInputName, paneBody, templateBody } from "./compile.js";
12
+ import { usesAI } from "../ai/policy.js";
13
+ import { aiGateLimits } from "../ai/bridge.js";
14
+ import { parseRetryAfter } from "../model/errors.js";
15
+ import { cspFetch } from "../network/csp-frame.js";
16
+ import { watchResourceTiming } from "./resource-timing.js";
17
+ import { relayStream, streamsBody } from "../network/streams.js";
18
+ import { isX402DemoUrl, x402Demo } from "../x402/demo-server.js";
19
+ import { payHostResponse } from "../x402/retry.js";
20
+ import { afterThisTask } from "../model/turns.js";
21
+ import { markTransfer, TRANSFER } from "./transfer.js";
22
+ import { createPersonWaits } from "./person-waits.js";
23
+ import { createStrictRunner, strictConfig, STRICT_MAX_INPUT } from "./strict.js";
24
+ import { moduleMatches } from "../packages/module.js";
25
+ export { checkInputName, paneBody, paneLine, templateBody } from "./compile.js";
26
+
27
+ const J = JSON.stringify;
28
+
29
+ const MAX_RESPONSE_BYTES = 25 * 1024 * 1024;
30
+
31
+ /** The most calls one batched evaluation carries; more make several, so the Worker starts on the first while the rest are sent. */
32
+ export const BATCH_MAX = 256;
33
+
34
+ /** An error from the Worker (`{ message, name, code?, stack? }`) as andbox makes one from a failed evaluation. */
35
+ function sandboxError(e) {
36
+ const error = new Error(e?.message || "Evaluation failed");
37
+ error.name = e?.name || "Error";
38
+ if (e?.code) error.code = e.code;
39
+ if (typeof e?.stack === "string") error.sandboxStack = e.stack;
40
+ return error;
41
+ }
42
+
43
+ /**
44
+ * The network, as panes see it: http(s) only, no cookies or other
45
+ * credentials, no referrer. Runs on this page on behalf of the sandbox.
46
+ * This is the transport; which hosts a pane may reach is decided by the
47
+ * policy in src/network/policy.js, which wraps it (`createRuntime({ network })`).
48
+ *
49
+ * `init.maxBytes` and `init.timeoutMs` (a caller that knows what it expects, such as the soundfont loader): a body over `maxBytes` is refused as soon as
50
+ * it is seen to be (not after reading up to the 25 MB cap), and a request that has not finished, body included, after `timeoutMs` is given up on.
51
+ *
52
+ * `init.stream` (a pane's own fetch): a response whose body is a stream
53
+ * of events or records (src/network/streams.js streamsBody) comes back with
54
+ * `stream`, a ReadableStream of its body as it arrives, instead of `body`. `init.streamAll` (a frame's own fetch, src/network/frame-net.js) streams every body.
55
+ */
56
+ export async function hostFetch(url, init = {}) {
57
+ const target = new URL(url, globalThis.location?.href);
58
+ const limit = Number(init.maxBytes) > 0 ? Math.min(MAX_RESPONSE_BYTES, Number(init.maxBytes)) : MAX_RESPONSE_BYTES;
59
+ const timeoutMs = Number(init.timeoutMs) > 0 ? Number(init.timeoutMs) : 0;
60
+ if (target.protocol !== "https:" && target.protocol !== "http:") throw new TypeError(`fetch: only http(s) URLs are allowed (got ${target.protocol})`);
61
+ const clock = timeoutMs ? new AbortController() : null;
62
+ let timedOut = false;
63
+ const timer = clock ? setTimeout(() => ((timedOut = true), clock.abort()), timeoutMs) : null;
64
+ let signal = clock?.signal ?? init.signal;
65
+ let release = () => {};
66
+ if (clock && init.signal) {
67
+ try {
68
+ ({ signal, release } = bothSignals(init.signal, clock.signal));
69
+ } catch (error) {
70
+ clearTimeout(timer);
71
+ throw error;
72
+ }
73
+ }
74
+ // This request's Resource Timing entry is on the performance timeline of the realm that made it: this page's, or the CSP frame's (cspFetch gives
75
+ // `send` the frame's window). The numbers go out as `resourceTiming` for the tap and the send value to explain (src/model/timing.js); nothing is guessed.
76
+ const browser = typeof document !== "undefined";
77
+ let watch;
78
+ const send = (platformFetch, win) => {
79
+ if (browser) watch = watchResourceTiming(win ?? globalThis, target.href);
80
+ return platformFetch(target.href, {
81
+ method: init.method ?? "GET",
82
+ headers: init.headers,
83
+ body: init.body,
84
+ credentials: "omit",
85
+ referrerPolicy: "no-referrer",
86
+ redirect: init.redirect === "manual" ? "manual" : init.redirect === "error" ? "error" : "follow",
87
+ mode: "cors",
88
+ signal,
89
+ });
90
+ };
91
+ const streams = (res) => init.stream === true && Boolean(res.body?.getReader) && !EMPTY_STATUSES.includes(res.status) && (init.streamAll === true || streamsBody(res.headers.get("content-type")));
92
+ // `hops` (the network policy's redirectSources()): on a page, the
93
+ // request is made under a CSP that lists them, so the browser checks every
94
+ // redirect before following it (src/network/csp-frame.js). Its response
95
+ // belongs to that frame: the body is copied into this page's objects (and a
96
+ // streamed one keeps the frame until it ends).
97
+ const framed = Array.isArray(init.hops) && typeof document !== "undefined";
98
+ let bodyDone;
99
+ try {
100
+ const res = framed ? await cspFetch(target.href, init.hops, send, (r) => (streams(r) ? new Promise((resolve) => (bodyDone = resolve)) : undefined)) : await send(fetch);
101
+ const length = Number(res.headers.get("content-length") ?? 0);
102
+ if (length > limit) {
103
+ bodyDone?.();
104
+ res.body?.cancel().catch(() => {});
105
+ throw new Error(`fetch: response too large (${length} bytes)`);
106
+ }
107
+ const head = { url: res.url, status: res.status, statusText: res.statusText, headers: [...res.headers].map(([k, v]) => [k, v]), redirected: res.redirected, type: res.type };
108
+ if (streams(res)) return { ...head, stream: relayStream(res.body, { maxBytes: MAX_RESPONSE_BYTES, onEnd: bodyDone }) }; // a stream's timing is not read (it would block the first chunk): the observer is let go below
109
+ const limited = limit < MAX_RESPONSE_BYTES || timeoutMs > 0;
110
+ const body = (framed || limited) && res.body?.getReader ? await readAll(res.body, limit, signal) : framed ? new ArrayBuffer(0) : await res.arrayBuffer();
111
+ if (body.byteLength > limit) throw new Error(`fetch: response too large (${body.byteLength} bytes)`);
112
+ // The entry is queued when the body has ended, so it is asked for after the body is read, never before.
113
+ if (watch) head.resourceTiming = await watch.result();
114
+ return { ...head, body };
115
+ } catch (error) {
116
+ if (timedOut) throw new Error(`fetch: timed out after ${timeoutMs} ms`);
117
+ throw error;
118
+ } finally {
119
+ clearTimeout(timer);
120
+ release();
121
+ watch?.cancel(); // on every path: a rejected or aborted fetch, a refusal, a too-large body, a stream
122
+ }
123
+ }
124
+
125
+ const EMPTY_STATUSES = [101, 204, 205, 304];
126
+
127
+ /** A signal that aborts when either does, and what to call when the request is over: `{ signal, release }` (AbortSignal.any is Safari 17.4 and Firefox 124 and later; without it the listeners are taken off again). */
128
+ function bothSignals(a, b) {
129
+ if (typeof AbortSignal.any === "function") return { signal: AbortSignal.any([a, b]), release() {} };
130
+ const both = new AbortController();
131
+ const listeners = [];
132
+ for (const s of [a, b]) {
133
+ if (s.aborted) both.abort(s.reason);
134
+ else {
135
+ const on = () => both.abort(s.reason);
136
+ s.addEventListener("abort", on, { once: true });
137
+ listeners.push([s, on]);
138
+ }
139
+ }
140
+ return { signal: both.signal, release: () => listeners.forEach(([s, on]) => s.removeEventListener("abort", on)) };
141
+ }
142
+
143
+ /** A response body (another realm's, a CSP frame's) read whole into this page's ArrayBuffer, up to `limit` bytes and until `signal` aborts. */
144
+ async function readAll(stream, limit = MAX_RESPONSE_BYTES, signal = undefined) {
145
+ const reader = stream.getReader();
146
+ const parts = [];
147
+ let size = 0;
148
+ const aborted = signal ? new Promise((_, reject) => (signal.aborted ? reject(signal.reason) : signal.addEventListener("abort", () => reject(signal.reason), { once: true }))) : null;
149
+ aborted?.catch(() => {});
150
+ for (;;) {
151
+ let step;
152
+ try {
153
+ step = await (aborted ? Promise.race([reader.read(), aborted]) : reader.read());
154
+ } catch (error) {
155
+ reader.cancel().catch(() => {});
156
+ throw error;
157
+ }
158
+ const { done, value } = step;
159
+ if (done) break;
160
+ size += value.byteLength;
161
+ if (size > limit) {
162
+ reader.cancel().catch(() => {});
163
+ throw new Error(`fetch: response too large (more than ${limit} bytes)`);
164
+ }
165
+ parts.push(value);
166
+ }
167
+ const out = new Uint8Array(size);
168
+ let at = 0;
169
+ for (const p of parts) (out.set(p, at), (at += p.byteLength));
170
+ return out.buffer;
171
+ }
172
+
173
+ /** How long a streamed response body waits for the Worker to claim it, and how many may be read at once per Worker. */
174
+ const BODY_CLAIM_MS = 30000;
175
+ const MAX_BODY_STREAMS = 32;
176
+
177
+ /** What a restart says when nothing timed out (▶ restart sandbox; src/ui/network-ui.js has its own words for the network's). */
178
+ export const RESTARTED = "Restarted. Panes keep their values where they can; the rest rerun.";
179
+
180
+ // An evaluation that rejects is andbox's own doing: its timeout or an
181
+ // abort ended the Worker. What the evaluated code threw never rejects: every
182
+ // call's code runs in a try whose catch returns the error as a value
183
+ // (worker-runtime.js thrown, THROWN below), so pane code that throws an error
184
+ // named AbortError or TimeoutError (an aborted fetch, AbortSignal.timeout())
185
+ // is that pane's error, not a killed Worker.
186
+ const isKill = (error) => error?.name === "TimeoutError" || error?.name === "AbortError";
187
+ /** The key of an error the evaluated code threw, returned instead of rejecting (worker-runtime.js thrown). */
188
+ const THROWN = "mallory:thrown";
189
+
190
+ /** Does a value hold a Blob (a media value, say)? Then it travels by structured clone, not JSON. */
191
+ export function holdsBlob(value, depth = 4) {
192
+ if (!value || typeof value !== "object" || depth < 0) return false;
193
+ if (typeof Blob === "function" && value instanceof Blob) return true;
194
+ if (Array.isArray(value)) return value.some((v) => holdsBlob(v, depth - 1));
195
+ const proto = Object.getPrototypeOf(value);
196
+ if (proto !== Object.prototype && proto !== null) return false;
197
+ return Object.values(value).some((v) => holdsBlob(v, depth - 1));
198
+ }
199
+
200
+ /**
201
+ * @param {{ timeoutMs?: number, onRestart?: (reason: Error) => void,
202
+ * onConsole?: (paneId: string | null, level: string, args: string[]) => void,
203
+ * network?: (url: string, init: object, context: { pane?: string, signal?: AbortSignal }) => Promise<object> }} options
204
+ * `tap` is the read-only record of this canvas's own requests beside `network` ({ snapshot() }, src/model/http-tap.js): the http pane's tap mode reads it as `runtime.tap`.
205
+ * `network` makes panes' requests, both a pane's own `fetch` (with `context.pane`)
206
+ * and the sandbox's global `fetch` that libraries use (no pane). Without it,
207
+ * every request is refused: there is no network by default.
208
+ * `sources` is `{ runtime, keys, inspectable, exporter? }`: the text of worker-runtime.js, of keys.js,
209
+ * of `@johnhenry/inspectable/serialize` and of src/export/value.js (see ./sources.js). `sandbox` adds
210
+ * createSandbox options (the headless runner's `nodeWorker`). `env` is
211
+ * `{ values, missing }`: the variables panes read as `env.NAME` (see setEnv).
212
+ * `ai` is on-device AI (src/ai/): `{ bridge, ask?, timeoutMs? }`. `bridge()` makes
213
+ * the Chrome AI bridge definition for each new sandbox (src/ai/bridge.js
214
+ * malloryChromeAI, or unavailableAI for headless runs), which puts `ai`,
215
+ * LanguageModel, … in it; `ask(pane, api, options, { signal })` is asked before a
216
+ * pane's create() and resolves `{ ok, message? }` (the page's prompt names the
217
+ * pane); a pane whose code uses them gets `timeoutMs` (default 120 s) when that
218
+ * is longer than the timeout. Without `ai`, panes have none of those names.
219
+ * `onBlocked(url, directive, { own })` hears what the Worker's CSP refused (a module from a host the
220
+ * canvas doesn't allow, see src/network/csp-frame.js cspWorkers, passed as `sandbox.workerFactory`);
221
+ * `own`: a pane's own Worker refused it. `ownSandbox` (default `sandbox`): createSandbox options
222
+ * for panes' own Workers (the page gives them a workerFactory of their own, so the shared Worker's
223
+ * `current()` stays the shared one's).
224
+ * `transfer`: the Worker factories move ArrayBuffers marked for it (src/runtime/transfer.js;
225
+ * the page's CSP Workers do, Node's don't), so a copy between a pane's own Worker and the shared
226
+ * one hands its buffers over instead of copying them again.
227
+ * `channel`: give the shared Worker and each pane's own Worker a MessageChannel of their own
228
+ * (browser only: the page's Worker factories pass a MessagePort on with a transfer list, Node's can't),
229
+ * so copies between them go straight across instead of through this page.
230
+ * `createSandbox` (tests) replaces andbox's, so a test can make a Worker slow to start.
231
+ * `strict`: strict panes' engine (./strict.js, andbox `mode: 'wasm'`): `{ options() }` gives its createSandbox
232
+ * options (the page: a workerFactory and the engine's URLs, src/runtime/strict-engine.js; Node: none, andbox
233
+ * finds the installed engine). Without it a strict pane fails, saying strict mode isn't available.
234
+ * `eventBatchGapMs` (tests) stretches the Worker's wait between one pane's batches of
235
+ * events (worker-runtime.js flushEvents; 0 by default), as a loaded machine can.
236
+ */
237
+ export function createRuntime({ timeoutMs = 15000, onRestart, onConsole, onStateChanged, onBlocked, network, socket, tap, sources, sandbox: sandboxOptions, ownSandbox: ownSandboxOptions = sandboxOptions, env: envOption, decodeAudio, ai, companion, ffmpeg, crossTab, midi, serial, vfs, devices, eventBatchGapMs, transfer = false, channel = false, strict, createSandbox: makeSandbox = createSandbox } = {}) {
238
+ if (typeof sources?.runtime !== "string" || typeof sources?.inspectable !== "string" || typeof sources?.keys !== "string") throw new TypeError("createRuntime: pass sources: { runtime, keys, inspectable } (see src/runtime/sources.js)");
239
+ // No policy, no network: a runtime created without `network` refuses every request.
240
+ const send = (url, init, context) => (network ? network(url, init, context) : Promise.reject(new TypeError(`fetch: no network policy for ${url} (pass createRuntime({ network }))`)));
241
+ // A socket is opened by the host only (the ws-client pane, src/model/runners/ws-client.js), through the network policy's socket function (src/network/sockets.js); no socket function, no socket.
242
+ const openSocket = (url, init, context) => (socket ? socket(url, init, context) : Promise.reject(new TypeError(`websocket: no network policy for ${url} (pass createRuntime({ socket }))`)));
243
+ // Error policies (src/model/errors.js): a pane's own timeout, and what its
244
+ // requests came back with during one attempt (watchFetches).
245
+ const paneTimeouts = new Map(); // pane id -> ms
246
+ const fetchWatchers = new Set(); // { pane, item, outcomes }
247
+ const watched = (pane, item, request) => {
248
+ const watchers = [...fetchWatchers].filter((w) => w.pane === pane && (w.item === undefined || w.item === item));
249
+ if (!watchers.length) return request;
250
+ const note = (outcome) => watchers.forEach((w) => w.outcomes.push(outcome));
251
+ return request.then(
252
+ (res) => {
253
+ const retryAfter = (res.headers ?? []).find(([k]) => String(k).toLowerCase() === "retry-after")?.[1];
254
+ note({ kind: "status", status: res.status, ...(retryAfter !== undefined ? { retryAfterMs: parseRetryAfter(retryAfter) } : {}) });
255
+ return res;
256
+ },
257
+ (error) => {
258
+ note({ kind: error?.fetchFailure ?? "error" });
259
+ throw error;
260
+ },
261
+ );
262
+ };
263
+ // The Workers: the shared one, which holds every pane's value, and one
264
+ // of its own for each pane set to "Run in its own Worker" (made on its first
265
+ // run). A slot is one Worker's life: its sandbox, the promise of it being
266
+ // ready, and a generation that moves on each time it is replaced.
267
+ // A pane's own Worker also knows its pane's runs: the calls each has in flight there (`runs`, run id ->
268
+ // { n, shared }: how many, and the shared Worker's generation when the first started), and the newest run that
269
+ // started (`newest`), so a rerun after a shared restart can end the run from before it first (supersedeOwn).
270
+ const newSlot = (own = null) => ({ own, sandbox: undefined, ready: undefined, generation: 0, envDirty: false, clockDirty: false, evalDirty: false, profileDirty: false, assetsDirty: false, modulesDirty: false, codecDirty: false, codecDefined: new Set(), disposed: false, runs: new Map(), newest: -Infinity });
271
+ const shared = newSlot();
272
+ const ownSlots = new Map(); // pane id -> its slot
273
+ // Calls that wait for a person (./person-waits.js): a call's clock
274
+ // stops while its pane waits for an answer to a prompt (on-device AI), and a
275
+ // wait as long as the call's timeout gives up with a refusal instead of
276
+ // ending the Worker. `where` is the slot.
277
+ const personWaits = createPersonWaits();
278
+ // Model calls are slow (a first session can take a while): a pane that uses
279
+ // on-device AI may run this long. A timeout restarts the Worker, which
280
+ // destroys every session in it.
281
+ let aiTimeoutMs = ai?.timeoutMs ?? 120000;
282
+ const timeFor = (code) => (ai && usesAI(code) ? Math.max(timeoutMs, aiTimeoutMs) : timeoutMs);
283
+ // Variables (src/env/): `{ values, missing }`, sent when the Worker starts
284
+ // and, after setEnv, ahead of the next call's code, so no call that starts
285
+ // after setEnv (a pane of a canvas just opened, say) sees the old values.
286
+ let env = { values: {}, missing: undefined, ...envOption };
287
+ const envCode = () => `globalThis.__mallory.setEnv(JSON.parse(${J(J(env.values ?? {}))}), ${J(env.missing ?? null)});\n`;
288
+ // Evaluations in progress (src/tests/evaluate.js): id prefix -> dataset row,
289
+ // sent like the variables (ahead of the next call, and again after a restart).
290
+ const evaluations = new Map();
291
+ const slots = () => [shared, ...ownSlots.values()];
292
+ // A package pane's files (src/packages/assets.js): id prefix -> [{ name, type, data }], for the panes under that prefix. Sent to a Worker when they change or it starts.
293
+ const assetTables = new Map();
294
+ const assetsCode = () => `globalThis.__mallory.setAssets(JSON.parse(${J(J([...assetTables]))}));\n`;
295
+ // A package pane's shared module (src/packages/module.js): id prefix -> { specifier, package, version, name, problem? }, sent like the
296
+ // assets; the source itself is a virtual module (`mallory:pkg/<its sha256>`), defined in a Worker before the first call after it
297
+ // changed (ensureModules) and only once its integrity matches its source. Nothing is fetched: its text comes from the page.
298
+ const moduleTables = new Map();
299
+ const moduleSources = new Map(); // specifier -> { source, ok: Promise<boolean> }
300
+ const modulesCode = () => `globalThis.__mallory.setModules(JSON.parse(${J(J([...moduleTables].map(([prefix, { specifier, package: pkg, version, name, problem }]) => [prefix, { specifier, package: pkg, version, name, ...(problem ? { problem } : {}) }])))}));\n`;
301
+ const definedModules = new WeakMap(); // sandbox -> the specifiers defined in it
302
+ async function ensureModules(slot) {
303
+ const box = slot.sandbox;
304
+ if (!box || !moduleTables.size) return;
305
+ let defined = definedModules.get(box);
306
+ if (!defined) definedModules.set(box, (defined = new Set()));
307
+ for (const entry of moduleTables.values()) {
308
+ if (defined.has(entry.specifier)) continue;
309
+ const held = moduleSources.get(entry.specifier);
310
+ if (!held) continue;
311
+ if (!(await held.ok)) {
312
+ if (!entry.problem) {
313
+ entry.problem = `the package's module "${entry.name}" doesn't match its integrity (its source isn't the one the package author hashed), so it wasn't loaded`;
314
+ for (const other of slots()) other.modulesDirty = true;
315
+ }
316
+ continue;
317
+ }
318
+ defined.add(entry.specifier);
319
+ await box.defineModule(entry.specifier, held.source);
320
+ }
321
+ }
322
+ // What panes' profile views are read with (src/model/profile-settings.js): pane id -> options, sent to a Worker when they change or it starts.
323
+ const profiles = new Map();
324
+ const profileCode = () => `globalThis.__mallory.setProfileSettings(JSON.parse(${J(J([...profiles]))}));\n`;
325
+ // A virtual clock's instant (ms) that events are stamped with, or null (setClock): sent like the variables.
326
+ let clockAt = null;
327
+ const clockCode = () => `globalThis.__mallory.setClock(${clockAt === null ? "null" : J(clockAt)});\n`;
328
+ // Codec panes (src/codec/): which there are by name (setCodecs), sent like the variables; the engine ships in every sandbox, the three
329
+ // libraries (MessagePack, CBOR, protobufjs, flatc, the Cap'n Proto reader) only once a canvas has a codec pane that needs them: `sources.codec.libs(name)` loads one
330
+ // as text (the page's lazy chunks, Node's files), and it is defined in every Worker as the virtual module mallory:codec/<name>.
331
+ let codecTable = {};
332
+ let calendarLoaded; // the calendar bundle's text (a chunk of the page, a file in Node), read once
333
+ const calendarText = () => (calendarLoaded ??= Promise.resolve(typeof sources.calendar === "function" ? sources.calendar() : sources.calendar));
334
+ // jth (src/jth/vendor.js, the Worker's mallory:jth): a module of its own that no canvas pays for until pane code asks for `jth` (the Worker's
335
+ // `jthDefine` call, below): `sources.jth` loads it as text (the page's lazy chunk, Node's file), and it is defined in every Worker, now and after a restart.
336
+ let jthText; // the bundle's text, once loaded
337
+ let jthLoading; // the promise of loading it and defining it in every Worker
338
+ // Aimatey (src/aimatey/vendor.js, the Worker's mallory:aimatey): the same way as jth, for `aimatey` in pane code (the `aimateyDefine` call).
339
+ let aimateyText;
340
+ let aimateyLoading;
341
+ let exactLoaded; // the exact-math bundle's text, read once
342
+ let smfLoaded; // the smf helper's bundle (src/smf-helper/vendor.js), read once
343
+ const smfText = () => (smfLoaded ??= Promise.resolve(typeof sources.smf === "function" ? sources.smf() : sources.smf));
344
+ const exactText = () => (exactLoaded ??= Promise.resolve(typeof sources.exact === "function" ? sources.exact() : sources.exact));
345
+ let plotLoaded; // the plot helper's bundle (src/plot/vendor.js), read once
346
+ const plotText = () => (plotLoaded ??= Promise.resolve(typeof sources.plot === "function" ? sources.plot() : sources.plot));
347
+ let mathplusLoaded; // the math-plus bundle's text (a package's one-file build, about 490 kB), read once; it is compiled only when a pane's code imports it
348
+ const mathplusText = () => (mathplusLoaded ??= Promise.resolve().then(() => (typeof sources.mathplus === "function" ? sources.mathplus() : sources.mathplus)));
349
+ const codecLibs = new Map(); // library name -> its text, once loaded
350
+ const codecLoading = new Map(); // library name -> the promise of loading it and defining it in every Worker
351
+ const codecCode = () => `globalThis.__mallory.setCodecs(JSON.parse(${J(J(codecTable))}));\n`;
352
+ const evalCode = () => `globalThis.__mallory.setEvaluations(JSON.parse(${J(J([...evaluations]))}));\n`;
353
+ // Values made on the page that JSON can't carry (Blobs in media values),
354
+ // waiting for the Worker to fetch them by structured clone (setValue).
355
+ const handoffs = new Map();
356
+ let handoffSeq = 0;
357
+ // Agent panes only (src/agent/run.js): while one waits for its model, what
358
+ // it is told as the reply arrives. Keyed by sandbox pane id; see agent().
359
+ // Not a value: the pane's value is still published once, when its run ends.
360
+ const agentTaps = new Map(); // pane id -> { runId, onProgress }
361
+ // Response bodies that stream into the sandbox (src/network/streams.js):
362
+ // paneFetch answers with a token, and the Worker's fetch reads the body
363
+ // through the `malloryBody` bridge (bodyBridge). One the Worker never claims is
364
+ // cancelled after BODY_CLAIM_MS.
365
+ const bodies = new Map(); // token -> { stream, timer }
366
+ const holdBody = (stream) => {
367
+ const token = crypto.randomUUID();
368
+ const timer = setTimeout(() => {
369
+ if (bodies.get(token)?.stream !== stream) return;
370
+ bodies.delete(token);
371
+ stream.cancel().catch(() => {});
372
+ }, BODY_CLAIM_MS);
373
+ bodies.set(token, { stream, timer });
374
+ return token;
375
+ };
376
+ const bodyBridge = {
377
+ api: {
378
+ // The Worker's fetch (worker-runtime.js sandboxFetch) claims the body of a response paneFetch answered with `stream`.
379
+ read: {
380
+ stream: true,
381
+ call(ctx, token) {
382
+ const held = bodies.get(String(token));
383
+ if (!held) throw new DOMException("This response body was already read, or the request it belongs to was cancelled.", "InvalidStateError");
384
+ bodies.delete(String(token));
385
+ clearTimeout(held.timer);
386
+ return held.stream;
387
+ },
388
+ },
389
+ },
390
+ limits: { maxStreams: MAX_BODY_STREAMS },
391
+ };
392
+ // Live outputs: who hears a live run's emit(value) and emit.close(),
393
+ // keyed by sandbox pane id (see liveWatch). Values that arrive for a run
394
+ // nobody watches (a newer run took over) are refused.
395
+ const liveWatchers = new Map(); // pane id -> { runId, onEmit, onClose }
396
+ // A live pane's code (by pane id), for the timeout of each of its steps.
397
+ const liveCode = new Map();
398
+ // Events from pane code (emit.event, values keyed by event outputs): who hears them (the root canvases, src/model/canvas.js).
399
+ const eventListeners = new Set();
400
+ // MCP server panes (src/mcp/hub.js): who answers `mcp.call(…)` and friends in pane code (the root canvases, src/model/canvas.js).
401
+ // Each answers for its own panes (`{ value }` or `{ error }`) and undefined for a pane that isn't its.
402
+ const mcpHandlers = new Set();
403
+ // A2A agent panes (src/a2a/hub.js): who answers `a2a.send(…)` and `a2a.card(…)` in pane code (the root canvases), the same way.
404
+ const a2aHandlers = new Set();
405
+ // x402 payment challenges in panes' fetches (src/x402/pay.js): who decides them (the root canvases), the same way.
406
+ const payHandlers = new Set();
407
+ /** The decision for a challenge pane `pane` met, from the canvas that owns it: decidePayment's answer, or undefined. */
408
+ async function askPayment(slot, pane, challenge, url, signal) {
409
+ const from = `fetch ${String(url).length > 200 ? `${String(url).slice(0, 199)}…` : String(url)}`;
410
+ for (const fn of [...payHandlers]) {
411
+ const answer = await fn(pane, { challenge, from }, { signal, waiting: (giveUp) => personWaits.wait(slot, pane, giveUp) });
412
+ if (answer !== undefined) return answer;
413
+ }
414
+ return undefined;
415
+ }
416
+ // What a pane's run wants back in the reply that stores its value (see withRun): pane id -> { runId, base?, json? }.
417
+ const runWants = new Map();
418
+
419
+ /** withRun's `json`: the run log's limits, and how big a value the page keeps to put back after a restart. */
420
+ const cleanJson = (json) => ({
421
+ maxBytes: Number(json.maxBytes) || 0,
422
+ maxPreviewEntries: Number(json.maxPreviewEntries) || 0,
423
+ ...(Number(json.restoreBytes) > 0 ? { restoreBytes: Number(json.restoreBytes) } : {}),
424
+ ...(json.only === "restore" ? { only: "restore" } : {}),
425
+ });
426
+
427
+ /**
428
+ * The code that calls `expr` (a call into the Worker that stores pane `id`'s
429
+ * value) and returns its result: through `__mallory.finish` when run `runId`
430
+ * of the pane asked for more in the same reply (withRun). `own`: the value
431
+ * came from the pane's own Worker, with its `state` as JSON.
432
+ */
433
+ function finishing(id, runId, expr, { effects = false, own = false, state } = {}) {
434
+ const want = runWants.get(String(id));
435
+ if (!want || want.runId !== Number(runId)) return `return ${expr};`;
436
+ const base = want.base?.(); // read now, as compare() would read it after the run
437
+ const options = { ...(want.base ? { cutoff: true, ...(base == null ? {} : { base: Number(base) }) } : {}), ...(want.json ? { json: want.json } : {}), ...(effects ? { effects: true } : {}), ...(own ? { own: true, ...(typeof state === "string" ? { state } : {}) } : {}) };
438
+ return `return globalThis.__mallory.finish(${J(id)}, ${Number(runId)}, ${expr}, ${J(options)});`;
439
+ }
440
+
441
+ async function boot(slot) {
442
+ const sandbox = (slot.sandbox ??= await makeSandbox({
443
+ ...(slot.own != null ? ownSandboxOptions : sandboxOptions),
444
+ defaultTimeoutMs: timeoutMs,
445
+ // Output from no call in flight: andbox (0.3.1) says which call it came
446
+ // from (`this.consoleId`, a pane id: a timer a pane left behind), or
447
+ // nothing (the sandbox's own).
448
+ onConsole(level, ...args) {
449
+ onConsole?.(typeof this?.consoleId === "string" ? this.consoleId : null, level, args);
450
+ },
451
+ // The sandbox's global fetch (andbox's `network` option, andbox#39): what
452
+ // libraries call on their own. It goes through the same policy, without
453
+ // a pane id (the page attributes it to the panes that are running).
454
+ // allowedHosts "*": mallory's own policy (`network`, per canvas and host, with
455
+ // prompts) decides every request and redirect inside `send` (andbox 0.2.0).
456
+ network: { allowedHosts: "*", fetch: (url, init) => send(url, { method: init.method, headers: [...init.headers], body: init.body }, { signal: init.signal }) },
457
+ capabilities: {
458
+ // The `fetch` each pane gets (see worker-runtime.js) says which pane
459
+ // asked; `this.signal` aborts when the Worker is killed.
460
+ // A response that streams comes back with a token for its body, read through bodyBridge.
461
+ // A URL of the demo x402 endpoint (src/x402/demo-server.js) is answered in the page: no request, no prompt.
462
+ // A 402 that carries an x402 challenge is a payment decision (src/x402/pay.js, through the canvas that owns the
463
+ // pane): refused, it comes back as it is (with x-mallory-payment saying why); approved, the request is made
464
+ // once more with a simulated X-PAYMENT. A wait for the person stops the pane's clock, as a prompt does.
465
+ async paneFetch(url, init, context) {
466
+ const pane = context?.pane == null ? undefined : String(context.pane);
467
+ const signal = this?.signal;
468
+ const request = (headers) => (isX402DemoUrl(url) ? x402Demo().fetch(url, { ...init, headers, signal }) : send(url, { ...init, headers }, { pane, signal, stream: true }));
469
+ const paying = (res) => (pane === undefined || !payHandlers.size ? res : payHostResponse(res, { headers: init?.headers, retry: request, decide: (challenge) => askPayment(slot, pane, challenge, url, signal) }));
470
+ const r = await watched(pane, context?.item ?? undefined, request(init?.headers).then(paying));
471
+ if (!r?.stream) return r;
472
+ const { stream, ...head } = r;
473
+ return { ...head, stream: holdBody(stream) };
474
+ },
475
+ // An agent pane's model reply, as it arrives (worker-runtime.js AGENT.http and AGENT.chrome): text for the pane's trace only.
476
+ agentProgress(id, runId, text) {
477
+ const tap = agentTaps.get(String(id));
478
+ if (tap && tap.runId === Number(runId)) tap.onProgress(String(text));
479
+ },
480
+ // emit(value) in a live pane: the page settles it, after the pane's per-frame budget (src/model/live.js).
481
+ // From a pane's own Worker it is a copy (a Map), stored in the shared sandbox first.
482
+ async liveEmit(id, runId, result) {
483
+ const watcher = liveWatchers.get(String(id));
484
+ if (!watcher || watcher.runId !== Number(runId)) {
485
+ if (result instanceof Map && result.has("ticket")) dropTicket(slot.own ?? id, result.get("ticket")); // its copy, sent on the channel, goes unstored
486
+ return false;
487
+ }
488
+ if (result instanceof Map) result = await storeOwn({ id: String(id), runId: Number(runId), payload: result, view: ownRuns.get(String(id))?.view });
489
+ return (await watcher.onEmit(result)) !== false;
490
+ },
491
+ // Events pane code sent, in order: `[{ name, key, result, at, source }]`. From a
492
+ // pane's own Worker, a Map of copies, stored in the shared sandbox first (forwardEvents).
493
+ async paneEvents(id, list) {
494
+ if (list instanceof Map) list = await forwardEvents(String(id), list, slot.own ?? String(id));
495
+ // A listener may answer events whose sender asked to hear (`{ acks: { key: answer } }`): the answers go back with the reply.
496
+ const acks = {};
497
+ const deferred = []; // acknowledged channel sends the page answers later: the sender keeps waiting for them
498
+ for (const fn of eventListeners) {
499
+ try {
500
+ const reply = fn(String(id), Array.isArray(list) ? list : []);
501
+ Object.assign(acks, reply?.acks);
502
+ if (reply?.deferred) deferred.push(...reply.deferred);
503
+ } catch (error) {
504
+ globalThis.reportError?.(error);
505
+ }
506
+ }
507
+ return Object.keys(acks).length || deferred.length ? { acks, ...(deferred.length ? { deferred } : {}) } : undefined;
508
+ },
509
+ // frame() in a live pane: resolves at the run's next animation frame (src/model/live.js decides when).
510
+ liveFrame(id, runId) {
511
+ const watcher = liveWatchers.get(String(id));
512
+ if (!watcher || watcher.runId !== Number(runId) || !watcher.onFrame) return { time: 0, delta: 0, eventWaiting: false, ended: true };
513
+ return watcher.onFrame();
514
+ },
515
+ // emit.close(): the live run ends.
516
+ liveClose(id, runId) {
517
+ const watcher = liveWatchers.get(String(id));
518
+ if (watcher && watcher.runId === Number(runId)) watcher.onClose?.();
519
+ },
520
+ // mcp.call(server, tool, args), mcp.read(server, uri), mcp.prompt(…), mcp.tools(server) in pane code (worker-runtime.js mcpFor): the page
521
+ // makes the request, through the canvas's network policy and the person's tool gate (src/mcp/hub.js), and answers
522
+ // `{ value }` or `{ error }`. A wait for the person's approval stops the calling pane's clock (personWaits), as a prompt does.
523
+ async mcpCall(pane, server, op, request) {
524
+ for (const fn of [...mcpHandlers]) {
525
+ const answer = await fn(String(pane), String(server), String(op), request ?? {}, { signal: this?.signal, waiting: (giveUp) => personWaits.wait(slot, String(pane), giveUp) });
526
+ if (answer !== undefined) return answer;
527
+ }
528
+ return { error: "mcp: this pane isn't on an open canvas, so it can't reach an MCP server pane" };
529
+ },
530
+ // a2a.send(agent, message, { skill }) and a2a.card(agent) in pane code (worker-runtime.js a2aFor): the page sends
531
+ // it through the canvas's network policy, the person's tool gate and the protocol inspector (src/a2a/hub.js), and
532
+ // answers `{ value }` or `{ error }`. A wait for the person (an approval, a task's question) stops the pane's clock.
533
+ async a2aCall(pane, agent, op, request) {
534
+ for (const fn of [...a2aHandlers]) {
535
+ const answer = await fn(String(pane), String(agent), String(op), request ?? {}, { signal: this?.signal, waiting: (giveUp) => personWaits.wait(slot, String(pane), giveUp) });
536
+ if (answer !== undefined) return answer;
537
+ }
538
+ return { error: "a2a: this pane isn't on an open canvas, so it can't reach an A2A agent pane" };
539
+ },
540
+ // ffmpegRun(graph) in pane code (src/media/helpers.js): only a run that was given a program and a folder
541
+ // (`mallory run --allow-ffmpeg`, src/headless/ffmpeg-exec.js) can; the page and every other run answer
542
+ // `unavailable` and the helper refuses with the usual message. The result's bytes are copied back to the Worker.
543
+ async ffmpegExec(graph) {
544
+ if (!ffmpeg) return { unavailable: true };
545
+ return await ffmpeg.run(graph, { signal: this?.signal });
546
+ },
547
+ // companion.use(id) in pane code (worker-runtime.js): may this pane use that module? The page answers from its
548
+ // attachment in memory (and raises the permission bar's request the first time): no network request is made here.
549
+ async companionUse(pane, id) {
550
+ if (!companion) return { ok: false, why: "no companion is attached" };
551
+ return (await companion.use(String(pane), String(id))) ?? { ok: false, why: "no companion is attached" };
552
+ },
553
+ // A call on a module `companionUse` said yes to: the page adds the address and the credential, so the Worker never sees them.
554
+ async companionCall(pane, id, route, init) {
555
+ if (!companion) throw new Error("no companion is attached");
556
+ return await companion.call(String(pane), String(id), String(route), init ?? {}, { signal: this?.signal });
557
+ },
558
+ // companion.ws(id, route) in pane code (C5): the Worker can't open a socket (its CSP is connect-src 'none'), so the page
559
+ // does, after the same three gates as `use`, and the pane pulls messages from a bounded queue. Only a provider that has
560
+ // `wsOpen` (the page) can; a provider without it answers "no".
561
+ async companionWsOpen(pane, id, route) {
562
+ if (!companion?.wsOpen) return { ok: false, why: companion ? "this run can't open companion sockets (this provider has no sockets)" : "no companion is attached" };
563
+ return (await companion.wsOpen(String(pane), String(id), String(route))) ?? { ok: false, why: "no companion is attached" };
564
+ },
565
+ companionWsSend(pane, socket, data) {
566
+ if (!companion?.wsSend) throw new Error("no companion is attached");
567
+ return companion.wsSend(String(pane), Number(socket), data);
568
+ },
569
+ async companionWsNext(pane, socket, waitMs) {
570
+ if (!companion?.wsNext) return { messages: [], closed: true };
571
+ try {
572
+ return await companion.wsNext(String(pane), Number(socket), { waitMs: Number(waitMs) || 0, signal: this?.signal });
573
+ } catch {
574
+ return { messages: [], closed: true }; // released meanwhile (a rerun, a detach)
575
+ }
576
+ },
577
+ companionWsClose(pane, socket) {
578
+ companion?.wsClose?.(String(pane), Number(socket));
579
+ },
580
+ // crossTab.open() in pane code (worker-runtime.js): the page opens a BroadcastChannel for the open canvas, when the
581
+ // person allowed it (src/crosstab/bridge.js); the Worker has none and never names a channel. Absent (mallory run): "no".
582
+ async crossTabOpen(pane) {
583
+ if (!crossTab?.open) return { ok: false, why: "this run has no other tabs to link to (only the page can)" };
584
+ return (await crossTab.open(String(pane))) ?? { ok: false, why: "no cross-tab link is available" };
585
+ },
586
+ crossTabSend(pane, link, data) {
587
+ if (!crossTab?.send) throw new Error("no cross-tab link is available");
588
+ return crossTab.send(String(pane), Number(link), data);
589
+ },
590
+ async crossTabNext(pane, link, waitMs) {
591
+ if (!crossTab?.next) return { messages: [], closed: true };
592
+ try {
593
+ return await crossTab.next(String(pane), Number(link), { waitMs: Number(waitMs) || 0, signal: this?.signal });
594
+ } catch (error) {
595
+ return { messages: [], closed: true, why: String(error?.message ?? error) };
596
+ }
597
+ },
598
+ crossTabClose(pane, link) {
599
+ crossTab?.close?.(String(pane), Number(link));
600
+ },
601
+ // midi.open() in pane code (worker-runtime.js): raw MIDI on a MessagePort, once the person turned it on in the MIDI panel
602
+ // (src/midi/tap.js). The pane's end of the channel goes over as a capability reply with the port in its transfer list
603
+ // (src/runtime/transfer.js); where a Worker can't take one (headless), or the run has no page, the answer is "no".
604
+ async midiOpen(pane, have) {
605
+ if (!midi?.open) return { ok: false, why: "this run has no MIDI controller to read (only the page can)" };
606
+ const found = (await midi.open(String(pane), have === true)) ?? { ok: false, why: "no MIDI input is available" };
607
+ if (!found.port) return found;
608
+ if (!transfer) {
609
+ found.port.close?.();
610
+ return { ok: false, why: "this run can't hand a MIDI channel to the sandbox" };
611
+ }
612
+ return new Map([["ok", true], ["port", found.port], [TRANSFER, [found.port]]]);
613
+ },
614
+ midiClose(pane) {
615
+ midi?.close?.(String(pane));
616
+ },
617
+ // serial.write() / serial.signals() / serial.ports() in pane code (worker-runtime.js, #384): the page decides each call
618
+ // (src/serial/pane-writes.js: an open port, this browser's grant for the canvas and port, the limits). Absent (mallory run):
619
+ // nothing can write, and the pane is told so.
620
+ async serialCall(pane, op, args) {
621
+ if (!serial?.call) return { ok: false, name: "NotSupportedError", message: "serial: this run has no serial port (only the page can write to one)" };
622
+ return (await serial.call(String(pane), String(op), args ?? {})) ?? { ok: false, name: "NotSupportedError", message: "serial: no serial port is available" };
623
+ },
624
+ // vfs.folder(scope).read() and the rest in pane code (worker-runtime.js, #840): the page decides each call
625
+ // (src/vfs-access.js: this browser's grant for the canvas and folder, read again every time; the path confined to the folder;
626
+ // the file system's quota guard). Absent (mallory run): there is no file system, and the pane is told so.
627
+ async vfsCall(pane, op, args) {
628
+ if (!vfs?.call) return { ok: false, name: "NotSupportedError", message: "vfs: this run has no file system (only the page has one)" };
629
+ return (await vfs.call(String(pane), String(op), args ?? {})) ?? { ok: false, name: "NotSupportedError", message: "vfs: no file system is available" };
630
+ },
631
+ // devices.stream(x).frame() / .chunk() / .sample() in pane code (worker-runtime.js devicesFor): a fresh sample of a camera,
632
+ // microphone or screen a person started on the page, for a pane that reads that device pane (src/ui/device-pane.js
633
+ // decides). The Worker never holds the stream: it gets a media value or a copy of the PCM. Absent (mallory run): "no".
634
+ async deviceSample(pane, source, op) {
635
+ if (!devices?.sample) return { ok: false, name: "NotSupportedError", message: "devices: this run has no camera, microphone or screen (only the page can capture one)" };
636
+ return (await devices.sample(String(pane), String(source), String(op))) ?? { ok: false, name: "NotFoundError", message: "devices: no such capture" };
637
+ },
638
+ // `jth` in pane code needs its bundle (worker-runtime.js jthLib): it is defined in every Worker, then the caller imports it. False when this runtime has none.
639
+ jthDefine: () => loadJth().then(() => true, () => false),
640
+ // `aimatey` in pane code needs its bundle (worker-runtime.js aimateyLib): the same, for mallory:aimatey.
641
+ aimateyDefine: () => loadAimatey().then(() => true, () => false),
642
+ // The Worker's CSP refused a load (worker-runtime.js): the page decides what it means.
643
+ cspBlocked: (url, directive) => void onBlocked?.(String(url ?? ""), String(directive ?? ""), { own: slot.own != null }),
644
+ // A state pane's setter ran in the sandbox: rerun what depends on it. Keyed setters say what changed: [{ op, key, at?, to? }…].
645
+ stateChanged: (id, changes) => void onStateChanged?.(String(id), Array.isArray(changes) ? changes : undefined),
646
+ // A setter in a pane's own Worker: its change, as a copy, made to the state pane in the shared sandbox, in order.
647
+ // On their channel, `entries` is a ticket for the copy the shared Worker already has.
648
+ ownSetState: (id, entries) => inOrder(() => fromOwnWorker(slot.own, entries, (v) => `return globalThis.__mallory.setState(${J(id)}, globalThis.__mallory.fromCopy((${v}).get("value")));`, { solo: true })),
649
+ ownChangeState: (id, entries) =>
650
+ inOrder(() => fromOwnWorker(slot.own, entries, (v) => `const e = ${v};\nreturn globalThis.__mallory.changeState(${J(id)}, e.get("request"), e.get("spec"), e.get("label") || undefined);`, { solo: true })),
651
+ // setValue: hand a page value to the Worker by structured clone (Blobs stay Blobs).
652
+ handoff: (token) => handoffs.get(String(token)),
653
+ // decodeAudio() in pane code, for compressed audio: Web Audio decodes on the page.
654
+ decodeAudio(blob) {
655
+ if (!decodeAudio) throw new Error("decodeAudio(): only WAV can be decoded here");
656
+ return decodeAudio(blob);
657
+ },
658
+ // A pane's create() (worker-runtime.js): may it use on-device AI? The
659
+ // page answers for that pane, asking the person if it must.
660
+ // `waiting(giveUp)`: the page is asking a person (src/ui/ai-ui.js consent), so this pane's calls stop their clocks.
661
+ ...(ai?.ask ? { aiAsk(pane, api, options) { return ai.ask(String(pane), String(api), options ?? undefined, { signal: this?.signal, waiting: (giveUp) => personWaits.wait(slot, String(pane), giveUp) }); } } : {}),
662
+ },
663
+ bridges: { malloryBody: bodyBridge, ...(ai ? { ai: ai.bridge() } : {}) },
664
+ policy: {
665
+ limits: { maxConcurrent: 16 },
666
+ capabilities: { fetch: { maxArgBytes: 10 * 1024 * 1024 }, paneFetch: { maxArgBytes: 10 * 1024 * 1024 }, companionCall: { maxArgBytes: 512 * 1024 }, mcpCall: { maxArgBytes: 512 * 1024 }, a2aCall: { maxArgBytes: 512 * 1024 }, companionWsSend: { maxArgBytes: 128 * 1024 }, crossTabSend: { maxArgBytes: 512 * 1024 }, serialCall: { maxArgBytes: 256 * 1024 }, vfsCall: { maxArgBytes: 12 * 1024 * 1024 }, ...(ai ? aiGateLimits() : {}) },
667
+ },
668
+ }));
669
+ if (slot.disposed) throw (await sandbox.dispose(), new Error("Sandbox is disposed")); // closed while it started
670
+ await sandbox.defineModule("mallory:inspectable", sources.inspectable);
671
+ await sandbox.defineModule("mallory:keys", sources.keys); // src/runtime/keys.js: item keys, keyed changes, canonical JSON
672
+ if (sources.tween) await sandbox.defineModule("mallory:tween", sources.tween); // src/runtime/tween.js: `tween` in pane code
673
+ if (sources.time) await sandbox.defineModule("mallory:time", sources.time); // src/model/nl-time.js: `time` in pane code
674
+ if (sources.units) await sandbox.defineModule("mallory:units", sources.units); // src/units/units.js: `units` in pane code, and the table helper's quantity column
675
+ if (sources.calendar) await sandbox.defineModule("mallory:calendar", await calendarText()); // src/model/calendar.js (bundled): `calendar` in pane code
676
+ if (sources.exact) await sandbox.defineModule("mallory:exact", await exactText()); // src/exact/source.js (bundled): `exact` in pane code
677
+ if (sources.smf) await sandbox.defineModule("mallory:smf", await smfText()); // src/smf-helper/source.js (bundled): `smf` in pane code, the app's own MIDI codec
678
+ if (sources.plot) await sandbox.defineModule("mallory:plot", await plotText()); // src/plot/source.js (bundled with math-sample): `plot` in pane code
679
+ // @johnhenry/math-plus-web's bundle: `mathplus` in pane code. An optional dependency of the CLI: where it isn't installed the Worker starts without it and a pane that asks for it says so.
680
+ if (sources.mathplus) await mathplusText().then((text) => sandbox.defineModule("mallory:mathplus", text)).catch(() => undefined);
681
+ if (sources.geometry) await sandbox.defineModule("mallory:geometry", sources.geometry); // src/geometry/model.js: the geometry pane's construction maths (the page runs the same file)
682
+ if (sources.graph) await sandbox.defineModule("mallory:graph", sources.graph); // src/graph/model.js: the graph pane's maths (the page runs the same file)
683
+ if (sources.clsh) await sandbox.defineModule("mallory:clsh", sources.clsh); // src/clsh/clsh.js: the shell language a shell pane's lines run in (the page imports the same file)
684
+ if (sources.spring) await sandbox.defineModule("mallory:spring", sources.spring); // src/runtime/spring.js: `spring` in pane code
685
+ if (sources.fixed) await sandbox.defineModule("mallory:fixed", sources.fixed); // src/sim/fixed.js: `fixed` in pane code (deterministic fixed-point math)
686
+ if (sources.midi) await sandbox.defineModule("mallory:midi", sources.midi); // src/runtime/midi-input.js: `midi` in pane code
687
+ if (sources.narrative) await sandbox.defineModule("mallory:narrative", sources.narrative); // src/narrative/narrative.js: `narrative` in pane code
688
+ if (sources.tilemap) await sandbox.defineModule("mallory:tilemap", sources.tilemap); // src/tilemap/tilemap.js: `tilemap` in pane code
689
+ if (sources.files) await sandbox.defineModule("mallory:files", sources.files); // src/files/files.js: `files` in pane code
690
+ // src/table/*.js: `table` in pane code. The core and each plugin are modules of their own (virtual modules can't import each other); the manifest lists the plugins to install.
691
+ if (sources.table) {
692
+ for (const [name, text] of Object.entries(sources.table)) await sandbox.defineModule(`mallory:table/${name}`, text);
693
+ await sandbox.defineModule("mallory:table/manifest", `export default ${JSON.stringify(Object.keys(sources.table).filter((n) => n !== "core"))};`);
694
+ }
695
+ if (sources.assets) await sandbox.defineModule("mallory:assets", sources.assets); // src/packages/asset-values.js: `assets` in pane code
696
+ if (sources.docs) await sandbox.defineModule("mallory:docs", sources.docs); // src/documents/documents.js: `docs` in pane code
697
+ // src/bytes/bytes.js and src/serial/framers.js: `bytes` in pane code (the Worker joins them, as the table's)
698
+ for (const [name, text] of Object.entries(sources.bytes ?? {})) await sandbox.defineModule(`mallory:bytes/${name}`, text);
699
+ if (sources.tensor) await sandbox.defineModule("mallory:tensor", sources.tensor); // src/tensor/tensor.js: `tensor` in pane code
700
+ if (sources.wasm) await sandbox.defineModule("mallory:wasm", sources.wasm); // src/runtime/wasm-fuel.js: `wasm` in pane code (fuel-metered WebAssembly)
701
+ if (sources.frame) await sandbox.defineModule("mallory:frame/core", sources.frame); // src/frame/frame.js: `dataframe` in pane code (its library is the lazy codec lib "dataframe")
702
+ if (sources.codec?.core) await sandbox.defineModule("mallory:codec/core", sources.codec.core); // src/codec/core.js: `codecs` in pane code
703
+ if (jthText !== undefined) {
704
+ (slot.jthDefined ??= new WeakSet()).add(sandbox);
705
+ await sandbox.defineModule("mallory:jth", jthText); // asked for before: a restarted Worker has it from the start
706
+ }
707
+ if (aimateyText !== undefined) {
708
+ (slot.aimateyDefined ??= new WeakSet()).add(sandbox);
709
+ await sandbox.defineModule("mallory:aimatey", aimateyText);
710
+ }
711
+ slot.codecDefined = new Set(); // a new Worker has none of the libraries yet
712
+ for (const [name, text] of codecLibs) {
713
+ slot.codecDefined.add(name);
714
+ await sandbox.defineModule(`mallory:codec/${name}`, text);
715
+ }
716
+ if (sources.exporter) await sandbox.defineModule("mallory:export", sources.exporter); // src/export/value.js
717
+ // src/media/*.js, one module each (the browser can't resolve imports between virtual modules)
718
+ for (const [name, text] of Object.entries(sources.media ?? {})) await sandbox.defineModule(`mallory:media/${name}`, text);
719
+ // @johnhenry/iteration's channel modules, each self-contained.
720
+ for (const [name, text] of Object.entries(sources.iteration ?? {})) await sandbox.defineModule(`mallory:iteration/${name}`, text.replace(/^\/\/# sourceMappingURL=.*$/m, ""));
721
+ await sandbox.evaluate(sources.runtime, { timeoutMs: 30000 });
722
+ await sandbox.evaluate(envCode() + (clockAt !== null ? clockCode() : "") + (evaluations.size ? evalCode() : "") + (Object.keys(codecTable).length ? codecCode() : "") + (profiles.size ? profileCode() : "") + (assetTables.size ? assetsCode() : "") + (moduleTables.size ? modulesCode() : "") + (slot.own != null ? "globalThis.__mallory.ownWorker();\n" : ""), { timeoutMs: 30000 });
723
+ if (eventBatchGapMs) await sandbox.evaluate(`globalThis.__mallory.setEventBatchGap(${Number(eventBatchGapMs)});`, { timeoutMs: 30000 });
724
+ if (slot.disposed) throw (await sandbox.dispose(), new Error("Sandbox is disposed")); // closed while it started
725
+ }
726
+
727
+ /**
728
+ * Replace a slot's Worker (a timeout, a restart): the old sandbox is
729
+ * disposed, so the calls still waiting in it fail at once (and their own
730
+ * timeouts can't restart the Worker that replaces it), and a new one boots.
731
+ * Calls made meanwhile wait for it.
732
+ */
733
+ function replace(slot) {
734
+ slot.generation++;
735
+ slot.runs = new Map(); // what ran in the old one ends with it
736
+ const old = slot.sandbox;
737
+ slot.sandbox = undefined;
738
+ const previous = slot.ready;
739
+ slot.ready = (async () => {
740
+ await previous?.catch(() => {}); // one Worker starting at a time
741
+ // A Worker still starting when it was replaced (a restart right after a canvas opens) lands in `slot.sandbox` when it is
742
+ // up, after `old` was read: it is an old Worker too, and must not be the one boot() finds and keeps (its CSP is the old one).
743
+ const late = slot.sandbox;
744
+ slot.sandbox = undefined;
745
+ await Promise.all([old?.dispose(), late?.dispose()]);
746
+ if (!slot.disposed) await boot(slot);
747
+ })();
748
+ slot.ready.catch(() => {}); // a Worker that doesn't start says so on its next call
749
+ return slot.ready;
750
+ }
751
+
752
+ /** Load the jth bundle once and define it in every Worker that doesn't have it yet (and, through boot, in each Worker that starts later). */
753
+ function loadJth() {
754
+ if (!sources.jth) return Promise.reject(new Error("this runtime has no jth support"));
755
+ jthLoading ??= (async () => {
756
+ jthText ??= await (typeof sources.jth === "function" ? sources.jth() : sources.jth);
757
+ for (const slot of slots()) {
758
+ await slot.ready?.catch(() => {});
759
+ if (slot.sandbox && !slot.jthDefined?.has(slot.sandbox)) {
760
+ (slot.jthDefined ??= new WeakSet()).add(slot.sandbox);
761
+ await slot.sandbox.defineModule("mallory:jth", jthText);
762
+ }
763
+ }
764
+ })().catch((error) => {
765
+ jthLoading = undefined; // a load that failed is tried again by the next call
766
+ throw error;
767
+ });
768
+ return jthLoading;
769
+ }
770
+
771
+ /** Load the Aimatey bundle once and define it in every Worker that doesn't have it yet (and, through boot, in each Worker that starts later). */
772
+ function loadAimatey() {
773
+ if (!sources.aimatey) return Promise.reject(new Error("this runtime has no aimatey support"));
774
+ aimateyLoading ??= (async () => {
775
+ aimateyText ??= await (typeof sources.aimatey === "function" ? sources.aimatey() : sources.aimatey);
776
+ for (const slot of slots()) {
777
+ await slot.ready?.catch(() => {});
778
+ if (slot.sandbox && !slot.aimateyDefined?.has(slot.sandbox)) {
779
+ (slot.aimateyDefined ??= new WeakSet()).add(slot.sandbox);
780
+ await slot.sandbox.defineModule("mallory:aimatey", aimateyText);
781
+ }
782
+ }
783
+ })().catch((error) => {
784
+ aimateyLoading = undefined; // a load that failed is tried again by the next call
785
+ throw error;
786
+ });
787
+ return aimateyLoading;
788
+ }
789
+
790
+ /** Load codec libraries (by name) once and define each in every Worker, now and after a restart (boot). */
791
+ function loadCodecLibs(names) {
792
+ const wanted = [];
793
+ for (const name of names) {
794
+ if (codecLibs.has(name)) continue;
795
+ if (!codecLoading.has(name)) {
796
+ const loading = (async () => {
797
+ const text = await sources.codec.libs(name);
798
+ codecLibs.set(name, text);
799
+ for (const slot of slots()) {
800
+ await slot.ready?.catch(() => {});
801
+ if (slot.sandbox && !slot.codecDefined.has(name)) {
802
+ slot.codecDefined.add(name);
803
+ await slot.sandbox.defineModule(`mallory:codec/${name}`, text);
804
+ }
805
+ }
806
+ })().finally(() => codecLoading.delete(name));
807
+ codecLoading.set(name, loading);
808
+ }
809
+ wanted.push(codecLoading.get(name));
810
+ }
811
+ return Promise.all(wanted);
812
+ }
813
+
814
+ /** A pane's own Worker, made on first use. */
815
+ function ownSlot(id) {
816
+ let slot = ownSlots.get(id);
817
+ if (!slot) {
818
+ slot = newSlot(id);
819
+ slot.ready = boot(slot);
820
+ slot.ready.catch(() => {});
821
+ ownSlots.set(id, slot);
822
+ }
823
+ return slot;
824
+ }
825
+
826
+ /** A pane's own Worker goes (deleted, set back to the shared sandbox, a restart): its onCleanup runs first, briefly. */
827
+ function dropOwn(id) {
828
+ const slot = ownSlots.get(id);
829
+ if (!slot) return Promise.resolve();
830
+ ownSlots.delete(id);
831
+ ownRuns.delete(id);
832
+ ownStates.delete(id);
833
+ if (slot.link) call(`return globalThis.__mallory.unlinkOwn(${J(id)});`, { solo: true }).catch(() => {}); // the shared Worker's end of their channel
834
+ // Once it has started (a Worker still starting would otherwise be left running), its cleanups, then it goes.
835
+ const bye = slot.ready.catch(() => {}).then(() => slot.sandbox?.evaluate(`globalThis.__mallory.forget(${J(id)});`, { timeoutMs: 2000 }).catch(() => {}));
836
+ return bye.then(() => {
837
+ slot.disposed = true;
838
+ slot.generation++;
839
+ return slot.sandbox?.dispose();
840
+ });
841
+ }
842
+
843
+ shared.ready = boot(shared);
844
+
845
+ /**
846
+ * `value` handed to a Worker by structured clone (a capability's reply, so no
847
+ * JSON on the way, and Blobs stay Blobs): `codeOf(expr)` is the call's code,
848
+ * `expr` the expression that gets it there.
849
+ */
850
+ async function viaHandoff(value, codeOf, options) {
851
+ const token = String(++handoffSeq);
852
+ handoffs.set(token, value);
853
+ try {
854
+ return await call(codeOf(`(await host.call("handoff", ${J(token)}))`), options);
855
+ } finally {
856
+ handoffs.delete(token);
857
+ }
858
+ }
859
+
860
+ /** Hand a page value to the Worker by structured clone (Blobs stay Blobs, no copy through JSON) and store it. */
861
+ function handOver({ id, runId, value, view, effects = false }) {
862
+ return viaHandoff(value, (v) => finishing(id, runId, `globalThis.__mallory.set(${J(id)}, ${runId}, ${v}, ${J(view)})`, { effects }), { pane: id });
863
+ }
864
+
865
+ // Copies on their way between Workers: a Map that only this page
866
+ // holds (a copy out of one Worker, on its way into another) gives its
867
+ // ArrayBuffers to the Worker it goes to, instead of a second copy of them,
868
+ // when the Worker factory can move them (`transfer`: the page's CSP Workers,
869
+ // src/network/csp-frame.js; not Node's). The Worker that made it said
870
+ // whether it holds any (`binary`), so a big value of plain data isn't walked.
871
+ const transferable = (map) => (transfer && map instanceof Map && map.get("binary") ? markTransfer(map) : map);
872
+
873
+ // What a pane's own Worker hands the shared sandbox in the background (its
874
+ // setters' changes, its events) is stored there in the order it was sent.
875
+ let ownChain = Promise.resolve();
876
+ function inOrder(step) {
877
+ const run = ownChain.then(step);
878
+ ownChain = run.catch(() => {});
879
+ return run;
880
+ }
881
+
882
+ /**
883
+ * Events and channel sends from a pane's own Worker: kept in the shared sandbox, as a pane's there are; the list as the page hears it from one.
884
+ * `map` is the Worker's `{ list }`, or its ticket on the channel of pane `owner`'s own Worker.
885
+ */
886
+ function forwardEvents(id, map, owner = id) {
887
+ return inOrder(() => fromOwnWorker(owner, map, (v) => `return globalThis.__mallory.ownEvents(${J(id)}, (${v}).get("list"));`, { solo: true }));
888
+ }
889
+
890
+ // The direct channel: with `channel`, the shared Worker and each
891
+ // pane's own Worker get the two ends of a MessageChannel (worker-runtime.js
892
+ // linkOwn, linkShared), handed over as a capability's reply with the port in
893
+ // its transfer list (the TRANSFER mark, src/runtime/transfer.js, honoured by
894
+ // the page's Worker factories). A copy then goes straight from one Worker to
895
+ // the other, with a ticket; this page only passes the ticket on. A new Worker
896
+ // on either side (a restart, a timeout) needs a new channel: made on the
897
+ // pane's next run. Calls that were waiting on an old one fail as calls in a
898
+ // Worker that went do ("Stopped: …"), and their panes run again.
899
+ const channelStats = { links: 0, in: 0, out: 0 }; // channels made; copies sent into own Workers on one, and out of them
900
+ let ticketSeq = 0;
901
+ /** How long a Worker waits for a copy on the channel, within a call of `timeout`: well inside it, so a lost copy never times the call out. */
902
+ const linkWait = (pane, timeout = timeoutMs) => Math.max(50, Math.min(2000, Math.floor((paneTimeouts.get(String(pane)) ?? timeout) / 2)));
903
+ const portMap = (port) => new Map([["port", port], [TRANSFER, [port]]]);
904
+
905
+ /** The channel between the shared Worker and own Worker `slot`, made (again) when either is new since. Resolves true when there is one. */
906
+ function linked(slot) {
907
+ if (!channel || typeof MessageChannel !== "function" || slot.disposed) return Promise.resolve(false);
908
+ const s = shared.generation;
909
+ const o = slot.generation;
910
+ if (slot.link?.s === s && slot.link.o === o) return slot.link.ready;
911
+ const { port1, port2 } = new MessageChannel();
912
+ const id = slot.own;
913
+ const ready = (async () => {
914
+ await Promise.all([
915
+ viaHandoff(portMap(port1), (v) => `return globalThis.__mallory.linkOwn(${J(id)}, (${v}).get("port"));`, { solo: true }),
916
+ viaHandoff(portMap(port2), (v) => `return globalThis.__mallory.linkShared((${v}).get("port"));`, { slot }),
917
+ ]);
918
+ if (shared.generation !== s || slot.generation !== o) return false; // a Worker was replaced meanwhile: its next run links again
919
+ channelStats.links++;
920
+ return true;
921
+ })().catch(() => false);
922
+ slot.link = { s, o, ready };
923
+ return ready;
924
+ }
925
+
926
+ /**
927
+ * Copies of what pane `id` in own Worker `slot` reads: `{ ticket }` when the shared Worker sent them
928
+ * straight to it on their channel, else `{ payload }`, copyIn's Map, to hand over through this page.
929
+ */
930
+ async function readsInto(id, slot, reads, event) {
931
+ const direct = slot ? await linked(slot) : false; // linked even with nothing to read: its value comes back on the channel too
932
+ if (direct && (reads.keys.length || event !== undefined)) {
933
+ const ticket = ++ticketSeq;
934
+ const to = { pane: slot.own, ticket };
935
+ await call(`return globalThis.__mallory.copyOut(${J(reads.keys)}, ${J(reads.names)}, ${event !== undefined ? J(event) : "undefined"}, ${J(to)});`, { pane: id, solo: true });
936
+ channelStats.in++;
937
+ return { ticket };
938
+ }
939
+ return { payload: await copyIn(id, reads, event) };
940
+ }
941
+
942
+ /** A call into a pane's own Worker whose code (`codeOf(expr)`) reads the copies readsInto made (`got`). */
943
+ function intoOwn(id, got, codeOf, options) {
944
+ if (got.ticket !== undefined) return call(codeOf(`(await globalThis.__mallory.fromShared(${got.ticket}, ${linkWait(id, options.timeout)}))`), options);
945
+ return viaHandoff(transferable(got.payload), codeOf, options);
946
+ }
947
+
948
+ /**
949
+ * A call into the shared Worker whose code (`codeOf(expr)`) takes `payload`, a copy from pane `owner`'s own
950
+ * Worker: through this page (a handoff), or a ticket for the copy it sent on their channel.
951
+ */
952
+ function fromOwnWorker(owner, payload, codeOf, options) {
953
+ const ticket = payload instanceof Map ? payload.get("ticket") : undefined;
954
+ if (ticket === undefined) return viaHandoff(transferable(payload), codeOf, options);
955
+ channelStats.out++;
956
+ return call(codeOf(`(await globalThis.__mallory.fromOwn(${J(String(owner))}, ${Number(ticket)}, ${linkWait(options.pane ?? owner)}))`), options);
957
+ }
958
+
959
+ /** A copy sent on the channel that nothing will take. */
960
+ function dropTicket(owner, ticket) {
961
+ call(`return globalThis.__mallory.dropFromOwn(${J(String(owner))}, ${Number(ticket)});`, { solo: true }).catch(() => {});
962
+ }
963
+
964
+ /**
965
+ * Store what a pane's own Worker made in the shared sandbox, which
966
+ * keeps it as it keeps any pane's value: `payload` is its copy (or skip), a
967
+ * Map (worker-runtime.js ownOut). `plain`: a live value, stored as an
968
+ * emit is, without the run's extras; else its run's reply carries them, with
969
+ * `effects` and `state` from its own Worker. Never batched.
970
+ */
971
+ function storeOwn({ id, runId, payload, view = "auto", plain = false, effects = false, state }) {
972
+ const store = (v) => `globalThis.__mallory.setOwn(${J(id)}, ${Number(runId)}, ${v}, ${J(view)})`;
973
+ return fromOwnWorker(id, payload, (v) => (plain ? `return ${store(v)};` : finishing(id, runId, store(v), { effects, own: true, state })), { pane: id, solo: true });
974
+ }
975
+
976
+ /** exec's arguments after its pane id and run id, as worker-runtime.js exec (and runOwn) take them. */
977
+ const execArgs = ({ sources, names, code, mode, view, label, setters = [], skipped = [], fresh = false, events = [], event, eventInput, keep, restoreState, stateBytes }) =>
978
+ `${J(sources)}, ${J(names)}, ${J(paneBody(code, mode))}, ${J(view)}, ${J(label)}, console, ${J(setters)}, ${J(skipped)}, ${J(Boolean(fresh))}, ${J({ events, ...(event !== undefined ? { event } : {}), ...(eventInput !== undefined ? { eventInput } : {}), ...(keep !== undefined ? { keep } : {}), ...(typeof restoreState === "string" ? { restoreState } : {}), ...(stateBytes ? { stateBytes } : {}) })}`;
979
+
980
+ // A pane's own Worker reads copies: of its inputs (not the skipped
981
+ // ones), and of the state panes its setters write to, so a setter's
982
+ // function form (setX(x => …)) sees the value. Its latest run's, by pane id,
983
+ // for a live step that copies them again (an input changed) and its values' view.
984
+ const ownRuns = new Map(); // pane id -> { keys, names, view, sources, setters }
985
+ function ownReads({ sources, names, skipped = [], setters = [] }) {
986
+ const keys = [];
987
+ const labels = [];
988
+ sources.forEach((s, i) => {
989
+ if (skipped.includes(s) || keys.includes(s)) return;
990
+ keys.push(s);
991
+ labels.push(names[i]);
992
+ });
993
+ for (const { source, name } of setters) {
994
+ if (keys.includes(source)) continue;
995
+ keys.push(source);
996
+ labels.push(`${name}()'s state`);
997
+ }
998
+ return { keys, names: labels };
999
+ }
1000
+
1001
+ /** Copies of `keys` (named `names`) and of event `event`'s (a reader's) out of the shared sandbox, as a Map loadOwn takes. */
1002
+ function copyIn(id, { keys, names }, event) {
1003
+ if (!keys.length && event === undefined) return Promise.resolve(new Map([["keys", []], ["values", []]]));
1004
+ return call(`return globalThis.__mallory.copyOut(${J(keys)}, ${J(names)}${event !== undefined ? `, ${J(event)}` : ""});`, { pane: id, solo: true });
1005
+ }
1006
+
1007
+ /** A pane's own Worker takes new copies of what it reads (`skipped`: the inputs skipped now), ahead of `code`. */
1008
+ async function recopy(id, skipped, code, options) {
1009
+ const run = ownRuns.get(String(id));
1010
+ if (!run) return call(code, options);
1011
+ const got = await readsInto(id, options.slot, ownReads({ sources: run.sources, names: run.names, skipped, setters: run.setters }));
1012
+ return intoOwn(id, got, (v) => `globalThis.__mallory.ownInputs(${v});\n${code}`, options);
1013
+ }
1014
+
1015
+ /** What a call into a pane's own Worker answered: ownOut's Map is a value, stored in the shared sandbox (`plain`: a live one); anything else as it is. */
1016
+ const settleOwn = (id, runId, answer, view) => (answer instanceof Map ? storeOwn({ id, runId, payload: answer, view, plain: true }) : answer);
1017
+
1018
+ // A pane's own Worker's `state` as JSON after its last run there (`{ text, code, mode }`), for a run that had to
1019
+ // end the Worker an older run was still going in (supersedeOwn): it gets that `state` back, as after a restart.
1020
+ const ownStates = new Map();
1021
+
1022
+ /**
1023
+ * Run `runId` of pane `key` starts in its own Worker. Calls of its older runs that haven't started are
1024
+ * refused from now on (they are superseded). A run still going there that started before the shared Worker was
1025
+ * last replaced ends now, with its Worker: a timeout in the shared sandbox leaves own Workers running and reruns
1026
+ * their panes, and the old run, left going next to the rerun, would end the Worker and the rerun with it when its
1027
+ * own timeout came. Its value would only have gone to the shared Worker that is gone. (A run superseded with no
1028
+ * restart between, by an input or a setter, is left to finish, as in the shared sandbox: its Worker and `state`
1029
+ * stay.) Returns whether it replaced the Worker.
1030
+ */
1031
+ function supersedeOwn(key, runId) {
1032
+ const slot = ownSlots.get(key);
1033
+ const run = Number(runId);
1034
+ if (!slot || !(run > slot.newest)) return false;
1035
+ slot.newest = run;
1036
+ if (![...slot.runs].some(([r, { shared: gen }]) => r < run && gen !== shared.generation)) return false;
1037
+ replace(slot);
1038
+ return true;
1039
+ }
1040
+
1041
+ /** `state` (JSON) for a run that ended its Worker's older run (supersedeOwn), when the caller has none: its last, if made by the same code. */
1042
+ function stateAfterSupersede(key, { restoreState, fresh, code, mode }) {
1043
+ if (restoreState !== undefined || fresh) return restoreState;
1044
+ const kept = ownStates.get(key);
1045
+ return kept && kept.code === code && kept.mode === mode ? kept.text : undefined;
1046
+ }
1047
+
1048
+ /**
1049
+ * Run an eval pane in its own Worker: its inputs are copied out of the
1050
+ * shared sandbox into it, its code runs there (a timeout restarts only that
1051
+ * Worker), and its value is copied back into the shared sandbox, which keeps
1052
+ * it as it keeps any pane's (readers, previews, exports, the cut-off and the
1053
+ * run log work as usual). What needs the shared sandbox (live values, events,
1054
+ * channels, setters) is forwarded to it by copy. None of its calls is
1055
+ * batched, not even the ones to the shared sandbox (`solo`).
1056
+ */
1057
+ async function execOwn(args) {
1058
+ const { id, runId, code, mode, view, event } = args;
1059
+ const key = String(id);
1060
+ if (supersedeOwn(key, runId)) args = { ...args, restoreState: stateAfterSupersede(key, args) };
1061
+ const reads = ownReads(args);
1062
+ // With a channel its Worker is made first, so the shared one can send it the copies; else they are checked first.
1063
+ const got = await readsInto(id, channel ? ownSlot(key) : null, reads, event);
1064
+ const slot = ownSlot(key);
1065
+ ownRuns.set(key, { ...reads, sources: args.sources, names: args.names, setters: args.setters ?? [], view, code, mode });
1066
+ const want = runWants.get(key);
1067
+ const stateBytes = want?.runId === Number(runId) ? want.json?.restoreBytes : undefined;
1068
+ const out = await intoOwn(id, got, (v) => `return await globalThis.__mallory.runOwn(${v}, ${J(id)}, ${runId}, ${execArgs({ ...args, stateBytes })});`, { pane: id, timeout: timeFor(code), slot, run: runId });
1069
+ return ownAnswer(id, runId, view, out);
1070
+ }
1071
+
1072
+ /** runOwn's (or eachFinishOwn's) answer: `{ result }` as it is (an emitter's first value stored), or the value stored with its run's extras. */
1073
+ async function ownAnswer(id, runId, view, out) {
1074
+ const key = String(id);
1075
+ if (out.has("out")) {
1076
+ const run = ownRuns.get(key);
1077
+ const text = out.get("state");
1078
+ if (typeof text === "string") ownStates.set(key, { text, code: run?.code, mode: run?.mode }); // for a run that has to replace this Worker
1079
+ else ownStates.delete(key);
1080
+ }
1081
+ if (out.has("result")) {
1082
+ const result = out.get("result");
1083
+ if (result?.live === "emit" && result.first instanceof Map) return { ...result, first: await storeOwn({ id, runId, payload: result.first, view, plain: true }) };
1084
+ return result;
1085
+ }
1086
+ return storeOwn({ id, runId, payload: out.get("out"), view, effects: Boolean(out.get("effects")), state: out.get("state") });
1087
+ }
1088
+
1089
+ // Batched calls: calls for panes under a registered prefix (a
1090
+ // repeater's instances, `<pane>/@`; batchUnder) made in one task go to the
1091
+ // Worker as one evaluation (worker-runtime.js batch), up to BATCH_MAX each,
1092
+ // instead of a round trip each. Each call still answers on its own, as soon
1093
+ // as it settles there. Not a call with a timeout of its own (a pane's, or
1094
+ // on-device AI's): a batch has one, counted from when it was sent. Not a
1095
+ // call to a pane's own Worker, nor a `solo` one (a pane in its own
1096
+ // Worker). Any other call sends the waiting batch first, so the Worker sees
1097
+ // calls in the order they were made (a pane's run, then its forget).
1098
+ const batchPrefixes = new Map(); // prefix -> how many registered it
1099
+ const batchQueue = [];
1100
+ let batchSeq = 0;
1101
+ const callStats = { evaluations: 0, batches: 0, batched: 0 };
1102
+
1103
+ // Strict panes (./strict.js): their code runs in the QuickJS-WASM engine, one run at a time; their
1104
+ // inputs come out of the shared sandbox as JSON and their value goes back into it as JSON, stored like
1105
+ // any pane's. The newest run of each, so an older one that finishes later is superseded.
1106
+ const strictRunner = strict ? createStrictRunner({ createSandbox: makeSandbox, options: strict.options ?? (() => ({})), onConsole }) : null;
1107
+ const strictNewest = new Map(); // pane id -> its newest run id
1108
+
1109
+ async function execStrict({ id, runId, sources, names, code, mode, view, skipped = [], pane }) {
1110
+ if (!strictRunner) throw new Error("strict mode isn't available here: this runtime has no QuickJS-WASM engine. Turn strict mode off to run it in the sandbox Worker.");
1111
+ const key = String(id);
1112
+ strictNewest.set(key, Number(runId));
1113
+ if (ownSlots.has(key)) await dropOwn(key); // it ran in its own Worker before
1114
+ const keys = [];
1115
+ const labels = [];
1116
+ sources.forEach((s, i) => {
1117
+ if (skipped.includes(s)) return;
1118
+ keys.push(s);
1119
+ labels.push(names[i]);
1120
+ });
1121
+ const inputsText = keys.length ? await call(`return globalThis.__mallory.strictIn(${J(keys)}, ${J(labels)}, ${STRICT_MAX_INPUT});`, { pane: id }) : "{}";
1122
+ const limits = strictConfig(pane);
1123
+ const { value, fuelUsed } = await strictRunner.run({ pane: key, body: paneBody(code, mode), names, inputsText, limits });
1124
+ if (strictNewest.get(key) !== Number(runId)) return { superseded: true };
1125
+ const stored = value === undefined ? "undefined" : `JSON.parse(${J(J(value))})`;
1126
+ const result = await call(finishing(id, runId, `globalThis.__mallory.set(${J(id)}, ${Number(runId)}, ${stored}, ${J(view)})`), { pane: id });
1127
+ return result && typeof result === "object" ? { ...result, strict: { fuelUsed, fuel: limits.fuel } } : result;
1128
+ }
1129
+
1130
+ /** A call into the shared Worker, or (`slot`) into a pane's own one. */
1131
+ function call(code, { pane = null, timeout = timeoutMs, slot = shared, solo = false, run } = {}) {
1132
+ // Code that names `dataframe` needs its library (math-plus's Frame and Parquet bridge, a 760 KB chunk) in every Worker first: it is
1133
+ // fetched once, the first time, and defined like a codec library.
1134
+ if (!codecLibs.has("dataframe") && sources.frame && sources.codec?.libs && /\bdataframe\b/.test(code)) return loadCodecLibs(["dataframe"]).then(() => call(code, { pane, timeout, slot, solo, run }));
1135
+ if (pane != null && paneTimeouts.has(String(pane))) timeout = paneTimeouts.get(String(pane)); // the pane's own timeout wins
1136
+ // A pane's own Worker has nothing to batch with, and the shared Worker's order doesn't involve it. `run`: the run it is for.
1137
+ if (slot !== shared) return evaluate(code, { pane, timeout, slot, run });
1138
+ if (!solo && pane != null && timeout === timeoutMs && batchPrefixes.size) {
1139
+ const id = String(pane);
1140
+ for (const prefix of batchPrefixes.keys()) if (id.startsWith(prefix)) return queueBatched(code, id);
1141
+ }
1142
+ if (batchQueue.length) flushBatched();
1143
+ return evaluate(code, { pane, timeout });
1144
+ }
1145
+
1146
+ function queueBatched(code, pane) {
1147
+ return new Promise((resolve, reject) => {
1148
+ batchQueue.push({ code, pane, resolve, reject });
1149
+ if (batchQueue.length === 1) afterThisTask(flushBatched);
1150
+ });
1151
+ }
1152
+
1153
+ function flushBatched() {
1154
+ const ops = batchQueue.splice(0);
1155
+ for (let i = 0; i < ops.length; i += BATCH_MAX) sendBatch(ops.slice(i, i + BATCH_MAX));
1156
+ }
1157
+
1158
+ /**
1159
+ * One evaluation for `ops`; the ones still running come back from batchMore
1160
+ * as they settle. When the Worker is replaced meanwhile (another call
1161
+ * timed out, a restart), the old one is disposed: the evaluation in flight
1162
+ * fails at once, and so does every op still open, with "Stopped: the
1163
+ * sandbox was restarted while this ran." (they rerun). When the batch itself
1164
+ * times out, the ops still open are the ones that ran past it: the restart
1165
+ * names them (`reason.pane`, a list), so they fail instead of hanging again.
1166
+ */
1167
+ async function sendBatch(ops) {
1168
+ if (ops.length === 1) return evaluate(ops[0].code, { pane: ops[0].pane }).then(ops[0].resolve, ops[0].reject);
1169
+ const id = ++batchSeq;
1170
+ callStats.batches++;
1171
+ callStats.batched += ops.length;
1172
+ const open = new Map(ops.map((op, i) => [i, op]));
1173
+ const timeout = timeoutMs;
1174
+ const sent = Date.now();
1175
+ const stillOpen = () => [...open.values()].map((op) => op.pane);
1176
+ const gen = shared.generation;
1177
+ try {
1178
+ let answer = await evaluate(`return await globalThis.__mallory.batch(${id}, [\n${ops.map((op) => `async (console) => {\n${op.code}\n}`).join(",\n")}\n], ${J(ops.map((op) => op.pane))}, console);`, { timeout, panes: stillOpen });
1179
+ for (;;) {
1180
+ for (const [i, ok, value] of answer?.done ?? []) {
1181
+ const op = open.get(i);
1182
+ open.delete(i);
1183
+ if (ok) op?.resolve(value);
1184
+ else op?.reject(sandboxError(value));
1185
+ }
1186
+ if (!open.size || !answer?.left) break;
1187
+ if (shared.generation !== gen) throw stopped(shared); // the ones left went with the old Worker
1188
+ // The ones still running have what is left of the batch's timeout (as each call had its own).
1189
+ answer = await evaluate(`return await globalThis.__mallory.batchMore(${id});`, { timeout: Math.max(1, timeout - (Date.now() - sent)), said: timeout, panes: stillOpen });
1190
+ }
1191
+ if (open.size) throw new Error("A batched call got no answer.");
1192
+ } catch (error) {
1193
+ for (const op of open.values()) op.reject(error);
1194
+ }
1195
+ }
1196
+
1197
+ /**
1198
+ * One evaluation in a Worker (`slot`: the shared one, or a pane's own).
1199
+ * A timeout or abort restarts it; `said`: the timeout the message names (a
1200
+ * batch's); `panes()`: the panes it ran for (a batch's ops still open),
1201
+ * when it isn't one pane's.
1202
+ */
1203
+ async function evaluate(code, { pane = null, timeout = timeoutMs, said = timeout, slot = shared, panes, run } = {}) {
1204
+ // A pane's own Worker: the calls each run has in flight, so a newer run can end an older one first (supersedeOwn).
1205
+ const runs = slot.own != null && run !== undefined ? slot.runs : null;
1206
+ if (runs) {
1207
+ const entry = runs.get(Number(run)) ?? { n: 0, shared: shared.generation };
1208
+ entry.n++;
1209
+ runs.set(Number(run), entry);
1210
+ }
1211
+ // Calls reach a Worker in the order they were made (a pane's value set, then the same pane's newer value): a call that waits for a
1212
+ // restart's new Worker and one made later would otherwise start in the order their waits end, and the older value would land last.
1213
+ const turn = takeTurn(slot);
1214
+ try {
1215
+ for (let r = slot.ready; ; r = slot.ready) if ((await r, r === slot.ready)) break; // a restart meanwhile: its new Worker
1216
+ if (turn.before) await turn.before; // the calls made before this one have started
1217
+ turn.start();
1218
+ if (slot.disposed) throw new Error(slot.own != null ? "Stopped: this pane's own Worker was closed." : "Sandbox is disposed");
1219
+ if (runs && Number(run) < slot.newest) throw stopped(slot); // a newer run of its pane started meanwhile: this one is superseded
1220
+ return await evaluateIn(slot, code, { pane, timeout, said, panes });
1221
+ } finally {
1222
+ turn.start();
1223
+ const entry = runs?.get(Number(run));
1224
+ if (entry && --entry.n <= 0) runs.delete(Number(run));
1225
+ }
1226
+ }
1227
+
1228
+ const tails = new WeakMap(); // slot -> the last call made to it: { promise, settled }
1229
+ /**
1230
+ * This call's place in line for `slot`: `before` resolves once the calls made earlier have started (undefined when they all have, so a
1231
+ * call that never waited adds no delay), `start()` says this one has.
1232
+ */
1233
+ function takeTurn(slot) {
1234
+ const previous = tails.get(slot);
1235
+ const mine = { settled: false };
1236
+ mine.promise = new Promise((resolve) => (mine.resolve = resolve));
1237
+ tails.set(slot, mine);
1238
+ return {
1239
+ before: previous && !previous.settled ? previous.promise : undefined,
1240
+ start() {
1241
+ if (mine.settled) return;
1242
+ mine.settled = true;
1243
+ mine.resolve();
1244
+ },
1245
+ };
1246
+ }
1247
+
1248
+ async function evaluateIn(slot, code, { pane, timeout, said, panes }) {
1249
+ callStats.evaluations++;
1250
+ if (codecLoading.size) await Promise.allSettled([...codecLoading.values()]); // a codec library being loaded is in the Worker before a call that may use it
1251
+ const gen = slot.generation;
1252
+ if (slot.envDirty) {
1253
+ slot.envDirty = false;
1254
+ code = envCode() + code;
1255
+ }
1256
+ if (slot.clockDirty) {
1257
+ slot.clockDirty = false;
1258
+ code = clockCode() + code;
1259
+ }
1260
+ if (slot.evalDirty) {
1261
+ slot.evalDirty = false;
1262
+ code = evalCode() + code;
1263
+ }
1264
+ if (slot.assetsDirty) {
1265
+ slot.assetsDirty = false;
1266
+ code = assetsCode() + code;
1267
+ }
1268
+ if (moduleTables.size) await ensureModules(slot); // a package module this Worker hasn't got yet (a new one, or a restarted Worker)
1269
+ if (slot.modulesDirty) {
1270
+ slot.modulesDirty = false;
1271
+ code = modulesCode() + code;
1272
+ }
1273
+ if (slot.profileDirty) {
1274
+ slot.profileDirty = false;
1275
+ code = profileCode() + code;
1276
+ }
1277
+ if (slot.codecDirty) {
1278
+ slot.codecDirty = false;
1279
+ code = codecCode() + code;
1280
+ }
1281
+ // The call's clock is ours, not andbox's: it stops while the pane waits for a person (personWaits).
1282
+ // When it runs out, the abort ends the Worker as andbox's own timeout would.
1283
+ const kill = new AbortController();
1284
+ let timedOutHere = false;
1285
+ const end = personWaits.start({
1286
+ where: slot,
1287
+ panes: () => (panes ? panes() : pane == null ? [] : [String(pane)]).map(String),
1288
+ ms: timeout,
1289
+ onTimeout: () => {
1290
+ timedOutHere = true;
1291
+ kill.abort();
1292
+ },
1293
+ });
1294
+ let out;
1295
+ try {
1296
+ out = await slot.sandbox.evaluate(`try {\n${code}\n} catch (__malloryError) {\nreturn globalThis.__mallory.thrown(__malloryError);\n}`, {
1297
+ timeoutMs: 0,
1298
+ signal: kill.signal,
1299
+ // andbox (0.3.1, andbox#41) sends this call's console output here and
1300
+ // nowhere else, even when panes run at the same time; output after the
1301
+ // call returned goes to the sandbox-level handler above, named by
1302
+ // `consoleId`.
1303
+ ...(pane == null ? {} : { consoleId: String(pane) }),
1304
+ onConsole(level, ...args) {
1305
+ onConsole?.(typeof this?.consoleId === "string" ? this.consoleId : pane, level, args);
1306
+ },
1307
+ });
1308
+ } catch (error) {
1309
+ // Its Worker was replaced while it ran (another call timed out, a restart): it ended with it.
1310
+ if (gen !== slot.generation) throw stopped(slot);
1311
+ // A timeout or abort hard-kills the Worker: every value in it is gone.
1312
+ if (isKill(error)) {
1313
+ replace(slot);
1314
+ const after = timedOutHere ? timedOut({ name: "TimeoutError" }, said) : timedOut(error, said);
1315
+ if (slot.own != null) throw Object.assign(new Error(`${after} It runs in its own Worker, which was restarted: no other pane was affected.`), { ownWorker: true, pane });
1316
+ // The shared sandbox: the canvas puts back the values it can, reruns the rest, and leaves the pane that timed out (`pane`, or a batch's list) failed.
1317
+ const reason = Object.assign(new Error(`${after} The sandbox was restarted: this pane stops here until it runs again (an edit or ▶), and the other panes keep their values where they can (the rest rerun).`), { pane: panes ? panes() : pane });
1318
+ onRestart?.(reason);
1319
+ throw reason;
1320
+ }
1321
+ // The Worker itself died (its heap ran out, or it crashed): the sandbox cannot run anything more, so it is replaced like a timed-out one.
1322
+ if (/worker exited with code|ERR_WORKER_OUT_OF_MEMORY|reaching memory limit|heap out of memory/i.test(String(error?.message ?? ""))) { // only a Worker that has died: an uncaught error in one that is alive is the pane's own error
1323
+ replace(slot);
1324
+ const after = "This pane used more memory than a Worker has (or crashed it).";
1325
+ if (slot.own != null) throw Object.assign(new Error(`${after} It runs in its own Worker, which was restarted: no other pane was affected.`), { ownWorker: true, pane });
1326
+ const reason = Object.assign(new Error(`${after} The sandbox was restarted: this pane stops here until it runs again, and the other panes keep their values where they can.`), { pane });
1327
+ onRestart?.(reason);
1328
+ throw reason;
1329
+ }
1330
+ throw error;
1331
+ } finally {
1332
+ end();
1333
+ }
1334
+ // The code threw: its error, whatever its name, is the call's; the Worker is fine.
1335
+ if (out instanceof Map && out.has(THROWN)) throw sandboxError(out.get(THROWN));
1336
+ return out;
1337
+ }
1338
+
1339
+ const timedOut = (error, timeout) => (error.name === "TimeoutError" ? `Timed out after ${Math.round(timeout / 1000)}s.` : "Stopped.");
1340
+ const stopped = (slot) => Object.assign(new Error(slot.own != null ? "Stopped: this pane's own Worker was restarted while it ran." : "Stopped: the sandbox was restarted while this ran."), { restarted: true });
1341
+
1342
+ return {
1343
+ /**
1344
+ * A request a pane type makes on its own (the http pane's send mode, src/model/http-send.js), through the same `network` every pane's own
1345
+ * fetch uses: the canvas's policy decides it (a host with no grant is refused and asks the person) and fills in secret() placeholders.
1346
+ * `context.pane` is the pane's sandbox id; the answer is the policy's response ({ status, statusText, headers, body, url, redirected }).
1347
+ * `context.maxBytes` and `context.timeoutMs` say what the caller expects (the soundfont loader): the transport stops reading at the size and gives up at the time.
1348
+ */
1349
+ request(url, init, context = {}) {
1350
+ return send(String(url), init, { pane: context.pane == null ? undefined : String(context.pane), signal: context.signal, ...(context.redirects === "same-host" ? { redirects: "same-host" } : {}), ...(context.maxBytes > 0 ? { maxBytes: context.maxBytes } : {}), ...(context.timeoutMs > 0 ? { timeoutMs: context.timeoutMs } : {}) });
1351
+ },
1352
+ /**
1353
+ * A WebSocket a pane type opens on its own (the ws-client pane): through the canvas's network policy, like `request`. `init`: { protocols?, headers? };
1354
+ * `context`: { pane, signal, onmessage(data), onclose({ code, reason }) }. Resolves with { send(data), close(code, reason) } once open; rejects with the
1355
+ * policy's refusal (a `fetchFailure` of "refused", "secret" or "network"). Pane code in the sandbox has no way to call this: it has no WebSocket.
1356
+ */
1357
+ socket(url, init, context = {}) {
1358
+ return openSocket(String(url), init ?? {}, { pane: context.pane == null ? undefined : String(context.pane), signal: context.signal, onmessage: context.onmessage, onclose: context.onclose });
1359
+ },
1360
+ /** The tap on the canvas's own requests (the page's, src/ui/network-ui.js), or undefined: the http pane's tap mode reads it. */
1361
+ tap,
1362
+ /** The companion provider panes use: `companion pane` runs and `companion.use(id)` read it (src/model/canvas.js #companion). */
1363
+ companion,
1364
+ get ready() {
1365
+ return shared.ready;
1366
+ },
1367
+ get generation() {
1368
+ return shared.generation;
1369
+ },
1370
+
1371
+ /** How long a pane may run before the Worker is restarted (the "timeout" setting). */
1372
+ setTimeoutMs(ms) {
1373
+ timeoutMs = ms; // read by every call()
1374
+ },
1375
+
1376
+ /**
1377
+ * A pane's own timeout (its error policy's `timeoutMs`), instead of the
1378
+ * global one; undefined goes back to the global one. A timeout restarts
1379
+ * the shared sandbox, or only the pane's own Worker.
1380
+ */
1381
+ setPaneTimeout(id, ms) {
1382
+ if (Number.isFinite(ms) && ms > 0) paneTimeouts.set(String(id), ms);
1383
+ else paneTimeouts.delete(String(id));
1384
+ },
1385
+
1386
+ /**
1387
+ * Record what pane `pane`'s own fetch gets back (for-each: only item
1388
+ * `item`'s) until `stop()`: `outcomes` fills with `{ kind: "status",
1389
+ * status, retryAfterMs? }` per response and `{ kind }` per failure
1390
+ * ("network", "refused", "secret" or "error"; src/network/policy.js
1391
+ * fetchFailure). Error policies decide from it whether to retry.
1392
+ */
1393
+ watchFetches({ pane, item } = {}) {
1394
+ const watcher = { pane: String(pane), item, outcomes: [] };
1395
+ fetchWatchers.add(watcher);
1396
+ return { outcomes: watcher.outcomes, stop: () => fetchWatchers.delete(watcher) };
1397
+ },
1398
+
1399
+ /** How long a pane that uses on-device AI may run (the "AI timeout" setting); the longer of the two applies. */
1400
+ setAITimeoutMs(ms) {
1401
+ aiTimeoutMs = ms;
1402
+ },
1403
+
1404
+ /**
1405
+ * The variables panes see as `env` (src/env/env.js), and the requireEnv
1406
+ * error for a missing one (`{name}` is replaced). Kept across restarts.
1407
+ */
1408
+ setEnv(values, { missing } = {}) {
1409
+ env = { values: { ...values }, missing: missing ?? env.missing };
1410
+ for (const slot of slots()) slot.envDirty = true;
1411
+ return call("return true;").catch(() => {});
1412
+ },
1413
+
1414
+ /**
1415
+ * Stamp the events and channel sends pane code makes with this instant (ms since the epoch, a headless run's virtual
1416
+ * clock) instead of the real time; null goes back. The Workers hear it ahead of their next call.
1417
+ */
1418
+ setClock(ms) {
1419
+ const next = Number.isFinite(ms) ? ms : null;
1420
+ if (next === clockAt) return;
1421
+ clockAt = next;
1422
+ for (const slot of slots()) slot.clockDirty = true;
1423
+ },
1424
+
1425
+ /**
1426
+ * The codec panes of the open canvas, `{ name: codec setting | null }` (null: two panes share the name), and the formats of
1427
+ * every codec pane (the libraries to load, lazily, before a call that may use them). The Workers hear about the table with
1428
+ * their next call, only when it changed. Resolves once the libraries are in the Workers.
1429
+ */
1430
+ setCodecs(table, formats = []) {
1431
+ const next = table && typeof table === "object" ? table : {};
1432
+ if (JSON.stringify(next) !== JSON.stringify(codecTable)) {
1433
+ codecTable = next;
1434
+ for (const slot of slots()) slot.codecDirty = true;
1435
+ }
1436
+ if (!sources.codec?.libs) return Promise.resolve();
1437
+ return loadCodecLibs(new Set(formats)).then(() => {}, () => {}); // a library that doesn't load is said by the first call that needs it
1438
+ },
1439
+
1440
+ /** A codec call from the page: `op` "decode", "encode" or "analyze" (worker-runtime.js codecCall); answers { ok, … }. */
1441
+ async codec(op, request) {
1442
+ const format = request?.codec?.format; // a codec setting given as it is: its library is loaded first (a pane's name is in the table already)
1443
+ if (format && sources.codec?.libs) await loadCodecLibs([format]).catch(() => {});
1444
+ return call(`return await globalThis.__mallory.codecCall(${J(op)}, JSON.parse(${J(J(request))}));`);
1445
+ },
1446
+
1447
+ /**
1448
+ * The files the panes under id prefix `prefix` read as `assets` (a linked package pane's inner canvas):
1449
+ * `[{ name, type, data }]` (base64), or null when the pane goes. The Worker hears it ahead of its next call.
1450
+ */
1451
+ setAssets(prefix, entries) {
1452
+ const key = String(prefix);
1453
+ const had = JSON.stringify(assetTables.get(key));
1454
+ if (!Array.isArray(entries) || !entries.length) assetTables.delete(key);
1455
+ else assetTables.set(key, entries);
1456
+ if (had !== JSON.stringify(assetTables.get(key))) for (const slot of slots()) slot.assetsDirty = true;
1457
+ },
1458
+
1459
+ /**
1460
+ * The shared module the panes under id prefix `prefix` read as `pkg.module` (a linked package pane's inner canvas,
1461
+ * src/packages/module.js): `{ package, version, name, source, integrity }`, or null when the pane goes. Its integrity is
1462
+ * checked against its source here before any Worker gets it; the Worker hears of it ahead of its next call.
1463
+ */
1464
+ setModule(prefix, module) {
1465
+ const key = String(prefix);
1466
+ const had = JSON.stringify(moduleTables.get(key) ?? null);
1467
+ if (!module || typeof module.source !== "string" || typeof module.integrity !== "string") moduleTables.delete(key);
1468
+ else {
1469
+ const specifier = `mallory:pkg/${module.integrity.replace(/^sha256-/, "").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
1470
+ if (!moduleSources.has(specifier)) moduleSources.set(specifier, { source: module.source, ok: moduleMatches(module).catch(() => false) });
1471
+ const was = moduleTables.get(key);
1472
+ moduleTables.set(key, { specifier, package: String(module.package ?? ""), version: String(module.version ?? ""), name: String(module.name ?? "module"), ...(was?.specifier === specifier && was.problem ? { problem: was.problem } : {}) });
1473
+ }
1474
+ for (const specifier of moduleSources.keys()) if (![...moduleTables.values()].some((e) => e.specifier === specifier)) moduleSources.delete(specifier); // a module no pane reads any more: a Worker that has it keeps it, a new one won't get it
1475
+ if (had !== JSON.stringify(moduleTables.get(key) ?? null)) for (const slot of slots()) slot.modulesDirty = true;
1476
+ },
1477
+
1478
+ /**
1479
+ * What pane `id`'s profile view is read with (its `profile` setting, cleaned: src/model/profile-settings.js);
1480
+ * undefined goes back to the defaults. The Worker hears about it with the pane's next call, only when it changed.
1481
+ */
1482
+ setProfileSettings(id, options) {
1483
+ const key = String(id);
1484
+ const had = profiles.get(key);
1485
+ if (options === undefined || options === null || (typeof options === "object" && !Object.keys(options).length)) profiles.delete(key);
1486
+ else profiles.set(key, options);
1487
+ if (JSON.stringify(had) !== JSON.stringify(profiles.get(key))) for (const slot of slots()) slot.profileDirty = true;
1488
+ },
1489
+
1490
+ /**
1491
+ * Mark the panes whose ids start with `prefix` as an evaluation of `row`
1492
+ * (they see `isEvaluating` true and `evalRow`); `row` null ends it.
1493
+ */
1494
+ setEvaluation(prefix, row) {
1495
+ if (row == null) evaluations.delete(String(prefix));
1496
+ else evaluations.set(String(prefix), row);
1497
+ for (const slot of slots()) slot.evalDirty = true;
1498
+ return call("return true;").catch(() => {});
1499
+ },
1500
+
1501
+ /**
1502
+ * Run an eval pane's code with its inputs. `skipped` (source ids) are inputs
1503
+ * that were skipped, for a pane that takes skips. `fresh` (▶, run all): the
1504
+ * pane's `state` starts again. `own`: run it in its own Worker (see
1505
+ * execOwn). `strict`: the pane (its `strict` settings): run it in the QuickJS-WASM engine
1506
+ * (execStrict). `restoreState`: the pane's `state` as JSON from before a
1507
+ * restart, put back unless it has one. Resolves to a preview, or
1508
+ * `{ skipped: true, reason }` when the pane returned skip(…).
1509
+ */
1510
+ exec({ id, runId, sources, names, code, mode, view, label, setters = [], skipped = [], fresh = false, events = [], event, eventInput, keep, own = false, restoreState, strict: strictPane }) {
1511
+ for (const name of names) {
1512
+ const problem = checkInputName(name);
1513
+ if (problem) return Promise.reject(new Error(problem));
1514
+ }
1515
+ // Strict (./strict.js): in the QuickJS-WASM engine, JSON in and out.
1516
+ if (strictPane) return execStrict({ id, runId, sources, names, code, mode, view, skipped, pane: strictPane });
1517
+ // In its own Worker, or back in the shared sandbox (its own Worker goes, after its onCleanup).
1518
+ if (own) return execOwn({ id, runId, sources, names, code, mode, view, label, setters, skipped, fresh, events, event, eventInput, keep, restoreState });
1519
+ const leaving = ownSlots.has(String(id)) ? dropOwn(String(id)) : null;
1520
+ const run = () => call(finishing(id, runId, `await globalThis.__mallory.exec(${J(id)}, ${runId}, ${execArgs({ sources, names, code, mode, view, label, setters, skipped, fresh, events, event, eventInput, keep, restoreState })})`), { pane: id, timeout: timeFor(code) });
1521
+ return leaving ? leaving.then(run) : run();
1522
+ },
1523
+
1524
+ /**
1525
+ * An agent pane's part in the sandbox (src/agent/run.js): `op` "prepare"
1526
+ * (its templates and function inputs), "call" (a function tool), "http"
1527
+ * (a model request through the pane's fetch), "chrome" (the on-device
1528
+ * model through the AI bridge) or "cancel" (below). Model calls are slow:
1529
+ * the AI timeout applies when it is longer than the timeout.
1530
+ *
1531
+ * `onProgress(text)` (op "http" or "chrome", agent panes only): the model's
1532
+ * reply as it arrives, for the pane's trace, sent back by the Worker with the
1533
+ * `agentProgress` capability. For "http" it is the response body's text as
1534
+ * the pane's fetch reads it (a streamed body, through the network
1535
+ * policy, scrubbed of secrets as it arrives); for "chrome", the text
1536
+ * promptStreaming() yields. The call still resolves once, with the whole
1537
+ * reply. Op "cancel" stops the pane's model call in flight (its run was
1538
+ * superseded or stopped): the request's body is cancelled, or the
1539
+ * on-device prompt aborted.
1540
+ */
1541
+ agent({ id, runId, op, sources = [], names = [], payload = {}, onProgress }) {
1542
+ for (const name of names) {
1543
+ const problem = checkInputName(name);
1544
+ if (problem) return Promise.reject(new Error(problem));
1545
+ }
1546
+ const key = String(id);
1547
+ const tap = typeof onProgress === "function" && (op === "http" || op === "chrome") ? { runId: Number(runId), onProgress } : null;
1548
+ if (tap) agentTaps.set(key, tap);
1549
+ const done = call(`return await globalThis.__mallory.agent(${J(id)}, ${Number(runId)}, ${J(op)}, ${J(sources)}, ${J(names)}, JSON.parse(${J(J(payload))}), console);`, {
1550
+ pane: id,
1551
+ timeout: op === "prepare" || op === "cancel" ? timeoutMs : Math.max(timeoutMs, ai ? aiTimeoutMs : 0, 60000),
1552
+ });
1553
+ if (!tap) return done;
1554
+ return done.finally(() => {
1555
+ if (agentTaps.get(key) === tap) agentTaps.delete(key);
1556
+ });
1557
+ },
1558
+
1559
+ /**
1560
+ * Listen to a live run's emits: `onEmit(result)` for each emit(value)
1561
+ * (a preview, or `{ skipped, reason }`; it may return a promise, which holds
1562
+ * the pane's next emit until it settles, and false to refuse it), and
1563
+ * `onClose()` for emit.close(), and `onFrame()` for frame() (a promise
1564
+ * of `{ time, delta, eventWaiting }` at the run's next animation frame).
1565
+ * Register before exec(): code can emit before it returns. Returns a
1566
+ * function that stops listening.
1567
+ */
1568
+ liveWatch({ id, runId, onEmit, onClose, onFrame }) {
1569
+ const key = String(id);
1570
+ const watcher = { runId: Number(runId), onEmit, onClose, onFrame };
1571
+ liveWatchers.set(key, watcher);
1572
+ return () => {
1573
+ if (liveWatchers.get(key) === watcher) liveWatchers.delete(key);
1574
+ };
1575
+ },
1576
+
1577
+ /**
1578
+ * A live pane's next value: one step of its generator, so the pane's
1579
+ * timeout applies to each step (a step that never yields restarts the
1580
+ * Worker, like any run). `resume`: its inputs changed, and the `yield` it
1581
+ * waits at evaluates to them; `skipped`: the inputs that are skipped now.
1582
+ */
1583
+ liveNext({ id, runId, code, resume = false, skipped = [] }) {
1584
+ if (code !== undefined) liveCode.set(String(id), code);
1585
+ const step = `return await globalThis.__mallory.liveNext(${J(id)}, ${Number(runId)}, ${J(Boolean(resume))}, ${J(skipped)});`;
1586
+ const options = { pane: id, timeout: timeFor(liveCode.get(String(id)) ?? "") };
1587
+ const slot = ownSlots.get(String(id));
1588
+ if (!slot) return call(step, options);
1589
+ // In its own Worker: a step that resumes takes new copies of its inputs, and its value is stored in the shared sandbox.
1590
+ const answer = resume ? recopy(id, skipped, step, { ...options, slot }) : call(step, { ...options, slot });
1591
+ return answer.then((a) => settleOwn(id, runId, a, ownRuns.get(String(id))?.view));
1592
+ },
1593
+
1594
+ /** A resume pane that emits (no generator): its `inputs` view follows its inputs (in its own Worker, new copies of them). */
1595
+ liveInputs({ id, runId, skipped = [] }) {
1596
+ const code = `return globalThis.__mallory.liveInputs(${J(id)}, ${Number(runId)}, ${J(skipped)});`;
1597
+ const slot = ownSlots.get(String(id));
1598
+ return slot ? recopy(id, skipped, code, { pane: id, slot }) : call(code, { pane: id });
1599
+ },
1600
+
1601
+ /** The canvas transport: hold an emit pane's values in the Worker (the latest wins) or let them go again. Resolves to `{ pending }`. */
1602
+ livePause({ id, runId, paused }) {
1603
+ return call(`return globalThis.__mallory.livePause(${J(id)}, ${Number(runId)}, ${J(Boolean(paused))});`, { pane: id, slot: ownSlots.get(String(id)) ?? shared }).catch(() => ({ pending: false }));
1604
+ },
1605
+
1606
+ /** A step of a paused emit pane: the value it holds, now (a preview), `{ none }` or `{ busy }`. */
1607
+ liveTake({ id, runId }) {
1608
+ const slot = ownSlots.get(String(id));
1609
+ return call(`return globalThis.__mallory.liveTake(${J(id)}, ${Number(runId)});`, { pane: id, slot: slot ?? shared })
1610
+ .then((a) => (slot ? settleOwn(id, runId, a, ownRuns.get(String(id))?.view) : a))
1611
+ .catch(() => ({ none: true }));
1612
+ },
1613
+
1614
+ /**
1615
+ * A request made on the page for pane `pane`, exactly as that pane's own fetch would make it: through the network
1616
+ * policy (a host not allowed is refused and raises the prompt; secret() placeholders filled in for their hosts) and
1617
+ * credited to the pane. `stream`: a streaming body comes back as `stream`. MCP server panes use it (src/mcp/hub.js).
1618
+ */
1619
+ pageFetch(url, init = {}, { pane, signal, stream = false } = {}) {
1620
+ const id = pane == null ? undefined : String(pane);
1621
+ return watched(id, undefined, send(url, init, { pane: id, signal, ...(stream ? { stream: true } : {}) }));
1622
+ },
1623
+
1624
+ /** Answer MCP requests from pane code: `fn(paneId, server, op, request, { signal, waiting })`. Returns a function that stops. */
1625
+ serveMcp(fn) {
1626
+ mcpHandlers.add(fn);
1627
+ return () => mcpHandlers.delete(fn);
1628
+ },
1629
+ /** Answer `a2a.send(…)` in pane code: `fn(paneId, agent, op, request, { signal, waiting })` -> `{ value } | { error } | undefined`. */
1630
+ serveA2a(fn) {
1631
+ a2aHandlers.add(fn);
1632
+ return () => a2aHandlers.delete(fn);
1633
+ },
1634
+ /**
1635
+ * Decide the x402 challenges panes' fetches meet: `fn(paneId, { challenge, from }, { signal, waiting })` ->
1636
+ * decidePayment's answer (src/x402/pay.js), or undefined for a pane that isn't its. Returns a function that stops.
1637
+ */
1638
+ servePayments(fn) {
1639
+ payHandlers.add(fn);
1640
+ return () => payHandlers.delete(fn);
1641
+ },
1642
+
1643
+ /** Hear the events pane code sends: `fn(paneId, list)`. Returns a function that stops listening. */
1644
+ listenEvents(fn) {
1645
+ eventListeners.add(fn);
1646
+ return () => eventListeners.delete(fn);
1647
+ },
1648
+
1649
+ /** Store an event made on the page under `key`, in event node `node`'s ring of `keep`. Resolves to its preview. */
1650
+ storeEvent({ node, key, name, payload, at, source, keep, batch }) {
1651
+ // A payload that holds a Blob (a media value: a recorded take) goes over by structured clone, as a pane's value does; JSON would leave `{}`.
1652
+ if (holdsBlob(payload)) return viaHandoff(payload, (v) => `return globalThis.__mallory.storeEvent(${J(node)}, ${J(key)}, ${J(name)}, ${v}, ${J(at)}, ${J(source)}, ${Number(keep) || 1002}${batch === undefined ? "" : `, ${J(batch)}`});`, { pane: node });
1653
+ return call(`return globalThis.__mallory.storeEvent(${J(node)}, ${J(key)}, ${J(name)}, JSON.parse(${J(J(payload ?? null))}), ${J(at)}, ${J(source)}, ${Number(keep) || 1002}${batch === undefined ? "" : `, ${J(batch)}`});`, { pane: node });
1654
+ },
1655
+
1656
+ /** Drop event `key` from event node `node`'s ring in the Worker. Resolves to whether it was held. */
1657
+ discardEvent({ node, key }) {
1658
+ return call(`return globalThis.__mallory.discardEvent(${J(node)}, ${J(key)});`, { pane: node }).catch(() => false);
1659
+ },
1660
+
1661
+ /** Store a repeater's item event under `key`: `fields` plus the payload (Worker key `from`, or `payload`) and the instance's `value` ({ s, l? }). Resolves to its preview. */
1662
+ storeItemEvent({ node, key, name, fields, from, payload, value, at, source, keep, batch }) {
1663
+ return call(`return globalThis.__mallory.storeItemEvent(${J(node)}, ${J(key)}, ${J(name)}, JSON.parse(${J(J(fields ?? {}))}), ${J(from ?? null)}, JSON.parse(${J(J(payload ?? null))}), JSON.parse(${J(J(value ?? null))}), ${J(at)}, ${J(source)}, ${Number(keep) || 1002}${batch === undefined ? "" : `, ${J(batch)}`});`, { pane: node });
1664
+ },
1665
+
1666
+ /** Store a channel's event for a receiver's event output `node` under `key`: the payload is Worker key `from`'s value, or `payload`. Resolves to its preview. */
1667
+ storeChannelEvent({ node, key, name, channel, scope, from, payload, at, source, keep }) {
1668
+ return call(`return globalThis.__mallory.storeChannelEvent(${J(node)}, ${J(key)}, ${J(name)}, ${J(channel)}, ${J(scope)}, ${J(from ?? null)}, JSON.parse(${J(J(payload ?? null))}), ${J(at)}, ${J(source)}, ${Number(keep) || 1002});`, { pane: node });
1669
+ },
1670
+
1671
+ /**
1672
+ * An acknowledged channel send that waited for the runaway budget was sent or dropped: tell its sender, in the Worker the pane runs in
1673
+ * (the shared one, or the pane's own), the answer for ack key `key` (as the Worker made it).
1674
+ */
1675
+ settleSendAck({ id, key, answer }) {
1676
+ return call(`return globalThis.__mallory.settleSendAck(${J(String(id))}, ${J(String(key))}, JSON.parse(${J(J(answer))}));`, { pane: id, slot: ownSlots.get(String(id)) ?? shared }).catch(() => false);
1677
+ },
1678
+
1679
+ /** Push Worker keys through one stage of a wire's operators (src/model/wire-pipeline.js). Resolves to the keys that came out. */
1680
+ wirePush({ wire, stage, ops, at, keys, kind, batch }) {
1681
+ return call(`return globalThis.__mallory.wirePush(${J(wire)}, ${Number(stage)}, JSON.parse(${J(J(ops))}), ${Number(at)}, ${J(keys)}, ${J(kind)}${batch === undefined ? "" : `, ${J(batch)}`});`, { pane: wire });
1682
+ },
1683
+
1684
+ /** A finite batch ended on a wire: what one stage holds for it comes out (mode "end"), comes out marked partial ("partial", with `reason`), or goes ("discard"). Resolves to the keys. */
1685
+ wireComplete({ wire, stage, kind, batch, mode, reason }) {
1686
+ return call(`return globalThis.__mallory.wireComplete(${J(wire)}, ${Number(stage)}, ${J(kind)}, ${J(batch)}, ${J(mode)}, ${J(reason ?? null)});`, { pane: wire });
1687
+ },
1688
+
1689
+ /**
1690
+ * Push Worker keys into a window stage of a wire (src/model/wire-pipeline.js) at time `now`, the canvas clock's.
1691
+ * Resolves to `{ keys, bounds, held, since, next }`: the windows that closed, where each opened and closed, what the stage holds, and when to look again.
1692
+ */
1693
+ wireWindow({ wire, stage, op, at, keys, kind, batch, now }) {
1694
+ return call(`return globalThis.__mallory.wireWindow(${J(wire)}, ${Number(stage)}, JSON.parse(${J(J(op))}), ${Number(at)}, ${J(keys)}, ${J(kind)}, ${J(batch ?? null)}, ${Number(now)});`, { pane: wire });
1695
+ },
1696
+
1697
+ /** Time has passed on a window stage: the windows whose deadline came close, as wireWindow returns them. */
1698
+ wireWindowTick({ wire, stage, op, at, kind, batch, now }) {
1699
+ return call(`return globalThis.__mallory.wireWindowTick(${J(wire)}, ${Number(stage)}, JSON.parse(${J(J(op))}), ${Number(at)}, ${J(kind)}, ${J(batch ?? null)}, ${Number(now)});`, { pane: wire });
1700
+ },
1701
+
1702
+ /** A finite batch ended on a window stage: the open window goes (mode "end"), or goes marked partial ("partial", with `reason`). Resolves to `{ keys, bounds }`. */
1703
+ wireWindowEnd({ wire, stage, kind, batch, mode, reason, now }) {
1704
+ return call(`return globalThis.__mallory.wireWindowEnd(${J(wire)}, ${Number(stage)}, ${J(kind)}, ${J(batch)}, ${J(mode)}, ${J(reason ?? null)}, ${Number(now)});`, { pane: wire });
1705
+ },
1706
+
1707
+ /** How big each event (Worker keys) that came out of a wire's operators is, approximately. Resolves to the sizes, in order. */
1708
+ wireSizes({ wire, keys }) {
1709
+ return call(`return globalThis.__mallory.wireSizes(${J(keys)});`, { pane: wire });
1710
+ },
1711
+
1712
+ /** What came out of a wire's operators becomes the wire's value (or next event). Resolves to its preview. */
1713
+ wireTake({ wire, key, kind, keep, view = "auto", runId }) {
1714
+ const take = `globalThis.__mallory.wireTake(${J(wire)}, ${J(key)}, ${J(kind)}, ${Number(keep) || 1002}, ${J(view)}${runId !== undefined ? `, ${Number(runId)}` : ""})`;
1715
+ // `runId` (the wire node's run): its reply can carry its value to put back after a restart (withRun).
1716
+ return call(runId !== undefined ? finishing(wire, runId, take) : `return ${take};`, { pane: wire });
1717
+ },
1718
+
1719
+ /** Values a debounce or throttle let go. */
1720
+ wireDrop({ keys }) {
1721
+ return call(`return globalThis.__mallory.wireDrop(${J(keys)});`).catch(() => false);
1722
+ },
1723
+
1724
+ /** A wire's operators start again. */
1725
+ wireReset({ wire }) {
1726
+ return call(`return globalThis.__mallory.wireReset(${J(wire)});`).catch(() => false);
1727
+ },
1728
+
1729
+ /** End a live run: its generator's `finally`, its sleeps, its cleanups; later emits are refused. */
1730
+ liveEnd({ id, runId }) {
1731
+ const watcher = liveWatchers.get(String(id));
1732
+ if (watcher && watcher.runId === Number(runId)) liveWatchers.delete(String(id));
1733
+ return call(`return globalThis.__mallory.liveEnd(${J(id)}, ${Number(runId)});`, { pane: id, slot: ownSlots.get(String(id)) ?? shared }).catch(() => false);
1734
+ },
1735
+
1736
+ /**
1737
+ * For-each: each input's array length (null when it isn't an array). `fresh`: the pane's `state` starts again;
1738
+ * `restoreState` (with `code` and `mode`): its `state` from before a restart. `own`: the items run
1739
+ * in the pane's own Worker, which takes copies of its inputs (and of its setters' state panes) here, once a run.
1740
+ */
1741
+ async eachLengths({ id, runId, sources, names = [], skipped = [], fresh = false, own = false, setters = [], restoreState, code, mode }) {
1742
+ const key = String(id);
1743
+ // In its own Worker, a run of it still going there ends first, and then it gets the `state` its last run kept.
1744
+ if (own && supersedeOwn(key, runId)) restoreState = stateAfterSupersede(key, { restoreState, fresh, code, mode });
1745
+ const restore = typeof restoreState === "string" && code !== undefined ? { body: paneBody(code, mode), text: restoreState } : undefined;
1746
+ const lengths = (pre = "") => `${pre}return globalThis.__mallory.eachLengths(${J(id)}, ${runId}, ${J(sources)}, ${J(skipped)}, ${J(Boolean(fresh))}${restore ? `, ${J(restore)}` : ""});`;
1747
+ if (!own) {
1748
+ if (ownSlots.has(key)) await dropOwn(key); // back in the shared sandbox: its own Worker goes, after its onCleanup
1749
+ return call(lengths(), { pane: id });
1750
+ }
1751
+ const reads = ownReads({ sources, names, skipped, setters });
1752
+ const got = await readsInto(id, channel ? ownSlot(key) : null, reads);
1753
+ const slot = ownSlot(key);
1754
+ ownRuns.set(key, { ...reads, sources, names, setters, view: "auto", code, mode });
1755
+ return intoOwn(id, got, (v) => lengths(`globalThis.__mallory.ownInputs(${v});\n`), { pane: id, slot, run: runId });
1756
+ },
1757
+
1758
+ /** For-each: run one item of an eval pane; `bind` is [[inputIndex, elementIndex]] (see src/model/foreach.js). Each item is its own call, so the timeout is per item. */
1759
+ execItem({ id, runId, index, count, sources, names, bind, code, mode, label, setters = [], skipped = [], own = false }) {
1760
+ for (const name of names) {
1761
+ const problem = checkInputName(name);
1762
+ if (problem) return Promise.reject(new Error(problem));
1763
+ }
1764
+ return call(
1765
+ `return await globalThis.__mallory.execItem(${J(id)}, ${runId}, ${Number(index)}, ${Number(count)}, ${J(sources)}, ${J(names)}, ${J(bind)}, ${J(paneBody(code, mode))}, ${J(label)}, console, ${J(setters)}, ${J(skipped)});`,
1766
+ { pane: id, timeout: timeFor(code), ...(own ? { slot: ownSlot(String(id)), run: runId } : {}) }, // its own Worker: a timeout there restarts only that one
1767
+ );
1768
+ },
1769
+
1770
+ /** A for-each pane's inputs as its next run would see them: `{ lengths }` or `{ waiting }`. Starts no run. */
1771
+ eachPeek({ id, sources, skipped = [] }) {
1772
+ return call(`return globalThis.__mallory.eachPeek(${J(sources)}, ${J(skipped)});`, { pane: id });
1773
+ },
1774
+
1775
+ /** The key matching a run would make, for the preview: `{ matched }` or `{ error }`. Starts no run. */
1776
+ eachPeekMatch({ id, sources, names, over, spec, label, skipped = [] }) {
1777
+ return call(`return globalThis.__mallory.eachPeekMatch(${J({ sources, names, over, spec, label, skipped })});`, { pane: id });
1778
+ },
1779
+
1780
+ /** For-each matching by key: the rows the iterated inputs' elements line up in (keys.js matchByKey), read where the values are. */
1781
+ eachMatch({ id, runId, over, sources, spec, label, skipped = [], names = [], own = false }) {
1782
+ return call(`return globalThis.__mallory.eachMatch(${J(id)}, ${runId}, ${J({ sources, names, over, spec, label, skipped })});`, { pane: id, ...(own ? { slot: ownSlot(String(id)), run: runId } : {}) });
1783
+ },
1784
+
1785
+ /** Keyed for-each: which items must run, and the ones reused from the pane's kept results (worker-runtime.js eachPlan). */
1786
+ eachPlan({ id, runId, sources, names, over, binds, key, match, matchKeys, code, mode, label, skipped = [], own = false }) {
1787
+ const plan = { sources, names, over, binds, key, ...(match ? { match } : {}), ...(matchKeys ? { matchKeys } : {}), body: paneBody(code, mode), label, skipped };
1788
+ return call(`return globalThis.__mallory.eachPlan(${J(id)}, ${runId}, ${J(plan)});`, { pane: id, ...(own ? { slot: ownSlot(String(id)), run: runId } : {}) });
1789
+ },
1790
+
1791
+ /** A failed keyed for-each run's checkpoint (worker-runtime.js eachExport): the completed items' values and the failed items' payloads, as JSON. */
1792
+ eachExport({ id, runId, failed = [], sources = [], binds = [], skipped = [], maxBytes, own = false }) {
1793
+ const args = { failed, sources, binds, skipped, ...(maxBytes ? { maxBytes } : {}) };
1794
+ return call(`return globalThis.__mallory.eachExport(${J(id)}, ${runId}, ${J(args)});`, { pane: id, ...(own ? { slot: ownSlot(String(id)), run: runId } : {}) });
1795
+ },
1796
+
1797
+ /** A failed-item retry (worker-runtime.js eachImport): the checkpoint and edited payloads the pane's next eachPlan resumes from. */
1798
+ eachImport({ id, seed, edits = {}, own = false }) {
1799
+ return call(`return globalThis.__mallory.eachImport(${J(id)}, ${J({ seed, edits })});`, { pane: id, ...(own ? { slot: ownSlot(String(id)) } : {}) });
1800
+ },
1801
+
1802
+ /** For-each: the items' results become the pane's value (its preview is returned). `own`: made in its own Worker, copied into the shared sandbox. */
1803
+ async eachFinish({ id, runId, count, view, keyed = false, own = false, nest }) {
1804
+ const grouped = Array.isArray(nest) && nest.length > 1 ? nest.map(Number) : undefined; // sizes of the inputs a cross product is grouped by
1805
+ if (!own) return call(finishing(id, runId, `globalThis.__mallory.eachFinish(${J(id)}, ${runId}, ${Number(count)}, ${J(view)}, ${J(Boolean(keyed))}, { nest: ${J(grouped)} })`), { pane: id });
1806
+ const want = runWants.get(String(id));
1807
+ const stateBytes = want?.runId === Number(runId) ? (want.json?.restoreBytes ?? 0) : 0;
1808
+ const out = await call(`return await globalThis.__mallory.eachFinishOwn(${J(id)}, ${runId}, ${Number(count)}, ${J(Boolean(keyed))}, ${stateBytes}, ${J(grouped)});`, { pane: id, slot: ownSlot(String(id)), run: runId });
1809
+ return ownAnswer(id, runId, view, out);
1810
+ },
1811
+
1812
+ /** A repeater's plan: which input it repeats over, each item's key, fingerprint and template (worker-runtime.js repeatPlan). */
1813
+ repeatPlan({ id, runId, sources, names, input = "", key = "", templateBy = "", max = 0, label }) {
1814
+ const plan = { sources, names, input, key, templateBy, max: Number(max) || 0, label };
1815
+ return call(`return globalThis.__mallory.repeatPlan(${J(id)}, ${Number(runId)}, JSON.parse(${J(J(plan))}));`, { pane: id });
1816
+ },
1817
+
1818
+ /** A repeater instance's item port: item `index` of list `source` (found by `key` when it moved), stored under `id`. */
1819
+ pick({ id, runId, source, index, key = null, spec = "", label, view = "auto" }) {
1820
+ return call(finishing(id, runId, `globalThis.__mallory.pick(${J(id)}, ${Number(runId)}, ${J(source)}, ${Number(index)}, ${J(key)}, ${J(spec)}, ${J(label ?? "")}, ${J(view)})`), { pane: id });
1821
+ },
1822
+
1823
+ /** A repeater's value: its instances' values in item order (`keyed`: an object by key). */
1824
+ gather({ id, runId, items, keyed = false, view = "auto" }) {
1825
+ return call(finishing(id, runId, `globalThis.__mallory.gather(${J(id)}, ${Number(runId)}, JSON.parse(${J(J(items))}), ${J(Boolean(keyed))}, ${J(view)})`), { pane: id });
1826
+ },
1827
+
1828
+ /** Render an html pane's template against its inputs: `{ html }` (the string; `folder` too when an input is a files value), nothing stored. */
1829
+ template({ id, runId, sources, names, text, label }) {
1830
+ for (const name of names) {
1831
+ const problem = checkInputName(name);
1832
+ if (problem) return Promise.reject(new Error(problem));
1833
+ }
1834
+ return call(
1835
+ `return await globalThis.__mallory.template(${J(id)}, ${runId}, ${J(sources)}, ${J(names)}, ${J(templateBody(text))}, ${J(label)}, console);`,
1836
+ { pane: id, timeout: timeFor(text) },
1837
+ ).then((out) => (out instanceof Map ? Object.fromEntries(out) : out)); // { html, folder } when an input is a files value
1838
+ },
1839
+
1840
+ /**
1841
+ * Run a state pane (its initial value, the first time or on reset). A
1842
+ * persisted one passes `restore` (its stored JSON text) and `persist`
1843
+ * (return the value as JSON text to store; "blobs": media values' Blobs
1844
+ * beside it, and `restoreMedia`, `{ ref: Blob }`, the ones to put back).
1845
+ */
1846
+ async state({ id, runId, code, reset, label, restore, persist = false, restoreMedia }) {
1847
+ const restored = typeof restore === "string" ? J(restore) : "undefined";
1848
+ const token = restoreMedia && Object.keys(restoreMedia).length ? String(++handoffSeq) : null;
1849
+ if (token) handoffs.set(token, restoreMedia); // Blobs go over by structured clone
1850
+ try {
1851
+ const media = token ? `await host.call("handoff", ${J(token)})` : "undefined";
1852
+ return await call(finishing(id, runId, `await globalThis.__mallory.state(${J(id)}, ${runId}, ${J(paneBody(code, "expression"))}, ${J(Boolean(reset))}, ${J(label)}, ${restored}, ${J(persist || false)}, console, ${media})`), { pane: id });
1853
+ } finally {
1854
+ if (token) handoffs.delete(token);
1855
+ }
1856
+ },
1857
+
1858
+ /** What the store would keep for a state pane's value now (`{ ok, text, media?, blobs? }` or `{ ok: false, reason }`), without a run. */
1859
+ persistState(id, persist) {
1860
+ return call(`return await globalThis.__mallory.persistState(${J(id)}, ${J(persist || false)});`, { pane: id });
1861
+ },
1862
+
1863
+ /** Set a state pane's value from the page (a DOM pane's setter). */
1864
+ setState(id, value) {
1865
+ return call(`return globalThis.__mallory.setState(${J(id)}, JSON.parse(${J(J(value ?? null))}));`, { pane: id });
1866
+ },
1867
+
1868
+ /**
1869
+ * A keyed change to a state pane's list: `request` is
1870
+ * `{ op: "update", key, patch | item }`, `{ op: "insert", item, at? }`,
1871
+ * `{ op: "remove", key }` or `{ op: "move", key, to }` (JSON; src/runtime/keys.js
1872
+ * applyKeyed), `spec` the state pane's key. Resolves `{ change }` (`{}` when
1873
+ * nothing changed); rejects with a readable error (an unknown key, …).
1874
+ */
1875
+ changeState(id, request, spec, label) {
1876
+ return call(`return globalThis.__mallory.changeState(${J(id)}, JSON.parse(${J(J(request))}), ${spec === undefined ? "undefined" : J(spec)}, ${label ? J(label) : "undefined"});`, { pane: id });
1877
+ },
1878
+
1879
+ /** Keyed hints for keyed for-each readers on or off (on by default; for measuring). */
1880
+ setKeyedHints(on) {
1881
+ return call(`return globalThis.__mallory.setKeyedHints(${Boolean(on)});`);
1882
+ },
1883
+
1884
+ /** Every row of one problem of pane `id`'s profile (the profile view's "Find every row"): the Worker reads its current value, in slices. */
1885
+ findProfileRows(id, column, kind, limit) {
1886
+ return call(`return await globalThis.__mallory.findProfileRows(${J(id)}, ${J(column)}, ${J(kind)}, ${Number(limit)});`, { pane: id });
1887
+ },
1888
+
1889
+ /** A row of an interactive table (`{ data, onRowClick }`) was clicked. */
1890
+ rowClick(id, index) {
1891
+ return call(`return await globalThis.__mallory.rowClick(${J(id)}, ${Number(index)});`, { pane: id });
1892
+ },
1893
+
1894
+ /**
1895
+ * A select pane's run: its rows are Worker key `source`'s value, `picked` the selected keys as keyTexts
1896
+ * (src/runtime/keys.js selectRows), `options` { dataset, revision, mode, missing, limit }.
1897
+ */
1898
+ select({ id, runId, source, spec, picked, options }) {
1899
+ return call(finishing(id, runId, `globalThis.__mallory.selectRun(${J(id)}, ${runId}, ${J(source)}, ${J(spec ?? "")}, ${J(picked ?? [])}, ${J(options ?? {})})`), { pane: id });
1900
+ },
1901
+
1902
+ /**
1903
+ * A plot pane's run (src/model/runners/plot.js): the Worker samples `request`'s curves (src/plot/source.js) with the numbers the
1904
+ * wired inputs `names` (the values at `sources`) hold, stores { samples, features, viewport } as the pane's value and replies with
1905
+ * its preview plus `plot`, what the pane draws (typed arrays). A newer run of the pane makes this one `{ superseded: true }`.
1906
+ */
1907
+ plot({ id, runId, sources, names, request, skipped = [] }) {
1908
+ return call(finishing(id, runId, `await globalThis.__mallory.plotRun(${J(id)}, ${runId}, ${J(sources)}, ${J(names)}, ${J(request)}, ${J(skipped)})`), { pane: id });
1909
+ },
1910
+
1911
+ /**
1912
+ * A calc pane's run (src/model/runners/calc.js): the Worker works out `request`'s lines (src/calc/source.js) with the numbers the
1913
+ * wired inputs `names` (the values at `sources`) hold, stores { name: value } for every name a line assigned as the pane's value and
1914
+ * replies with its preview plus `calc`, one result per line. A newer run of the pane makes this one `{ superseded: true }`.
1915
+ */
1916
+ calc({ id, runId, sources, names, request, skipped = [] }) {
1917
+ return call(finishing(id, runId, `await globalThis.__mallory.calcRun(${J(id)}, ${runId}, ${J(sources)}, ${J(names)}, ${J(request)}, ${J(skipped)})`), { pane: id });
1918
+ },
1919
+
1920
+ /**
1921
+ * A geometry pane's run (src/model/runners/geometry.js): the Worker works out the construction (src/geometry/model.js) with the
1922
+ * numbers the wired inputs `names` (the values at `sources`) hold as its named parameters, stores { scene, <measurements> } as the
1923
+ * pane's value and replies with its preview plus `geometry`, the parameters in use and the objects that have an error.
1924
+ */
1925
+ geometry({ id, runId, sources, names, request, skipped = [] }) {
1926
+ return call(finishing(id, runId, `await globalThis.__mallory.geometryRun(${J(id)}, ${runId}, ${J(sources)}, ${J(names)}, ${J(request)}, ${J(skipped)})`), { pane: id });
1927
+ },
1928
+
1929
+ /**
1930
+ * A graph pane's run (src/model/runners/graph.js): the Worker works out the edge list (src/graph/model.js) with the wired inputs `edges`,
1931
+ * `directed`, `start` and `end` (the values at `sources`) beating the settings, stores the graph's value as the pane's value and replies
1932
+ * with its preview plus `graph`, the settings the wires took.
1933
+ */
1934
+ graph({ id, runId, sources, names, request, skipped = [] }) {
1935
+ return call(finishing(id, runId, `await globalThis.__mallory.graphRun(${J(id)}, ${runId}, ${J(sources)}, ${J(names)}, ${J(request)}, ${J(skipped)})`), { pane: id });
1936
+ },
1937
+
1938
+ /**
1939
+ * One line of a shell pane (src/ui/shell-pane.js, a machine's shell tool): the Worker runs `request.line` in clsh (src/clsh/clsh.js) over the canvas's own
1940
+ * folder (through the page broker and the person's grant, as `vfs.own()`) and with the pane's network (the canvas's rules), and replies with
1941
+ * { chunks, code, state, effects, truncated, ms }. The wired inputs `names` (the values at `sources`) are variables. It stores no pane value and is not a pane run.
1942
+ */
1943
+ shell({ id, request, sources = [], names = [] }) {
1944
+ return call(`return await globalThis.__mallory.shellExec(${J(id)}, ${J(request)}, ${J(sources)}, ${J(names)});`, { pane: id, solo: true });
1945
+ },
1946
+
1947
+ /**
1948
+ * Store a value computed on the page (text, input widgets, a DOM pane's
1949
+ * return value, a media pane's media value). JSON, unless it holds Blobs:
1950
+ * then it goes over by structured clone, so the bytes are never copied
1951
+ * through text.
1952
+ */
1953
+ set({ id, runId, value, view }) {
1954
+ if (holdsBlob(value)) return handOver({ id, runId, value, view });
1955
+ return call(finishing(id, runId, `globalThis.__mallory.set(${J(id)}, ${runId}, JSON.parse(${J(J(value ?? null))}), ${J(view)})`), { pane: id });
1956
+ },
1957
+
1958
+ /**
1959
+ * Put back a value the sandbox lost in a restart: `text` is the JSON
1960
+ * the run's reply carried (`captured.restore`, see withRun), and it is
1961
+ * stored as run `runId` of pane `id`, as set() stores one. Resolves to its
1962
+ * preview; the run's reply carries the cut-off's answer and `captured` as
1963
+ * for any run. `state` (with `code` and `mode`): an eval pane's
1964
+ * `state` as JSON, put back with it.
1965
+ */
1966
+ restoreValue({ id, runId, text, view, state, code, mode }) {
1967
+ // An eval pane's `state`, put back with its value (`code`: the code it was kept for).
1968
+ const putState = typeof state === "string" && code !== undefined ? `globalThis.__mallory.restoreState(${J(id)}, ${J(paneBody(code, mode))}, ${J(state)});\n` : "";
1969
+ return call(putState + finishing(id, runId, `globalThis.__mallory.set(${J(id)}, ${runId}, JSON.parse(${J(String(text))}), ${J(view)})`), { pane: id });
1970
+ },
1971
+
1972
+ /** A media pane's "from URL": the sandbox fetches it as the pane (through the network policy). */
1973
+ mediaFromUrl({ id, runId, url, meta = {}, view = "auto" }) {
1974
+ return call(finishing(id, runId, `await globalThis.__mallory.mediaFromUrl(${J(id)}, ${runId}, ${J(url)}, ${J(meta)}, ${J(view)})`), { pane: id, timeout: Math.max(timeoutMs, 60000) });
1975
+ },
1976
+
1977
+ /** Store a value made on the page that JSON can't carry (a media value's Blob), by structured clone. */
1978
+ setValue: handOver,
1979
+
1980
+ importModule({ id, runId, url, useDefault, view }) {
1981
+ return call(finishing(id, runId, `await globalThis.__mallory.importModule(${J(id)}, ${runId}, ${J(url)}, ${J(Boolean(useDefault))}, ${J(view)})`), {
1982
+ pane: id,
1983
+ timeout: Math.max(timeoutMs, 60000),
1984
+ });
1985
+ },
1986
+
1987
+ expand(handle) {
1988
+ return call(`return globalThis.__mallory.expand(${J(handle)});`);
1989
+ },
1990
+
1991
+ /** Structured-clone copies of values, for DOM panes. */
1992
+ async clone(sources) {
1993
+ return (await call(`return globalThis.__mallory.clone(${J(sources)});`)).get("values");
1994
+ },
1995
+
1996
+ /**
1997
+ * What run `runId` of pane `id` wants back in the same reply as its value
1998
+ * , so neither costs a round trip of its own: `base()` (the run
1999
+ * whose value its readers saw; the equality cut-off's compare, read when
2000
+ * the value is stored) and `json` (`{ maxBytes, maxPreviewEntries }`: the
2001
+ * run log's full value; with `restoreBytes`, the value to put back
2002
+ * after a restart when it comes back exactly from JSON, `captured.restore`;
2003
+ * `only: "restore"`: the run log wants none). The calls that store a pane's
2004
+ * value (exec, set, setValue, state, eachFinish, gather, pick, importModule,
2005
+ * mediaFromUrl, restoreValue) then return `cutoff` and `captured` on their
2006
+ * result (worker-runtime.js finish). Stays on the page; a later run of the
2007
+ * pane replaces it.
2008
+ */
2009
+ withRun({ id, runId, base, json }) {
2010
+ if (typeof base !== "function" && !json) runWants.delete(String(id));
2011
+ else runWants.set(String(id), { runId: Number(runId), ...(typeof base === "function" ? { base } : {}), ...(json ? { json: cleanJson(json) } : {}) });
2012
+ },
2013
+
2014
+ /**
2015
+ * The equality cut-off (src/model/rate.js): does the value run `runId` of
2016
+ * pane `id` stored equal the one run `base` stored? `{ unchanged }`, or
2017
+ * `{ superseded: true }` when a newer run has started.
2018
+ */
2019
+ compare({ id, runId, base }) {
2020
+ return call(`return globalThis.__mallory.compare(${J(id)}, ${Number(runId)}, ${base == null ? "undefined" : Number(base)});`, { pane: id });
2021
+ },
2022
+
2023
+ /** A pane was skipped: drop its value (unless a run newer than `runId` started). */
2024
+ clear(id, runId) {
2025
+ return call(`globalThis.__mallory.clear(${J(id)}, ${Number(runId)});`).catch(() => {});
2026
+ },
2027
+
2028
+ forget(id) {
2029
+ companion?.release?.(String(id)); // its companion sockets
2030
+ crossTab?.release?.(String(id)); // its cross-tab link
2031
+ midi?.release?.(String(id)); // its raw MIDI channel
2032
+ vfs?.release?.(String(id)); // its file watches
2033
+ dropOwn(String(id)); // its own Worker, after its onCleanup
2034
+ ownRuns.delete(String(id));
2035
+ ownStates.delete(String(id));
2036
+ paneTimeouts.delete(String(id));
2037
+ runWants.delete(String(id));
2038
+ liveWatchers.delete(String(id));
2039
+ liveCode.delete(String(id));
2040
+ return call(`globalThis.__mallory.forget(${J(id)});`).catch(() => {});
2041
+ },
2042
+
2043
+ /**
2044
+ * Batch the calls for panes whose sandbox ids start with `prefix` (a
2045
+ * repeater's instances, `<pane>/@`): the ones made in one task go to the
2046
+ * Worker as one evaluation. Returns a function that stops it.
2047
+ */
2048
+ batchUnder(prefix) {
2049
+ const key = String(prefix);
2050
+ batchPrefixes.set(key, (batchPrefixes.get(key) ?? 0) + 1);
2051
+ let on = true;
2052
+ return () => {
2053
+ if (!on) return;
2054
+ on = false;
2055
+ const n = batchPrefixes.get(key) - 1;
2056
+ if (n > 0) batchPrefixes.set(key, n);
2057
+ else batchPrefixes.delete(key);
2058
+ };
2059
+ },
2060
+
2061
+ /** The direct channels so far: `{ links, in, out }` (channels made; copies sent on one into panes' own Workers, and out of them). */
2062
+ channelStats() {
2063
+ return { ...channelStats };
2064
+ },
2065
+
2066
+ /** Calls into the Worker so far: `{ evaluations, batches, batched }` (evaluations made, batches among them, calls they carried). */
2067
+ callStats() {
2068
+ return { ...callStats };
2069
+ },
2070
+
2071
+ /** The Worker's compile cache: `{ size, max, hits, misses }`. */
2072
+ compileStats() {
2073
+ return call("return globalThis.__mallory.compileStats();");
2074
+ },
2075
+
2076
+ /**
2077
+ * What the Worker holds: `{ values, latest, setters, eachRuns, handles, aiSessions, paneStates, cleanups }`
2078
+ * counts (leak checks), plus, with on-device AI, the bridge's live
2079
+ * `aiHandles` and open `aiStreams`.
2080
+ */
2081
+ async stats() {
2082
+ const out = await call("return globalThis.__mallory.stats();");
2083
+ const bridge = ai ? shared.sandbox?.stats?.().bridges?.ai : undefined;
2084
+ if (bridge) Object.assign(out, { aiHandles: bridge.handles, aiStreams: bridge.streams });
2085
+ out.ownWorkers = ownSlots.size; // panes' own Workers
2086
+ out.strictEngine = Boolean(strictRunner?.started); // the QuickJS-WASM engine strict panes run in
2087
+ return out;
2088
+ },
2089
+
2090
+ /** What a pane's value can be copied or downloaded as (src/export/value.js describeValue). */
2091
+ exportInfo(id, { scalars = false } = {}) {
2092
+ return call(`return globalThis.__mallory.exportInfo(${J(id)}, ${J({ scalars: Boolean(scalars) })});`, { timeout: Math.max(timeoutMs, 60000) });
2093
+ },
2094
+
2095
+ /** A pane's value as text in one format, converted in the Worker: `{ text }` (or `{ preview }` for "preview"). */
2096
+ /** `runId`: only that run's value (else `{ stale: true }`); `maxBytes`: `{ tooBig: length }` for longer text (the run log). */
2097
+ async exportValue(id, format, { scalars = false, runId, maxBytes } = {}) {
2098
+ if (format === "parquet" && !codecLibs.has("dataframe") && sources.frame && sources.codec?.libs) await loadCodecLibs(["dataframe"]);
2099
+ const options = { scalars: Boolean(scalars), ...(runId !== undefined ? { runId: Number(runId) } : {}), ...(maxBytes ? { maxBytes: Number(maxBytes) } : {}) };
2100
+ // `await`: a Parquet write is a promise, and one that rejects (cancelled, over a limit) must reach the try that returns what it
2101
+ // threw; an evaluation that rejects would read as the Worker being ended.
2102
+ return call(`return await globalThis.__mallory.exportValue(${J(id)}, ${J(format)}, ${J(options)});`, { timeout: Math.max(timeoutMs, 60000) });
2103
+ },
2104
+
2105
+ /** Stop pane `id`'s Parquet export if one is being written (its exportValue call then fails with an AbortError): true if there was one. */
2106
+ cancelExport(id) {
2107
+ return call(`return globalThis.__mallory.cancelExport(${J(id)});`);
2108
+ },
2109
+
2110
+ /** How far pane `id`'s Parquet export has got (`{ rows, total }`, or null): the download toast shows it. */
2111
+ exportProgress(id) {
2112
+ return call(`return globalThis.__mallory.exportProgress(${J(id)});`);
2113
+ },
2114
+
2115
+ /**
2116
+ * Hard-stop everything (an infinite loop, say): the shared Worker and
2117
+ * panes' own Workers. Calls made from now on wait for the new Worker.
2118
+ * `quiet` leaves out onRestart (nothing to rerun: a canvas just opened,
2119
+ * ); `reason` is what onRestart hears (the canvas then puts back the
2120
+ * values it can and reruns the rest: Canvas#onRuntimeRestart).
2121
+ */
2122
+ async restart({ quiet = false, reason = RESTARTED } = {}) {
2123
+ // Panes' own Workers go too (their CSP is the old one); each starts again on its pane's next run.
2124
+ for (const id of [...ownSlots.keys()]) dropOwn(id);
2125
+ crossTab?.releaseAll?.("the sandbox restarted");
2126
+ midi?.releaseAll?.("the sandbox restarted");
2127
+ vfs?.releaseAll?.();
2128
+ companion?.releaseAll?.(); // the Worker that held the pane code (and its cleanups) is gone: so are its companion sockets
2129
+ const ready = replace(shared);
2130
+ if (!quiet) onRestart?.(new Error(reason));
2131
+ await ready;
2132
+ },
2133
+
2134
+ dispose() {
2135
+ companion?.releaseAll?.();
2136
+ crossTab?.releaseAll?.("the sandbox was closed");
2137
+ midi?.releaseAll?.("the sandbox was closed");
2138
+ vfs?.releaseAll?.();
2139
+ for (const id of [...ownSlots.keys()]) {
2140
+ const slot = ownSlots.get(id);
2141
+ ownSlots.delete(id);
2142
+ slot.disposed = true;
2143
+ slot.sandbox?.dispose();
2144
+ }
2145
+ strictRunner?.dispose();
2146
+ shared.disposed = true;
2147
+ return shared.sandbox?.dispose();
2148
+ },
2149
+ };
2150
+ }