@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,1303 @@
1
+ // Events: event outputs, readers that run once per
2
+ // event and sample their other inputs, and operators on wires.
3
+ //
4
+ // A value is "the latest one": a newer run supersedes an older one. An event
5
+ // is "this one happened": a click, a tick, a request. Each is delivered once,
6
+ // in order, and never superseded. In the dataflow (@johnhenry/dataflow 0.0.4):
7
+ //
8
+ // - An event output `pane#name` (an output with `type: "event"`, or one of its
9
+ // type's own: src/model/ports.js builtinEvents) is a node with no inputs and
10
+ // `queue: true`. Each event goes into its feed (a FIFO here) and asks for a
11
+ // run of the node; each run takes the oldest event, stores it in the Worker
12
+ // (a key per event, kept in a ring there) and settles the node with it, so
13
+ // each event is one settle, and readers get one trigger per event, in order.
14
+ // A run with nothing in the feed (run all, say) changes nothing.
15
+ // - A pane with an event input is a reader: its event inputs trigger it
16
+ // (`deps`), its other inputs are sampled (`sample`: read at their latest
17
+ // value, never triggering it: Noodl's Run, RxJS's withLatestFrom), and it
18
+ // runs once per event (`queue: true`, at most `queueLimit` waiting; past it
19
+ // the oldest is dropped and the pane warns). Its code sees the event as
20
+ // `event` ({ name, payload, at, source }) and the event input as the payload;
21
+ // another event input is undefined that run; `event.input` names the input
22
+ // it came in on. A pane without event inputs runs as before. One with
23
+ // `runsWithoutEvent` also runs where a reader skips (run all, ▶, an
24
+ // edit, no event yet), its event inputs undefined and no `event`: so a
25
+ // Toggle or Counter preset (src/model/event-presets.js) has a starting value.
26
+ // - A wire with operators (src/model/wire-ops.js) has a node of its own,
27
+ // `target##input`, between its source and the pane: its run pushes what
28
+ // crossed through the operators (src/model/wire-pipeline.js) and settles with
29
+ // what came out, one settle per output (a FIFO again), or changes nothing.
30
+ //
31
+ // Events come from pane code (emit.event(name, payload), or a value keyed by
32
+ // an event output's name: `yield outputs({ tick })`; worker-runtime.js sends
33
+ // them here in order), from the page (a timer's tick, a webhook request or a
34
+ // file event that mallory serve delivers, emit.event(name, payload) in a DOM,
35
+ // render or audio pane's frame or an html page's scripts (one way to
36
+ // fire, src/runtime/frame-events.js), an html pane's form submit), and from
37
+ // send() (tests, agents, the pane menu).
38
+ // Each source pane gets the runaway budget (src/model/runaway.js), the
39
+ // one live values, channel sends and state setters have: past it in a frame,
40
+ // delivery waits for the next frame; in a feedback loop past it, one a frame.
41
+ //
42
+ // The canvas transport (src/model/transport.js): events pane code sends
43
+ // while its pane is held (the canvas's live sources paused, or the pane's own
44
+ // ⏸) and its run isn't the one sending them (a callback's, a live run's) wait
45
+ // in their feed, in order, at most as many as the largest queueLimit of their
46
+ // readers (the oldest go past it), and go on play; a step lets one through.
47
+ // Held is decided when an event reaches the page, so one the Worker sent just
48
+ // before the pause that arrives after it is held too: it isn't lost, and
49
+ // it keeps its place in order. Events that reached the page before the pause
50
+ // go, even if their readers run after it.
51
+ // A live run that awaits frame() sends nothing while paused (no frames
52
+ // pass); a step moves it one frame, and the events that frame sends go at once,
53
+ // with the frame's value, not a step later (channels.js does the same).
54
+ // Events the person makes (send(): a frame's emit.event(), an html submit, a
55
+ // widget, mallory_send_event) are never held. Named channels (
56
+ // src/model/channels.js) follow the same rule; their held sends wait there.
57
+ //
58
+ // A repeater's instance (src/model/repeater.js) has an `outlet`: each
59
+ // event one of its panes sends goes out through it too, once it passes the
60
+ // transport (at once, or on play or a step), and comes back out of the
61
+ // repeater pane's "item" output as `{ key, name, payload, … }` (relay(): in
62
+ // order, each one, never coalesced, under the repeater pane's budget). A
63
+ // parked instance (kept for later) sends nothing.
64
+ //
65
+ // Finite batches (src/model/batches.js): an event can carry a batch key, and
66
+ // a batch marker (start, end, error, cancel) is an item of the same feed, in order
67
+ // with the events it closes. A marker settles the event node like an event (so the
68
+ // wires after it see it in order, and a pause or step holds it like one) but has no
69
+ // payload, no run of a reader and no place in a queue; an event wire hands it to its
70
+ // operators, which flush what they hold for that batch before the outputs reach the
71
+ // reader's queue.
72
+ //
73
+ // Pure apart from the canvas and runtime it is handed: it runs under node --test.
74
+ import { skip, UNCHANGED } from "@johnhenry/dataflow";
75
+ import { portId, splitPort, isEventDecl, outputsOf } from "./ports.js";
76
+ import { hasOperators, describeOperators, stagesOf, batchOf } from "./wire-ops.js";
77
+ import { WirePipeline } from "./wire-pipeline.js";
78
+ import { pausableClock } from "./pause-clock.js";
79
+ import { batchKeyProblem, markerProblem, cleanMarker } from "./batches.js";
80
+ import { LazyMap, LazySet } from "./lazy-map.js"; // most canvases send no events: their tables wait
81
+ import { QueueBook, queueBytesOf, queueExpireOf, queuePolicyOf, bytesText, spanText } from "./queue-book.js";
82
+ import { approxBytes } from "../runtime/keys.js";
83
+ import { ITEM_EVENTS } from "./repeater.js";
84
+
85
+ /** Events waiting for a reader, at most (a pane's `queueLimit`, by default). */
86
+ export const DEFAULT_QUEUE_LIMIT = 1000;
87
+ export const MAX_QUEUE_LIMIT = 100000;
88
+ /** Events waiting here for one event output to deliver them (beyond it the oldest go, counted). */
89
+ export const FEED_LIMIT = 10000;
90
+ /** Between a pane and an input's name, in a wire node's id (an output name can't hold "#"). */
91
+ export const WIRE_SEP = "##";
92
+
93
+ /** A pane's queue limit (its `queueLimit`, or the default). */
94
+ export const queueLimitOf = (pane) => (Number.isInteger(pane?.queueLimit) && pane.queueLimit >= 1 && pane.queueLimit <= MAX_QUEUE_LIMIT ? pane.queueLimit : DEFAULT_QUEUE_LIMIT);
95
+
96
+ /** Why `n` can't be a queue limit, or "". */
97
+ export const queueLimitProblem = (n) => (n === undefined || (Number.isInteger(n) && n >= 1 && n <= MAX_QUEUE_LIMIT) ? "" : `queueLimit is a whole number from 1 to ${MAX_QUEUE_LIMIT}`);
98
+
99
+ /**
100
+ * The limit dataflow holds a reader's triggers to. A reader that drops the
101
+ * oldest (the default) leaves it to dataflow, as it always has: past the
102
+ * queueLimit the oldest trigger goes. Another policy decides in the
103
+ * pane's QueueBook (src/model/queue-book.js) before an event is queued, so
104
+ * dataflow must never drop one of its own: no limit.
105
+ */
106
+ export const flowQueueLimit = (pane) => (queuePolicyOf(pane) === "drop-oldest" ? queueLimitOf(pane) : Infinity);
107
+
108
+ /** Does this patch of a pane change its queue's budgets or policy? */
109
+ export const QUEUE_SETTINGS = ["queueLimit", "queueBytes", "queueExpireMs", "queuePolicy"];
110
+
111
+ /** The node of the wire into pane `target` as input `name` when it carries operators. */
112
+ export const wireNodeId = (target, name) => `${target}${WIRE_SEP}${name}`;
113
+ export const isWireNode = (id) => String(id).includes(WIRE_SEP);
114
+
115
+ const words = (list) => (list.length < 2 ? list.join("") : `${list.slice(0, -1).join(", ")} or ${list.at(-1)}`);
116
+
117
+ export class CanvasEvents {
118
+ constructor(canvas) {
119
+ this.canvas = canvas;
120
+ this.feeds = new LazyMap(); // event node -> { queue: [{ key, result?, payload?, at, source }], had, dropped, held }: `held` of the queue's last items wait for the transport
121
+ this.wires = new LazyMap(); // wire node -> { target, name, dep, srcKey, kind, sig, pipeline, queue: [keys], had, lastFed, error? }
122
+ this.byTarget = new LazyMap(); // pane id -> Set(its wire nodes)
123
+ this.bindings = new LazyMap(); // reader id -> the event its current run is for
124
+ this.droppedSeen = new LazyMap(); // reader id -> state.dropped already warned about
125
+ this.facts = new LazyMap(); // `${id}:${runId}` -> the event a run was for (the run log)
126
+ this.seq = 0;
127
+ this.credit = new LazySet(); // animations a step moved by one frame: what that frame sends goes at once
128
+ this.notes = new LazyMap(); // pane id -> a warning to show again after its run settles
129
+ this.handled = new LazyMap(); // reader id -> Map(event node -> the version of the last event it ran for)
130
+ this.last = new LazyMap(); // reader id -> { status, reason? }: how its last run settled
131
+ this.settledAs = new Map(); // pane id (not a reader) -> how its last run settled
132
+ this.depVersions = new Map(); // pane id -> { input node -> the version it last ran for }: forMarkerOnly
133
+ this.outlet = null; // a repeater instance's: { wants() -> boolean, out(id, name, item) }
134
+ this.books = new LazyMap(); // reader id -> its QueueBook (src/model/queue-book.js): what waits for it, how big, how old, what was lost
135
+ this.sizes = new Map(); // event key -> its approximate size, for events that pass through a wire's operators (bounded)
136
+ this.discards = new Map(); // event key -> its node: events a person removed (a recorded take) that a reader may still need
137
+ }
138
+
139
+ // ── which outputs and inputs carry events ────────────────────────────────
140
+
141
+ /** Does pane `id`'s output `name` carry events? */
142
+ isEventOutput(id, name) {
143
+ if (!name) return false;
144
+ return isEventDecl(outputsOf(this.canvas.panes.get(id)).find((o) => o.name === name));
145
+ }
146
+
147
+ /** The event outputs of pane `id` (names). */
148
+ eventOutputs(id) {
149
+ return outputsOf(this.canvas.panes.get(id))
150
+ .filter(isEventDecl)
151
+ .map((o) => o.name);
152
+ }
153
+
154
+ /** Does an input read events (an event output of a pane on this canvas; one read through a subgraph pane is a value)? */
155
+ isEventInput(input) {
156
+ if (!input?.output) return false;
157
+ const home = this.canvas.inputHome(input);
158
+ return !home.path && this.isEventOutput(home.node, input.output);
159
+ }
160
+
161
+ /** The dataflow node pane `target`'s input waits for: its wire's node when it carries operators, else its source's. */
162
+ depOf(target, input) {
163
+ const home = this.canvas.inputHome(input);
164
+ const node = wireNodeId(target, input.name);
165
+ return hasOperators(input) && !home.path && this.wires.has(node) ? node : home.dep;
166
+ }
167
+
168
+ /** The Worker key of what pane `target`'s input reads (outside an event run): its wire's output, or its source's value. */
169
+ keyOf(target, input) {
170
+ const home = this.canvas.inputHome(input);
171
+ const node = wireNodeId(target, input.name);
172
+ return hasOperators(input) && !home.path && this.wires.has(node) ? node : home.key;
173
+ }
174
+
175
+ /**
176
+ * Is this run of pane `id` only for batch markers? A marker settles its event node like an event, so a
177
+ * dependent that doesn't read events one by one (an agent pane waiting for the output as a value) would run
178
+ * again for each boundary though nothing new arrived: it keeps what it has instead. A run that something else
179
+ * asked for (`asked`: ▶, an edit) or that another input caused still runs. Called on every run of such a pane,
180
+ * to note which versions of its inputs it has seen.
181
+ */
182
+ forMarkerOnly(id, { asked = false } = {}) {
183
+ const flow = this.canvas.flow;
184
+ if (flow.queues?.(id)) return false;
185
+ const deps = flow.deps(id) ?? [];
186
+ const seen = this.depVersions.get(id) ?? new Map();
187
+ this.depVersions.set(id, seen);
188
+ const changed = deps.filter((d) => seen.get(d) !== flow.get(d)?.version);
189
+ for (const d of deps) seen.set(d, flow.get(d)?.version);
190
+ return !asked && this.settledAs.get(id) === "done" && changed.length > 0 && changed.every((d) => this.feeds.has(d) && flow.get(d)?.result?.event?.marker);
191
+ }
192
+
193
+ /**
194
+ * A pane's dataflow inputs: `{ deps, sample, events }`. With an event input,
195
+ * `deps` are its event inputs and `sample` the others; otherwise every input
196
+ * is in `deps`, as before.
197
+ */
198
+ plan(id, pane) {
199
+ const events = [];
200
+ const values = [];
201
+ for (const input of pane.inputs) {
202
+ if (this.canvas.writeTarget?.(input)) continue; // a setter wire isn't a dependency
203
+ (this.isEventInput(input) ? events : values).push(this.depOf(id, input));
204
+ }
205
+ const unique = (list) => [...new Set(list)];
206
+ if (!events.length) return { deps: unique(values), sample: [], events: [] };
207
+ return { deps: unique(events), sample: unique(values).filter((d) => !events.includes(d)), events: unique(events) };
208
+ }
209
+
210
+ // ── nodes ────────────────────────────────────────────────────────────────
211
+
212
+ /** Is this dataflow node one of ours (an event output's or a wire's)? */
213
+ owns(nodeId) {
214
+ return this.wires.has(nodeId) || isWireNode(nodeId) || this.feeds.has(nodeId);
215
+ }
216
+
217
+ /** Event output node `node` (pane `id`'s output): no inputs, a queue; a new one says "no event yet" at once. */
218
+ syncEventNode(node) {
219
+ const c = this.canvas;
220
+ const fresh = !c.flow.has(node) || !this.feeds.has(node);
221
+ c.flow.set(node, { deps: [], queue: true, queueLimit: Infinity });
222
+ if (!this.feeds.has(node)) this.feeds.set(node, { queue: [], had: false, dropped: 0 });
223
+ if (fresh && c.trusted.value && !c.flow.paused) c.flow.run(node);
224
+ }
225
+
226
+ /** An event output went (deleted, or no longer an event output): forget what waited for it. */
227
+ forgetNode(node) {
228
+ this.feeds.delete(node);
229
+ this.#forgetVersions(node);
230
+ }
231
+
232
+ /** A node went (its versions start again if it comes back): readers forget what they handled from it. */
233
+ #forgetVersions(node) {
234
+ for (const seen of this.handled.values()) seen.delete(node);
235
+ }
236
+
237
+ /** Pane `id`'s wires with operators: a node each, between its source and the pane. Others go. */
238
+ syncWires(id, pane, { reads = true } = {}) {
239
+ const c = this.canvas;
240
+ const want = new Map();
241
+ if (reads) {
242
+ for (const input of pane?.inputs ?? []) {
243
+ if (!hasOperators(input) || c.inputHome(input).path || c.writeTarget?.(input)) continue; // a setter wire's operators do nothing
244
+ want.set(wireNodeId(id, input.name), input);
245
+ }
246
+ }
247
+ const had = this.byTarget.get(id) ?? new Set();
248
+ for (const node of had) if (!want.has(node)) this.#deleteWire(node);
249
+ for (const [node, input] of want) {
250
+ const home = c.inputHome(input);
251
+ const kind = this.isEventInput(input) ? "event" : "value";
252
+ const sig = JSON.stringify([home.dep, home.key, kind, input.operators]);
253
+ let w = this.wires.get(node);
254
+ const changed = !w || w.sig !== sig;
255
+ if (changed) {
256
+ w?.pipeline.dispose();
257
+ // `batch run` (value wires from a live pane's own value): each run of the source is a finite batch (liveEnded closes it).
258
+ const runBatch = kind === "value" && splitPort(home.dep).name === undefined ? batchOf(input.operators) : undefined;
259
+ w = { node, target: id, name: input.name, output: input.output, dep: home.dep, srcKey: home.key, kind, sig, operators: input.operators, queue: [], had: false, lastFed: 0, batchBytes: new Map(), ...(runBatch ? { runBatch, marks: [] } : {}) };
260
+ w.pipeline = this.#pipeline(w);
261
+ this.wires.set(node, w);
262
+ }
263
+ c.flow.set(node, { deps: [home.dep], queue: true, queueLimit: Infinity });
264
+ // New, or its operators changed: start it on what its source has now (a source still to run starts it itself).
265
+ const status = c.flow.get(home.dep)?.status;
266
+ if (changed && c.trusted.value && (status === "done" || status === "skipped")) c.flow.run(node, { replace: true });
267
+ }
268
+ if (want.size) this.byTarget.set(id, new Set(want.keys()));
269
+ else this.byTarget.delete(id);
270
+ }
271
+
272
+ /** The clock window operators run on: the canvas's, stopped while the transport is paused. Made with the first window. */
273
+ #windowClock() {
274
+ if (this.pausable) return this.pausable;
275
+ const c = this.canvas;
276
+ const clock = (this.pausable = pausableClock(c.clock));
277
+ const transport = c.transport;
278
+ const sync = () => clock.setPaused(transport.paused);
279
+ transport.addEventListener("change", sync);
280
+ this.unsync = () => transport.removeEventListener("change", sync);
281
+ sync();
282
+ return clock;
283
+ }
284
+
285
+ #pipeline(w) {
286
+ const c = this.canvas;
287
+ return new WirePipeline({
288
+ ...(stagesOf(w.operators).some((st) => st.kind === "window") ? { windowClock: this.#windowClock() } : {}),
289
+ id: w.node,
290
+ kind: w.kind,
291
+ operators: w.operators,
292
+ runtime: c.runtime,
293
+ clock: c.clock,
294
+ onOutput: (key, bytes) => {
295
+ if (this.wires.get(w.node) !== w) return;
296
+ // The reader's queue decides: an event its budgets refuse never reaches the wire's node, and its stored copy goes.
297
+ if (w.kind === "event" && !this.#admitFromWire(w, key, bytes)) {
298
+ c.runtime.wireDrop?.({ keys: [key] })?.catch?.(() => {});
299
+ return;
300
+ }
301
+ w.queue.push(key);
302
+ if (c.flow.has(w.node) && !c.disposed) c.flow.run(w.node);
303
+ },
304
+ onError: (error) => {
305
+ if (this.wires.get(w.node) !== w || c.disposed) return;
306
+ w.error = error;
307
+ if (c.flow.has(w.node)) c.flow.run(w.node);
308
+ },
309
+ });
310
+ }
311
+
312
+ #deleteWire(node) {
313
+ const w = this.wires.get(node);
314
+ w?.pipeline.dispose();
315
+ this.wires.delete(node);
316
+ this.#forgetVersions(node);
317
+ const c = this.canvas;
318
+ if (c.flow.has(node)) c.flow.delete(node);
319
+ c.runtime.forget?.(node);
320
+ }
321
+
322
+ /** Pane `id` went: its wires' nodes, its event outputs' feeds, its run's binding. */
323
+ forgetPane(id) {
324
+ this.#closeBatches(id, "cancel", "its source was deleted", { now: true });
325
+ // Wires that batch by run: its runs' batches can't end now, and nothing is left to hand a partial result to.
326
+ for (const w of this.wires.values()) {
327
+ if (!w.runBatch || w.dep !== id) continue;
328
+ w.marks.length = 0;
329
+ for (const batch of w.pipeline.open) this.#markWire(w, { kind: "cancel", batch, reason: "its source was deleted", discard: true }).catch(() => {});
330
+ }
331
+ for (const node of this.byTarget.get(id) ?? []) this.#deleteWire(node);
332
+ this.byTarget.delete(id);
333
+ for (const node of [...this.feeds.keys()]) if (splitPort(node).id === id) this.feeds.delete(node);
334
+ this.bindings.delete(id);
335
+ this.handled.delete(id);
336
+ this.last.delete(id);
337
+ this.droppedSeen.delete(id);
338
+ this.books.delete(id); // its queue: nothing it held outlives it
339
+ this.depVersions.delete(id);
340
+ this.settledAs.delete(id);
341
+ this.credit.delete(id);
342
+ this.canvas.guard?.forget(this.canvas.runawayKey(id));
343
+ this.canvas.channels?.forgetPane(id); // its channel sends waiting for the transport
344
+ }
345
+
346
+ // ── running ──────────────────────────────────────────────────────────────
347
+
348
+ /** dataflow's run for one of our nodes. */
349
+ run(node, ctx) {
350
+ return this.wires.has(node) ? this.#runWire(node, ctx) : this.#runEvent(node, ctx);
351
+ }
352
+
353
+ async #runEvent(node, ctx) {
354
+ const c = this.canvas;
355
+ const { name } = splitPort(node);
356
+ const feed = this.feeds.get(node);
357
+ if (!feed) return skip(`no "${name}" output any more`);
358
+ const item = feed.queue.shift();
359
+ if (!item) return feed.had ? UNCHANGED : skip(`no "${name}" event yet`);
360
+ if (item.marker) return { ...(feed.preview ? { preview: feed.preview } : {}), event: { key: item.key, name, at: item.at, source: item.source, marker: item.marker } }; // a batch boundary: nothing to store, but the node settles in order
361
+ let result = item.result;
362
+ if (!result && item.pending) {
363
+ result = await item.pending; // relayed: its store in the Worker started when it came
364
+ if (ctx.signal?.aborted) return { superseded: true };
365
+ } else if (!result) {
366
+ (feed.storing ??= new Set()).add(item.key); // a removal waits until the Worker has it
367
+ try {
368
+ result = await c.runtime.storeEvent({ node, key: item.key, name, payload: item.payload, at: item.at, source: item.source, keep: this.keepFor(node), ...(item.batch === undefined ? {} : { batch: item.batch }) });
369
+ } finally {
370
+ feed.storing.delete(item.key);
371
+ }
372
+ if (this.discards.size) this.#flushDiscards();
373
+ if (ctx.signal?.aborted) return { superseded: true };
374
+ }
375
+ feed.had = true;
376
+ feed.preview = result?.preview;
377
+ return { ...result, event: { key: item.key, name, at: item.at, source: item.source, ...(item.batch === undefined ? {} : { batch: item.batch }) } };
378
+ }
379
+
380
+ async #runWire(node, ctx) {
381
+ const c = this.canvas;
382
+ const w = this.wires.get(node);
383
+ if (!w) return skip("this wire has no operators any more");
384
+ if (w.error) {
385
+ const error = w.error;
386
+ w.error = undefined;
387
+ throw error;
388
+ }
389
+ const t = ctx.trigger;
390
+ if (t?.type === "settle") {
391
+ if (!t.skip && t.id === w.dep) {
392
+ if (w.kind === "event") {
393
+ const event = t.result?.event;
394
+ if (event?.marker) await this.#markWire(w, event.marker);
395
+ else if (event?.key) {
396
+ w.fedBytes = this.sizes.get(event.key) ?? 0; // what leaves the operators is taken to be about as big as what went in
397
+ if (event.batch !== undefined) w.batchBytes.set(event.batch, w.fedBytes);
398
+ await w.pipeline.feed(event.key, event.batch);
399
+ }
400
+ } else if (t.version > w.lastFed) {
401
+ w.lastFed = t.version;
402
+ await this.#feedValue(w);
403
+ }
404
+ }
405
+ } else if (w.kind === "value") {
406
+ // Run all, ▶, a restart: what the source has now, unless it already went through.
407
+ const s = c.flow.get(w.dep);
408
+ if (s?.status === "done" && s.version > w.lastFed) {
409
+ w.lastFed = s.version;
410
+ await this.#feedValue(w);
411
+ }
412
+ }
413
+ if (w.marks?.length) await this.#runMarks(w);
414
+ if (ctx.signal?.aborted) return { superseded: true };
415
+ const key = w.queue.shift();
416
+ if (key === undefined) return w.had ? UNCHANGED : skip(this.#waiting(w));
417
+ const result = await c.runtime.wireTake({ wire: node, key, kind: w.kind, keep: this.keepFor(node), view: "auto", runId: ctx.runId });
418
+ if (ctx.signal?.aborted) return { superseded: true };
419
+ w.had = true;
420
+ if (w.kind !== "event") return result;
421
+ const { key: kept = key, ...rest } = result ?? {};
422
+ return { ...rest, event: { key: kept, name: w.output } };
423
+ }
424
+
425
+ /** The source's current value goes into wire `w`'s operators, as part of its run's batch when the wire is `batch run` and the value came from a live run. */
426
+ async #feedValue(w) {
427
+ const batch = this.#runBatchKey(w);
428
+ if (batch !== undefined && !w.pipeline.open.includes(batch)) await w.pipeline.mark({ kind: "start", batch, onCancel: w.runBatch.onCancel });
429
+ await w.pipeline.feed(w.srcKey, batch);
430
+ }
431
+
432
+ /** The batch key of the value pane `w.dep` has now (`run-<id>`), when `w` batches by run and a live run made it. */
433
+ #runBatchKey(w) {
434
+ if (!w.runBatch) return undefined;
435
+ const runId = this.canvas.flow.get(w.dep)?.runId;
436
+ return runId !== undefined && this.canvas.live.get(w.dep)?.runId === runId ? runBatchKey(runId) : undefined;
437
+ }
438
+
439
+ /**
440
+ * Source pane `id`'s live run `runId` ended (src/model/live.js): `outcome` is "end" (it returned, or emit.close()),
441
+ * "error" (it threw) or "cancel" (a restart, an edit, ▶, a deletion). On the value wires that batch by run the
442
+ * run's batch gets that marker, after the last value it made.
443
+ */
444
+ liveEnded(id, runId, outcome, reason) {
445
+ const c = this.canvas;
446
+ if (c.disposed) return;
447
+ const batch = runBatchKey(runId);
448
+ const state = c.flow.get(id);
449
+ for (const w of this.wires.values()) {
450
+ if (!w.runBatch || w.dep !== id) continue;
451
+ w.marks.push({ kind: outcome, batch, version: state?.version, ...(reason ? { reason: String(reason).slice(0, 500) } : {}) });
452
+ // A last value the wire hasn't taken yet goes in first (its own run does that, then the marker); otherwise the batch closes now.
453
+ if (state?.status === "done" && state.version > w.lastFed && c.flow.has(w.node)) c.flow.run(w.node);
454
+ else
455
+ this.#runMarks(w).catch((error) => {
456
+ if (this.wires.get(w.node) !== w || c.disposed) return;
457
+ w.error = error;
458
+ if (c.flow.has(w.node)) c.flow.run(w.node);
459
+ });
460
+ }
461
+ }
462
+
463
+ /** The end markers waiting on wire `w`, in order: a value the run made last goes in first, then the batch closes (a batch that never opened has nothing to close). */
464
+ async #runMarks(w) {
465
+ const c = this.canvas;
466
+ for (const marker of w.marks.splice(0)) {
467
+ if (this.wires.get(w.node) !== w) return;
468
+ const s = c.flow.get(w.dep);
469
+ if (s?.status === "done" && s.version === marker.version && s.version > w.lastFed) {
470
+ w.lastFed = s.version;
471
+ await this.#feedValue(w);
472
+ }
473
+ if (w.pipeline.open.includes(marker.batch)) await this.#markWire(w, marker);
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Source pane `id` failed or went: the finite batches still open on wires that read its event outputs can never
479
+ * be ended by it, so each is closed with the marker the source's own start declared a policy for (error: onError;
480
+ * cancel: onCancel; discard unless it said emit). A failure goes down the source's feed, in order after its events;
481
+ * a deletion has no feed left, so the wires are told directly.
482
+ */
483
+ #closeBatches(id, kind, reason, { now = false } = {}) {
484
+ const c = this.canvas;
485
+ if (c.disposed) return;
486
+ for (const w of this.wires.values()) {
487
+ if (w.kind !== "event" || splitPort(w.dep).id !== id || !w.pipeline.open.length) continue;
488
+ // A repeater's `item` batches belong to its instances (closeInstanceBatches ends the ones whose source failed or went):
489
+ // the repeater pane failing because some instance did must not end the healthy instances' batches.
490
+ if (splitPort(w.dep).name === ITEM_EVENTS && this.canvas.repeaters?.has(id)) continue;
491
+ for (const batch of w.pipeline.open) {
492
+ if ((w.closing ??= new Set()).has(batch)) continue;
493
+ w.closing.add(batch);
494
+ const marker = { kind, batch, reason: reason.slice(0, 500) };
495
+ if (now) this.#markWire(w, marker).catch(() => {});
496
+ else if (!this.sendMarker(id, w.output, marker, { source: `${c.panes.get(id)?.name || id} (closed by mallory)` }).sent) w.closing.delete(batch);
497
+ }
498
+ }
499
+ this.outlet?.close?.(id, kind, reason); // batches this canvas's wires don't hold, but the repeater's readers do
500
+ }
501
+
502
+ /** A batch marker reached wire `w`: its operators flush (or drop) what they hold for the batch, and the outputs go on to the reader's queue. */
503
+ async #markWire(w, marker) {
504
+ const { kind, batch } = marker;
505
+ const bytes = w.batchBytes.get(batch);
506
+ if (bytes !== undefined) w.fedBytes = bytes; // flushed events are about as big as the last one fed to this batch
507
+ try {
508
+ const done = await w.pipeline.mark(marker);
509
+ if (kind === "error" || kind === "cancel") {
510
+ const why = kind === "error" ? `failed${marker.reason ? `: ${marker.reason}` : ""}` : `was cancelled${marker.reason ? ` (${marker.reason})` : ""}`;
511
+ const unit = w.kind === "event" ? "event" : "value";
512
+ this.#warn(w.target, `batch "${batch}" ${why}; its partial results ${done.discarded ? `were discarded (${done.fed} ${unit}${done.fed === 1 ? "" : "s"} had been fed)` : `were emitted${w.kind === "event" ? ", marked partial" : ""}`}`);
513
+ }
514
+ } finally {
515
+ if (kind !== "start") (w.batchBytes.delete(batch), w.closing?.delete(batch));
516
+ }
517
+ }
518
+
519
+ /** Why a wire has nothing yet: what its operators are holding back. */
520
+ #waiting(w) {
521
+ const ops = describeOperators(w.operators);
522
+ const open = w.pipeline.open;
523
+ if (open.length) return `waiting for the end of batch${open.length === 1 ? "" : "es"} ${open.join(", ")} (${ops})`;
524
+ if (w.pipeline.busy) return `waiting: ${ops}`;
525
+ return w.kind === "event" ? `no event has come through ${ops} yet` : `nothing has come through ${ops} yet`;
526
+ }
527
+
528
+ /**
529
+ * The event pane `id`'s run `ctx` is for, when it reads events: `{ skip }`
530
+ * (a run all, an edit or ▶ isn't an event; nor is "no event yet"), or the
531
+ * binding its run uses (the key of the event's payload for the input that
532
+ * fired, the others undefined). null: not a reader.
533
+ */
534
+ bind(id, pane, ctx) {
535
+ this.bindings.delete(id);
536
+ if (!this.canvas.flow.queues?.(id)) return null; // not a reader (a pinned pane, an agent pane): its inputs are values
537
+ const idx = [];
538
+ pane.inputs.forEach((input, n) => this.isEventInput(input) && idx.push(n));
539
+ if (!idx.length) return null;
540
+ const names = idx.map((n) => pane.inputs[n].name);
541
+ const deps = idx.map((n) => this.depOf(id, pane.inputs[n]));
542
+ // A reader that runs without an event too (`runsWithoutEvent`: the Toggle and Counter presets) runs
543
+ // where others skip (run all, ▶, an edit, no event yet), its event inputs undefined and no `event`: a starting value.
544
+ const idle = (reason) => (pane.runsWithoutEvent ? this.#idle(id, ctx, idx, deps) : { skip: reason });
545
+ const t = ctx.trigger;
546
+ if (!t || t.type !== "settle") return idle(`runs once per event: waiting for ${words(names)}`);
547
+ if (t.skip) return idle(t.skip.reason === undefined ? `no event on ${words(names)} yet` : String(t.skip.reason));
548
+ const at = deps.indexOf(t.id);
549
+ const key = t.result?.event?.key;
550
+ if (at >= 0 && t.result?.event?.marker) return this.last.get(id)?.status === "done" ? { unchanged: true } : { skip: `runs once per event: a batch marker is not an event` }; // a boundary for wires' operators: no event, no run
551
+ if (at < 0 || !key) return idle(`runs once per event: waiting for ${words(names)}`);
552
+ // Each event once: a settle of the same version again (an unchanged no-op run of its node) isn't a new event.
553
+ const seen = this.handled.get(id) ?? new Map();
554
+ if ((seen.get(t.id) ?? -1) >= t.version) return this.last.get(id)?.status === "done" ? { unchanged: true } : idle(this.last.get(id)?.reason ?? `runs once per event: waiting for ${words(names)}`);
555
+ seen.set(t.id, t.version);
556
+ this.handled.set(id, seen);
557
+ // Its queue lets go of the event; one it dropped, refused or let expire is skipped without running the code.
558
+ const left = this.#take(id, t.id, key);
559
+ if (left.skip !== undefined) return this.last.get(id)?.status === "done" ? { unchanged: true } : { skip: left.skip };
560
+ const fired = idx[at];
561
+ const keys = new Map(idx.map((n, k) => [n, n === fired ? key : deps[k]]));
562
+ const binding = {
563
+ runId: ctx.runId,
564
+ index: fired,
565
+ key,
566
+ keys,
567
+ eventDeps: new Set(deps),
568
+ skippedKeys: deps.filter((d, k) => idx[k] !== fired),
569
+ event: { input: pane.inputs[fired].name, name: t.result.event.name, at: t.result.event.at, source: t.result.event.source, ...(t.result.preview ? { preview: t.result.preview } : {}) },
570
+ };
571
+ this.bindings.set(id, binding);
572
+ this.facts.set(`${id}:${ctx.runId}`, binding.event);
573
+ while (this.facts.size > 500) this.facts.delete(this.facts.keys().next().value);
574
+ return binding;
575
+ }
576
+
577
+ /** A run of reader `id` that isn't for an event: every event input undefined (skipped), no `event`. */
578
+ #idle(id, ctx, idx, deps) {
579
+ const binding = { runId: ctx.runId, idle: true, keys: new Map(idx.map((n, k) => [n, deps[k]])), eventDeps: new Set(deps), skippedKeys: [...deps] };
580
+ this.bindings.set(id, binding);
581
+ return binding;
582
+ }
583
+
584
+ /** The binding of pane `id`'s current event run (undefined outside one). */
585
+ bound(id) {
586
+ return this.bindings.get(id);
587
+ }
588
+
589
+ unbind(id) {
590
+ this.bindings.delete(id);
591
+ }
592
+
593
+ /** What the run log keeps about run `runId` of pane `id` (src/model/runlog.js): `{ event }`, or {}. */
594
+ stepFacts(id, runId) {
595
+ const event = this.facts.get(`${id}:${runId}`);
596
+ return event ? { event } : {};
597
+ }
598
+
599
+ /** How many events the Worker keeps for an event node or event wire: enough for every reader's queue. */
600
+ keepFor(node) {
601
+ const c = this.canvas;
602
+ let max = DEFAULT_QUEUE_LIMIT;
603
+ const visit = (n, depth) => {
604
+ for (const d of c.flow.dependents(n)) {
605
+ const pane = c.panes.get(d);
606
+ if (pane) max = Math.max(max, queueLimitOf(pane));
607
+ else if (depth < 4 && this.wires.has(d)) visit(d, depth + 1);
608
+ }
609
+ };
610
+ visit(node, 0);
611
+ return Math.min(max, MAX_QUEUE_LIMIT) + 2;
612
+ }
613
+
614
+ /** The largest queueLimit of the panes that read event node `node` (through event wires too): what may wait for the transport. */
615
+ #readersLimit(node) {
616
+ const c = this.canvas;
617
+ let max = 0;
618
+ const visit = (n, depth) => {
619
+ for (const d of c.flow.dependents(n)) {
620
+ const pane = c.panes.get(d);
621
+ if (pane) max = Math.max(max, queueLimitOf(pane));
622
+ else if (depth < 4 && this.wires.has(d)) visit(d, depth + 1);
623
+ }
624
+ };
625
+ visit(node, 0);
626
+ return max || DEFAULT_QUEUE_LIMIT;
627
+ }
628
+
629
+ /** The keep (above) for pane `id`'s event outputs, the largest: the Worker stores its emit.event()s with it. */
630
+ keepForPane(id) {
631
+ return Math.max(DEFAULT_QUEUE_LIMIT + 2, ...this.eventOutputs(id).map((name) => this.keepFor(portId(id, name))));
632
+ }
633
+
634
+ // ── delivering ───────────────────────────────────────────────────────────
635
+
636
+ /**
637
+ * Send an event out of pane `id`'s event output `name` (the page's sources,
638
+ * tests, agents). Returns `{ sent: true }`, or `{ sent: false, reason }`.
639
+ */
640
+ send(id, name, payload, { source, batch, withKey, ack } = {}) {
641
+ if (batch !== undefined && batchKeyProblem(batch)) return { sent: false, reason: batchKeyProblem(batch) };
642
+ return this.#sendItem(id, name, { payload: payload === undefined ? null : payload, ...(batch === undefined ? {} : { batch }) }, { source, withKey, ack });
643
+ }
644
+
645
+ /**
646
+ * The person removed what event `key` of pane `id`'s output `name` carried (a recorded take): the Worker lets go
647
+ * of it (and of a Blob it holds), as soon as no reader still waits for it, is running on it, or is yet to be told of it:
648
+ * a removal never takes an event from a reader (ordering: each event is still read once, in order). A wire with
649
+ * operators on the output keeps its own copy of what passes through it. Returns `{ discarded: true }` (done now or
650
+ * when the last reader is through) or `{ discarded: false, reason }`.
651
+ */
652
+ discard(id, name, key) {
653
+ const node = portId(id, name);
654
+ if (typeof key !== "string" || !key.startsWith(`${node}@`)) return { discarded: false, reason: "that is not an event of this output" };
655
+ this.discards.set(key, node);
656
+ while (this.discards.size > 500) this.discards.delete(this.discards.keys().next().value);
657
+ this.#flushDiscards();
658
+ return { discarded: true };
659
+ }
660
+
661
+ /** Does anything still need event `key`: its output's feed (waiting or being stored), a reader's queue or a reader's run? */
662
+ #needed(key, node) {
663
+ const feed = this.feeds.get(node);
664
+ if (!feed) return false;
665
+ if (feed.storing?.has(key) || feed.queue.some((item) => item.key === key)) return true;
666
+ for (const book of this.books.values()) if (book.entries.some((e) => e.key === key)) return true;
667
+ for (const [reader, b] of this.bindings) if (b.key === key && this.canvas.flow.get(reader)?.status === "running") return true;
668
+ for (const w of this.wires.values()) if (w.kind === "event" && w.dep === node && this.#wireOwes(w)) return true;
669
+ return false;
670
+ }
671
+
672
+ /**
673
+ * Is something still on its way to the reader of wire `w` through its operators? The reader is owed what comes
674
+ * out of them, which the Worker keeps under the wire's own keys, so a removal can't tell which output carries which
675
+ * source event: it waits until the wire is quiet (nothing being fed or released, no output waiting for the page, none in
676
+ * the reader's queue or running). Batches the operators hold in their own state are left alone either way.
677
+ */
678
+ #wireOwes(w) {
679
+ const c = this.canvas;
680
+ const run = c.flow.get(w.node);
681
+ if (run?.status === "running" || (run?.queued ?? 0) > 0) return true;
682
+ if (w.queue.length || w.pipeline.working || w.pipeline.busy) return true;
683
+ const prefix = `${w.node}@`;
684
+ if (this.books.get(w.target)?.entries.some((e) => e.dep === w.node)) return true;
685
+ const b = this.bindings.get(w.target);
686
+ return Boolean(b?.key?.startsWith(prefix) && c.flow.get(w.target)?.status === "running");
687
+ }
688
+
689
+ /** Drop the removed events nothing needs any more (called as readers finish). */
690
+ #flushDiscards() {
691
+ for (const [key, node] of [...this.discards]) {
692
+ if (this.#needed(key, node)) continue;
693
+ this.discards.delete(key);
694
+ this.canvas.runtime.discardEvent?.({ node, key });
695
+ }
696
+ }
697
+
698
+ /**
699
+ * Send a batch marker (`{ kind, batch, reason?, onError?, onCancel? }`) out of pane `id`'s event output
700
+ * `name`, in order with its events. Returns `{ sent: true }`, or `{ sent: false, reason }`.
701
+ */
702
+ sendMarker(id, name, marker, { source, ack } = {}) {
703
+ const problem = markerProblem(marker);
704
+ if (problem) return { sent: false, reason: problem };
705
+ return this.#sendItem(id, name, { marker: cleanMarker(marker) }, { source, ack });
706
+ }
707
+
708
+ #sendItem(id, name, fields, { source, withKey, ack } = {}) {
709
+ const c = this.canvas;
710
+ const pane = c.panes.get(id);
711
+ if (!pane || !c.attached.has(id)) return { sent: false, reason: "no such pane on this canvas" };
712
+ const outs = this.eventOutputs(id);
713
+ if (!outs.length) return { sent: false, reason: `${pane.name || id} has no event outputs (give it one: Outputs…, type "event")` };
714
+ name ??= outs.length === 1 ? outs[0] : undefined;
715
+ if (!outs.includes(name)) return { sent: false, reason: `${pane.name || id} has no event output ${name === undefined ? "named (it has several)" : `"${name}"`}: its event outputs are ${outs.join(", ")}` };
716
+ if (!c.trusted.value) return { sent: false, reason: 'the canvas is paused until "Run it"' };
717
+ if (c.isDisabled(id)) return { sent: false, reason: `${pane.name || id} is deactivated` };
718
+ if (c.parked) return { sent: false, reason: "this repeater instance is kept for later (its key went): it sends nothing until its key comes back" };
719
+ const node = portId(id, name);
720
+ const key = `${node}@p${++this.seq}`;
721
+ const queued = this.#enqueue(id, node, { key, ...fields, at: new Date(c.clock.now()).toISOString(), source: source ?? (pane.name || id) });
722
+ if (!queued.accepted) return { sent: false, reason: queued.reason, refused: queued.refused.map(({ pane: who, kind }) => ({ pane: who, kind })) };
723
+ return { sent: true, name, ...(ack ? { queued: queued.readers } : {}), ...(withKey ? { key } : {}), ...(queued.refused.length ? { refusedBy: queued.refused.map(({ pane: who, kind, reason }) => ({ pane: who, kind, reason })) } : {}) };
724
+ }
725
+
726
+ /** A built-in source fired (a timer tick, a delivered request or file event): its event, when something reads it. */
727
+ builtin(id, name, payload) {
728
+ const node = portId(id, name);
729
+ if (!this.feeds.has(node) || (!this.canvas.flow.dependents(node).length && !this.outlet?.wants())) return { sent: false, reason: "nothing reads it" };
730
+ return this.send(id, name, payload);
731
+ }
732
+
733
+ /** Has event output `name` of pane `id` readers? */
734
+ hasReaders(id, name) {
735
+ const node = portId(id, name);
736
+ return this.feeds.has(node) && this.canvas.flow.dependents(node).length > 0;
737
+ }
738
+
739
+ /** Events from pane code, in order (worker-runtime.js): `[{ name, key, result, at, source }]`, keys already this canvas's. */
740
+ fromWorker(id, list) {
741
+ const c = this.canvas;
742
+ const acks = {}; // events whose sender asked to hear (emit.event(…, { ack: true })): ackKey -> the answer
743
+ const answer = (e, result) => {
744
+ if (e?.ackKey === undefined) return;
745
+ acks[e.ackKey] = result.accepted
746
+ ? { accepted: true, ...(result.held ? { held: true } : {}), queued: result.readers, ...(result.refused.length ? { refusedBy: result.refused.map(({ pane, kind, reason }) => ({ pane, kind, reason })) } : {}) }
747
+ : { accepted: false, reason: result.reason, refused: result.refused.map(({ pane, kind, reason }) => ({ pane, kind, reason })) };
748
+ };
749
+ if (!c.attached.has(id) || c.disposed || c.parked) {
750
+ for (const e of list ?? []) {
751
+ if (e?.channel !== undefined && e.ackKey !== undefined) acks[e.ackKey] = { accepted: false, queued: 0, reason: "no such pane on this canvas, or it is kept for later" };
752
+ else answer(e, { accepted: false, reason: "no such pane on this canvas, or it is kept for later", refused: [] });
753
+ }
754
+ return Object.keys(acks).length ? { acks } : undefined;
755
+ }
756
+ const held = this.#held(id);
757
+ let deferred; // keys of acknowledged channel sends whose answer comes later
758
+ let replying = true; // an acknowledged send's answer is in this call's reply while it is, and pushed to the Worker after
759
+ for (const e of list ?? []) {
760
+ if (e?.channel !== undefined) {
761
+ // send() on a named channel (src/model/channels.js); { ack: true }: the page's answer, now or once a paced send goes.
762
+ const key = e.ackKey;
763
+ let answered = false;
764
+ const ack = key === undefined ? undefined : (answer) => ((answered = true), replying ? void (acks[key] = answer) : void c.runtime.settleSendAck?.({ id, key, answer }));
765
+ c.channels?.fromWorker(id, e, { held, ack });
766
+ if (key !== undefined && !answered) (deferred ??= []).push(key); // a paced send: answered when it goes, not in this reply
767
+ continue;
768
+ }
769
+ const node = portId(id, e.name);
770
+ if (!this.feeds.has(node)) {
771
+ answer(e, { accepted: false, reason: `"${e.name}" is not an event output of this pane (any more)`, refused: [] });
772
+ continue; // not an event output (any more)
773
+ }
774
+ const isHeld = held && !this.credit.has(id);
775
+ answer(e, { ...this.#enqueue(id, node, { key: e.key, result: e.result, at: this.#arrival(e.at), source: e.source, bytes: e.bytes, ...(e.batch === undefined ? {} : { batch: e.batch }), ...(e.marker ? { marker: e.marker } : {}) }, { held: isHeld }), held: isHeld });
776
+ }
777
+ replying = false;
778
+ return Object.keys(acks).length || deferred ? { acks, ...(deferred ? { deferred } : {}) } : undefined;
779
+ }
780
+
781
+ /** Are pane `id`'s events from the Worker held: it is a held source, and they don't come from a run of it in progress (a person's edit, an input)? */
782
+ #held(id) {
783
+ const c = this.canvas;
784
+ const transport = c.root?.ownTransport;
785
+ if (!transport?.holds(c, id)) return false;
786
+ if (c.liveWatches?.has(id)) return true; // a live source (a yield or emit pane's run)
787
+ const state = c.flow.get(id);
788
+ return state?.status !== "running" && !state?.live; // a callback's; a resume pane moves when its inputs change (propagation)
789
+ }
790
+
791
+ /**
792
+ * An event for event output `node`: first the readers' queues say whether they take it
793
+ * (every policy's word is `#admit`'s), then it joins the output's feed. Returns `#admit`'s answer:
794
+ * `{ accepted, readers, refused: [{ pane, kind, reason }], reason? }`.
795
+ */
796
+ #enqueue(id, node, item, { held = false } = {}) {
797
+ const c = this.canvas;
798
+ const feed = this.feeds.get(node);
799
+ if (!feed) return { accepted: false, readers: 0, refused: [], reason: "not an event output" };
800
+ const verdict = this.#admit(node, item);
801
+ if (!verdict.accepted) return verdict;
802
+ feed.queue.push(item);
803
+ if (held) {
804
+ // Held by the transport: it waits, in order, at most as many as its readers' largest queue limit.
805
+ feed.held = (feed.held ?? 0) + 1;
806
+ const limit = this.#readersLimit(node);
807
+ if (feed.held > limit) {
808
+ this.#dropOldest(feed, feed.queue.length - feed.held);
809
+ feed.held--;
810
+ feed.dropped++;
811
+ feed.heldDropped = (feed.heldDropped ?? 0) + 1;
812
+ if (feed.heldDropped === 1) this.#warn(id, `more than ${limit} "${splitPort(node).name}" events waited while it was paused (its readers' queue limit): the oldest go`); // once a pause
813
+ }
814
+ c.dispatchEvent(new CustomEvent("events-held", { detail: { id } }));
815
+ return verdict;
816
+ }
817
+ if (feed.queue.length > FEED_LIMIT) {
818
+ this.#dropOldest(feed, 0);
819
+ feed.dropped++;
820
+ this.#warn(id, `more than ${FEED_LIMIT} "${splitPort(node).name}" events were waiting to be delivered: the oldest was dropped (a feedback loop?)`);
821
+ }
822
+ this.#out(id, node, item);
823
+ c.hint(`event ${c.labelOf(node)}`); // the run log's cause (src/model/runlog.js)
824
+ this.#budgeted(id, node);
825
+ return verdict;
826
+ }
827
+
828
+ /** The oldest event of `feed` from index `from` on goes: never a batch marker, or a batch would never close (unless only markers wait). */
829
+ #dropOldest(feed, from) {
830
+ const at = feed.queue.findIndex((item, i) => i >= from && !item.marker);
831
+ feed.queue.splice(at < 0 ? from : at, 1);
832
+ }
833
+
834
+ /** Ask for a run of event node `node` (pane `id`'s) under the runaway budget: now, or at a later frame. */
835
+ #budgeted(id, node) {
836
+ const c = this.canvas;
837
+ const wait = c.takeBudget(id, "event");
838
+ if (!wait) c.flow.run(node);
839
+ else wait.then(() => !c.disposed && c.flow.has(node) && c.flow.run(node));
840
+ }
841
+
842
+ /** An event goes (past the transport): a repeater instance's also leave through its outlet. */
843
+ #out(id, node, item) {
844
+ if (!this.outlet || !item) return; // a batch marker goes out too: the repeater namespaces it by instance
845
+ try {
846
+ this.outlet.out(id, splitPort(node).name, item);
847
+ } catch (error) {
848
+ this.#warn(id, `its event couldn't reach the repeater: ${error?.message ?? error}`);
849
+ }
850
+ }
851
+
852
+ /** When an event a pane's code sent reached this canvas: the Worker stamps real time, so on a canvas with its own clock (a virtual-time run) it is the canvas's, the clock the run log and the queue figures use. */
853
+ #arrival(at) {
854
+ const c = this.canvas;
855
+ return c.root.clockOption ? new Date(c.clock.now()).toISOString() : at;
856
+ }
857
+
858
+ /**
859
+ * An event from inside, out of pane `id`'s event output `name` (a repeater's
860
+ * item events): queued in order, each one (never coalesced), through
861
+ * this pane's budget; never held (it passed the transport where it was made).
862
+ * `store({ key, at })` keeps it in the Worker and resolves to its result; it
863
+ * is called now, so the Worker gets them in order. `bytes`: its approximate size, for the readers' byte
864
+ * budgets. Returns `#enqueue`'s answer: `{ accepted, readers, refused: [{ pane, kind, reason }] }`.
865
+ */
866
+ relay(id, name, store, { source, bytes = 0, batch } = {}) {
867
+ const c = this.canvas;
868
+ const node = portId(id, name);
869
+ if (c.disposed || !c.attached.has(id) || !this.feeds.has(node) || !c.trusted.value) return { accepted: false, readers: 0, refused: [] };
870
+ const key = `${node}@r${++this.seq}`;
871
+ const at = new Date(c.clock.now()).toISOString();
872
+ const pending = Promise.resolve(store({ key, at }));
873
+ pending.catch(() => {}); // a failure is the node's when it is delivered
874
+ return this.#enqueue(id, node, { key, pending, at, source: source ?? (c.panes.get(id)?.name || id), bytes, ...(batch === undefined ? {} : { batch }) }); // `bytes`: its size as the caller knows it (the Worker holds the payload)
875
+ }
876
+
877
+ /** Deliver one event that waited in `node`'s feed for the transport (through the budget, as any other); `item` is it. */
878
+ #deliverHeld(id, node, item) {
879
+ const c = this.canvas;
880
+ this.#out(id, node, item);
881
+ c.hint(`event ${c.labelOf(node)}`);
882
+ this.#budgeted(id, node);
883
+ }
884
+
885
+ /** The transport played: events that waited for panes no longer held (`free(id)`) go, in order. */
886
+ release(free = () => true) {
887
+ this.credit.clear();
888
+ for (const [node, feed] of this.feeds) {
889
+ if (!feed.held) continue;
890
+ const { id } = splitPort(node);
891
+ if (!free(id)) continue;
892
+ const n = feed.held;
893
+ const items = feed.queue.slice(feed.queue.length - n); // the held ones are the queue's last
894
+ feed.held = 0;
895
+ feed.heldDropped = 0;
896
+ for (let i = 0; i < n; i++) this.#deliverHeld(id, node, items[i]);
897
+ }
898
+ this.canvas.channels?.release(free); // channel sends that waited
899
+ }
900
+
901
+ /** A transport step: one waiting event from each held pane (`wanted(id)`). Returns the panes stepped. */
902
+ step(wanted = () => true) {
903
+ this.credit.clear();
904
+ const out = [];
905
+ for (const [node, feed] of this.feeds) {
906
+ if (!feed.held) continue;
907
+ const { id } = splitPort(node);
908
+ if (!wanted(id) || out.includes(id)) continue;
909
+ const item = feed.queue[feed.queue.length - feed.held]; // the oldest held one
910
+ feed.held--;
911
+ this.#deliverHeld(id, node, item);
912
+ out.push(id);
913
+ }
914
+ out.push(...(this.canvas.channels?.step(wanted, out) ?? [])); // or one channel send
915
+ // An animation (a live run that awaits frame()) with nothing waiting: this step moves it one frame, and
916
+ // the events that frame sends arrive after this step; they go at once, with the frame's value, not a step later.
917
+ for (const [id, handle] of this.canvas.liveWatches ?? []) if (handle?.animated && wanted(id) && !out.includes(id)) this.credit.add(id);
918
+ return out;
919
+ }
920
+
921
+ /** How many of pane `id`'s events wait for the transport. */
922
+ heldOf(id) {
923
+ let n = 0;
924
+ for (const [node, feed] of this.feeds) if (feed.held && splitPort(node).id === id) n += feed.held;
925
+ return n + (this.canvas.channels?.heldOf(id) ?? 0);
926
+ }
927
+
928
+ /** The runaway guard's word on pane `id` (Canvas#runawayOver): in its log, again once its run settles, and to listeners as `kind`. */
929
+ warnPane(id, text, kind) {
930
+ this.#warn(id, text, kind);
931
+ }
932
+
933
+ /** Warn in pane `id`'s log (now, and again once its current run settles: a run starts with an empty log) and to listeners. */
934
+ #warn(id, text, kind = "event-dropped") {
935
+ const c = this.canvas;
936
+ this.#log(id, text);
937
+ this.notes.set(id, text);
938
+ c.dispatchEvent(new CustomEvent(kind, { detail: { id, text } }));
939
+ }
940
+
941
+ #log(id, text) {
942
+ const logs = this.canvas.logsOf(id);
943
+ if (!logs.value.some((l) => l.text === text)) logs.value = [...logs.value, { level: "warn", text }].slice(-50);
944
+ }
945
+
946
+ /** Every state change (Canvas's onChange): a node that skipped has nothing to repeat; a reader that dropped events says so. */
947
+ observe(id, state) {
948
+ if (state.status !== "running" && this.canvas.panes.has(id) && !this.canvas.flow.queues?.(id)) this.settledAs.set(id, state.status); // forMarkerOnly: UNCHANGED only holds after a done
949
+ if (this.notes.has(id) && state.status !== "running" && !state.queued) {
950
+ this.#log(id, this.notes.get(id));
951
+ // A loop the runaway guard slows reruns the pane every frame: its word stays on the pane while it lasts.
952
+ if (!this.canvas.root?.runawayGuard?.loopOf(this.canvas.runawayKey(id))) this.notes.delete(id);
953
+ }
954
+ if (this.discards.size && state.status !== "running") this.#flushDiscards(); // a reader through with its event: the removed ones go
955
+ if (state.status === "error" && this.canvas.panes.has(id) && this.canvas.attached.has(id)) this.#closeBatches(id, "error", `its source failed${state.error?.message ? `: ${state.error.message}` : ""}`);
956
+ if (state.status === "skipped" || state.status === "error") {
957
+ const w = this.wires.get(id);
958
+ if (w) w.had = false;
959
+ const feed = this.feeds.get(id);
960
+ if (feed) feed.had = false;
961
+ }
962
+ if (state.queued === 0 && state.status !== "running" && this.books.get(id)?.count) this.#reconcile(id);
963
+ if (state.queued !== undefined && ["done", "skipped", "error"].includes(state.status)) this.last.set(id, { status: state.status, reason: state.skip?.reason === undefined ? undefined : String(state.skip.reason) });
964
+ if (state.dropped !== undefined && this.canvas.panes.has(id)) {
965
+ const seen = this.droppedSeen.get(id) ?? 0;
966
+ if (state.dropped > seen) {
967
+ this.droppedSeen.set(id, state.dropped);
968
+ const pane = this.canvas.panes.get(id);
969
+ const n = state.dropped - seen;
970
+ this.#warn(id, `${n} event${n === 1 ? "" : "s"} dropped: more than ${queueLimitOf(pane)} were waiting (its queue limit), so the oldest went`);
971
+ } else if (state.dropped < seen) this.droppedSeen.set(id, state.dropped);
972
+ }
973
+ }
974
+
975
+ /** Is an event waiting to be delivered, or a wire's output to settle (or a channel send or state change, the next frame)? */
976
+ get pending() {
977
+ for (const f of this.feeds.values()) if (f.queue.length > (f.held ?? 0)) return true; // events held by the transport wait for play
978
+ for (const w of this.wires.values()) if (w.queue.length) return true;
979
+ if (this.canvas.channels?.pacing?.size || this.canvas.stateDeferred?.size) return true; // channel sends and state changes waiting for the next frame
980
+ return false;
981
+ }
982
+
983
+ /** …or a value held by a debounce or throttle (headless runs wait for those too). */
984
+ get busy() {
985
+ if (this.pending) return true;
986
+ for (const w of this.wires.values()) if (w.pipeline.busy) return true;
987
+ return false;
988
+ }
989
+
990
+ /** A repeater instance is parked: what waited in its feeds goes (a parked instance sends nothing). */
991
+ dropQueued() {
992
+ for (const f of this.feeds.values()) Object.assign(f, { queue: [], held: 0, heldDropped: 0 });
993
+ for (const book of this.books.values()) book.clear(this.canvas.clock.now(), { why: "went when its instance was kept for later", mark: false });
994
+ this.canvas.channels?.clear(); // and its channel sends
995
+ }
996
+
997
+ /** The sandbox restarted (every value is gone): forget what waited, start the wires' operators again. */
998
+ reset() {
999
+ for (const f of this.feeds.values()) Object.assign(f, { queue: [], had: false, held: 0 });
1000
+ for (const book of this.books.values()) book.clear(this.canvas.clock.now(), { why: "went when the sandbox restarted", mark: false }); // its totals stay: only what waited is gone
1001
+ this.sizes.clear();
1002
+ this.discards.clear(); // everything in the Worker is gone
1003
+ this.canvas.channels?.clear(); // channel sends waiting: their payloads were in the sandbox
1004
+ for (const w of this.wires.values()) {
1005
+ const open = w.pipeline.open.length;
1006
+ if (open) this.#warn(w.target, `${open} open batch${open === 1 ? " was" : "es were"} lost when the sandbox restarted (a restart is not the end of a stream, so nothing was flushed)`);
1007
+ w.pipeline.dispose();
1008
+ Object.assign(w, { queue: [], had: false, lastFed: 0, error: undefined, batchBytes: new Map() });
1009
+ w.pipeline = this.#pipeline(w);
1010
+ }
1011
+ this.bindings.clear();
1012
+ this.handled.clear(); // versions start again after a reset
1013
+ }
1014
+
1015
+ /**
1016
+ * Wire `node`'s last value was put back after a restart (its operators
1017
+ * keep nothing between values): it has a value, and what its source has now
1018
+ * already went through it.
1019
+ */
1020
+ restored(node) {
1021
+ const w = this.wires.get(node);
1022
+ if (!w) return;
1023
+ w.had = true;
1024
+ w.lastFed = this.canvas.flow.get(w.dep)?.version ?? w.lastFed;
1025
+ }
1026
+
1027
+ /** The canvas closed. */
1028
+ dispose() {
1029
+ this.unsync?.();
1030
+ this.books.clear();
1031
+ this.sizes.clear();
1032
+ this.discards.clear();
1033
+ for (const w of this.wires.values()) w.pipeline.dispose();
1034
+ this.wires.clear();
1035
+ this.feeds.clear();
1036
+ this.byTarget.clear();
1037
+ this.bindings.clear();
1038
+ }
1039
+
1040
+ // ── queues (src/model/queue-book.js) ───────────────────────────────
1041
+
1042
+ /** Pane `id`'s queue settings: { items, bytes (or null), expireMs (or null), policy }. */
1043
+ queueSettings(id) {
1044
+ const pane = this.canvas.panes.get(id);
1045
+ return { items: queueLimitOf(pane), bytes: queueBytesOf(pane), expireMs: queueExpireOf(pane), policy: queuePolicyOf(pane) };
1046
+ }
1047
+
1048
+ #bookOf(id) {
1049
+ let book = this.books.get(id);
1050
+ if (!book) this.books.set(id, (book = new QueueBook()));
1051
+ return book;
1052
+ }
1053
+
1054
+ /** The panes that read event node `node` themselves (an event wire's reader is asked when the wire's operators let an event out). */
1055
+ #readersOf(node) {
1056
+ const c = this.canvas;
1057
+ const out = [];
1058
+ for (const d of c.flow.dependents(node)) if (c.panes.has(d) && c.attached.has(d) && c.flow.queues?.(d)) out.push(d);
1059
+ return out;
1060
+ }
1061
+
1062
+ /** How big event `item` is, approximately (the Worker measured the ones its panes sent). */
1063
+ #sizeOf(item) {
1064
+ if (typeof item.bytes === "number") return item.bytes;
1065
+ if (item.payload !== undefined) return approxBytes(item.payload);
1066
+ return 0;
1067
+ }
1068
+
1069
+ #remember(key, bytes) {
1070
+ this.sizes.set(key, bytes);
1071
+ if (this.sizes.size > 4000) this.sizes.delete(this.sizes.keys().next().value);
1072
+ }
1073
+
1074
+ /**
1075
+ * Ask the queues of the panes that read event output `node` to take `item`. An event nobody reads is
1076
+ * accepted (nothing holds it). Otherwise it is accepted when at least one reader's queue takes it, and
1077
+ * a reader that refuses it (its policy, or an event bigger than its byte budget) skips it when it comes.
1078
+ */
1079
+ #admit(node, item) {
1080
+ const c = this.canvas;
1081
+ const readers = this.#readersOf(node);
1082
+ if (item.marker) {
1083
+ item.bytes = 0; // a batch marker is no event: it takes no place in a queue and is never refused
1084
+ return { accepted: true, readers: readers.length, refused: [] };
1085
+ }
1086
+ const verdict = { accepted: true, readers: readers.length, refused: [] };
1087
+ const bytes = this.#sizeOf(item);
1088
+ item.bytes = bytes;
1089
+ if (item.key !== undefined) this.#remember(item.key, bytes);
1090
+ if (!readers.length) return verdict;
1091
+ const now = c.clock.now();
1092
+ let took = 0;
1093
+ const refusals = [];
1094
+ for (const reader of readers) {
1095
+ const book = this.#bookOf(reader);
1096
+ const s = this.queueSettings(reader);
1097
+ this.#sweep(reader, book, s, now);
1098
+ const entry = { dep: node, key: item.key, bytes, at: now };
1099
+ const result = book.admit(entry, s, now);
1100
+ if (result.ok) {
1101
+ took++;
1102
+ if (result.dropped.length) this.#said(reader, "dropped", s);
1103
+ } else {
1104
+ this.#said(reader, result.kind === "oversize" ? "oversize" : s.policy === "reject" ? "rejected" : "dropped", s);
1105
+ refusals.push({ reader, entry });
1106
+ verdict.refused.push({ pane: c.panes.get(reader)?.name || reader, kind: result.kind === "oversize" ? "oversize" : s.policy === "reject" ? "rejected" : "dropped", reason: result.reason });
1107
+ }
1108
+ }
1109
+ if (!took) {
1110
+ for (const { reader, entry } of refusals) this.books.get(reader)?.unvoid(entry); // it goes nowhere: nothing will arrive to skip
1111
+ verdict.accepted = false;
1112
+ verdict.reason = verdict.refused.map((r) => `${r.pane}: ${r.reason}`).join("; ");
1113
+ }
1114
+ return verdict;
1115
+ }
1116
+
1117
+ /** An event came out of a wire's operators for its pane: the pane's queue takes it, or it goes. */
1118
+ #admitFromWire(w, key, measured) {
1119
+ const c = this.canvas;
1120
+ if (!c.panes.has(w.target)) return true;
1121
+ const book = this.#bookOf(w.target);
1122
+ const s = this.queueSettings(w.target);
1123
+ const now = c.clock.now();
1124
+ this.#sweep(w.target, book, s, now);
1125
+ const result = book.admit({ dep: w.node, key, bytes: measured ?? w.fedBytes ?? 0, at: now, ordered: true }, s, now);
1126
+ if (result.ok) {
1127
+ if (result.dropped.length) this.#said(w.target, "dropped", s);
1128
+ return true;
1129
+ }
1130
+ const kind = result.kind === "oversize" ? "oversize" : s.policy === "reject" ? "rejected" : "dropped";
1131
+ this.#said(w.target, kind, s);
1132
+ this.#tellProducer(w, book, kind, result.reason);
1133
+ return false;
1134
+ }
1135
+
1136
+ /** The pane whose event went into wire `w` hears (once per fill of the reader's queue) that the reader refused what came out of the operators. */
1137
+ #tellProducer(w, book, kind, reason) {
1138
+ const producer = splitPort(w.dep).id;
1139
+ const tag = `producer:${producer}:${kind}`;
1140
+ if (book.said.has(tag) || !this.canvas.panes.has(producer) || producer === w.target) return;
1141
+ book.said.add(tag);
1142
+ const reader = this.canvas.panes.get(w.target)?.name || w.target;
1143
+ this.#log(producer, `an event it sent was ${kind === "oversize" ? "refused" : kind} behind the wire's operators: ${reader}'s queue ${kind === "oversize" ? "can't take it" : kind === "rejected" ? "was full" : "dropped it"}${reason ? ` (${reason})` : ""}`);
1144
+ }
1145
+
1146
+ /** Expire what has waited past the pane's `queueExpireMs`, and say so once. */
1147
+ #sweep(id, book, s, now) {
1148
+ if (book.sweep(now, s.expireMs).length) this.#said(id, "expired", s);
1149
+ }
1150
+
1151
+ /** Reader `id` starts on event `key` from `dep`: it leaves its queue. `{ skip }` when it was lost on the way. */
1152
+ #take(id, dep, key) {
1153
+ const book = this.books.get(id);
1154
+ if (!book) return {};
1155
+ const c = this.canvas;
1156
+ const s = this.queueSettings(id);
1157
+ const now = c.clock.now();
1158
+ this.#sweep(id, book, s, now);
1159
+ const left = book.take(dep, key, now, s.expireMs);
1160
+ if (!book.count) book.said.clear();
1161
+ if (left.expired) {
1162
+ this.#said(id, "expired", s);
1163
+ return { skip: left.expired };
1164
+ }
1165
+ return left.void ? { skip: left.void } : {};
1166
+ }
1167
+
1168
+ /** Pane `id`'s queue settings changed (src/model/canvas.js): a queue that holds more than the new budgets allow loses its oldest events now. */
1169
+ queueSettingsChanged(id) {
1170
+ const book = this.books.get(id);
1171
+ if (!book) return;
1172
+ const s = this.queueSettings(id);
1173
+ const now = this.canvas.clock.now();
1174
+ this.#sweep(id, book, s, now);
1175
+ if (book.trim(s, now)) this.#said(id, "dropped", { ...s, policy: s.policy === "drop-oldest" && !s.bytes ? "drop-oldest" : s.policy });
1176
+ }
1177
+
1178
+ /** Pane `id`'s log and the debug panel hear about a kind of loss once per fill of its queue (the totals count every one). */
1179
+ #said(id, kind, s) {
1180
+ const book = this.books.get(id);
1181
+ if (!book || book.said.has(kind)) return;
1182
+ const words = s.bytes ? `${s.items} events or about ${bytesText(s.bytes)}` : `${s.items} events`;
1183
+ let text;
1184
+ if (kind === "oversize") text = `an event was refused: it is bigger than its queue's byte budget (about ${bytesText(s.bytes ?? 0)})`;
1185
+ else if (kind === "rejected") text = `events were rejected: its queue was full (${words}; policy reject)`;
1186
+ else if (kind === "expired") text = `events expired: they waited longer than ${spanText(s.expireMs ?? 0)} for it (its queue's expiry)`;
1187
+ else if (s.policy === "drop-newest") text = `events were dropped: its queue was full (${words}) and the newest goes (policy drop-newest)`;
1188
+ else if (s.bytes) text = `events were dropped: its queue passed ${words} and the oldest go`;
1189
+ else return; // the count limit with the default policy: the queue limit's own warning says it (observe)
1190
+ book.said.add(kind);
1191
+ this.#warn(id, text);
1192
+ }
1193
+
1194
+ /** Is an event still on its way to reader `id` (in a feed, a node's run, or a wire's operators)? */
1195
+ #enRoute(id) {
1196
+ const c = this.canvas;
1197
+ const pane = c.panes.get(id);
1198
+ const busy = (node, depth = 0) => {
1199
+ const feed = this.feeds.get(node);
1200
+ if (feed?.queue.length) return true;
1201
+ const st = c.flow.get(node);
1202
+ if (st?.status === "running" || (st?.queued ?? 0) > 0) return true;
1203
+ const w = this.wires.get(node);
1204
+ if (w) return w.queue.length > 0 || w.pipeline.busy || (depth < 2 && busy(w.dep, depth + 1));
1205
+ return false;
1206
+ };
1207
+ return (pane?.inputs ?? []).some((input) => this.isEventInput(input) && busy(this.depOf(id, input)));
1208
+ }
1209
+
1210
+ /** Dataflow has nothing waiting for reader `id` but its queue still lists events: whatever they were, they won't come. */
1211
+ #reconcile(id) {
1212
+ if (this.#enRoute(id)) return;
1213
+ this.books.get(id)?.clear(this.canvas.clock.now(), { why: "never arrived", mark: false });
1214
+ }
1215
+
1216
+ /**
1217
+ * What waits for reader `id`, for the inspector, the pane's status and agents (null: it reads no events).
1218
+ * Sizes are approximate JSON sizes. `held`: events waiting on the transport (paused) for its sources.
1219
+ */
1220
+ queueStatus(id) {
1221
+ const c = this.canvas;
1222
+ const pane = c.panes.get(id);
1223
+ if (!pane || !c.attached.has(id) || !pane.inputs?.some((input) => this.isEventInput(input))) return null;
1224
+ const book = this.#bookOf(id);
1225
+ const s = this.queueSettings(id);
1226
+ const now = c.clock.now();
1227
+ this.#sweep(id, book, s, now);
1228
+ let held = 0;
1229
+ for (const input of pane.inputs) if (this.isEventInput(input)) held += this.feeds.get(this.depOf(id, input))?.held ?? 0;
1230
+ const out = { ...book.snapshot(now, s), ...(held ? { held } : {}) };
1231
+ const windows = this.windowsOf(id);
1232
+ if (windows.length) out.windows = windows; // the window operators on its wires: where each window opened and closed, and what it holds now
1233
+ if (pane.type === "wait") out.waits = c.waits?.pendingView?.(id); // its pending instances are another kind of waiting: visible beside its queue, counted apart
1234
+ return out;
1235
+ }
1236
+
1237
+ /** Every reader's queue on this canvas: [{ id, name, ...queueStatus }], those with something to say (waiting, or any loss) unless `all`. */
1238
+ queues({ all = false } = {}) {
1239
+ const out = [];
1240
+ for (const id of this.canvas.attached) {
1241
+ const q = this.queueStatus(id);
1242
+ if (!q) continue;
1243
+ const t = q.totals;
1244
+ if (all || q.count || t.dropped || t.expired || t.rejected || t.oversize) out.push({ id, name: this.canvas.panes.get(id)?.name || id, ...q });
1245
+ }
1246
+ return out;
1247
+ }
1248
+
1249
+ /**
1250
+ * Forget everything waiting for reader `id`, by hand: counted as dropped, said in the diagnostics. Its
1251
+ * metrics stay; events already on their way are skipped when they arrive. Returns how many.
1252
+ */
1253
+ clearQueue(id) {
1254
+ const book = this.books.get(id);
1255
+ if (!book) return 0;
1256
+ book.said.clear();
1257
+ return book.clear(this.canvas.clock.now(), { why: "were cleared by hand" });
1258
+ }
1259
+
1260
+ // ── for the page (wires, the inspector, agents) ─────────────────────────
1261
+
1262
+ /** The node pane `target`'s input `index` is drawn from: its wire's when it carries operators. */
1263
+ wireDep(target, index) {
1264
+ const input = this.canvas.panes.get(target)?.inputs?.[index];
1265
+ return input ? this.depOf(target, input) : undefined;
1266
+ }
1267
+
1268
+ /**
1269
+ * The windows wire `node`'s operators have: `{ now, open, closed }` (src/model/queue-book.js says what they hold), or null when
1270
+ * it has no window operator.
1271
+ */
1272
+ windowStatus(node) {
1273
+ const w = this.wires.get(node);
1274
+ if (!w?.pipeline.stages.some((st) => st.kind === "window")) return null;
1275
+ return { now: w.pipeline.windowClock.now(), ...w.pipeline.windowStatus() };
1276
+ }
1277
+
1278
+ /** The windows of the wires into reader `id`: [{ input, operators, now, open, closed }], those with a window operator. */
1279
+ windowsOf(id) {
1280
+ const out = [];
1281
+ for (const [node, w] of this.wires) {
1282
+ if (w.target !== id) continue;
1283
+ const status = this.windowStatus(node);
1284
+ if (status) out.push({ input: w.name, operators: describeOperators(w.operators), ...status });
1285
+ }
1286
+ return out;
1287
+ }
1288
+
1289
+ /** The finite batches open on wire `node` now: their keys. */
1290
+ openBatches(node) {
1291
+ return this.wires.get(node)?.pipeline.open ?? [];
1292
+ }
1293
+
1294
+ /** Does a time operator on this wire wait now? */
1295
+ waiting(node) {
1296
+ return Boolean(this.wires.get(node)?.pipeline.busy);
1297
+ }
1298
+ }
1299
+
1300
+ /** The batch key of a live run's values on a value wire. */
1301
+ const runBatchKey = (runId) => `run-${runId}`;
1302
+
1303
+ export { stagesOf };