@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,1017 @@
1
+ // A machine pane's run on the page side (docs/design/machine-pane.md): the settings read into a driver (src/machine/drive.js), the provider
2
+ // (the agent's providers, with the recorded one for offline runs), approvals and questions through the agent pane's cards and scripts
3
+ // (src/agent/run.js askPerson), parking in the agent's park store, and the live view the body draws. The pane's value is set once, when
4
+ // a run ends; a stepwise session (Step, Reset) keeps its driver between runs of the pane. Nothing here is reachable from WebMCP's
5
+ // writing tools; the person's controls (step, run, pause, reset, a cell edit, a parked answer) are commands and card buttons.
6
+ import { filesTool } from "./files-tool.js";
7
+ import { shellTool } from "./shell-tool.js";
8
+ import { vmTool } from "./vm-tool.js";
9
+ import { trait } from "../panes/registry.js";
10
+ import { lintMachine } from "./lint.js";
11
+ import { skip } from "@johnhenry/dataflow";
12
+ import { AgentStop } from "../agent/loop.js";
13
+ import { liveOf, askPerson, answerApproval, parkStoreOf, parkKey, approvals, textBody } from "../agent/run.js";
14
+ import { inputRole } from "../agent/ports.js";
15
+ import { callSubgraph, functionTool, subgraphSchema, graphFetches, usesFetch } from "../agent/tools.js";
16
+ import { graphPanes } from "../model/subgraph.js";
17
+ import { beginCall, AGENT_SERVER } from "../gate/gate.js";
18
+ import { callSeams } from "../gate/seams.js";
19
+ import { personsSafety } from "../safety/config.js";
20
+ import { prepareSend, performSend } from "../model/http-send.js";
21
+ import { createProvider } from "../agent/providers.js";
22
+ import { cleanPrice, digest, usd } from "../agent/guards.js";
23
+ import { localTransport } from "../agent/local-transport.js";
24
+ import { cannotReplayInto } from "../agent/fork.js";
25
+ import { compile, machineProblems, orphanedProtections, MAX_ELICIT_MS, stepCapProblem, DEFAULT_MAX_STEPS, POLICIES, makeCell, MAX_DEPTH } from "./tape.js";
26
+ import { createDriver } from "./drive.js";
27
+ import { runValue, DEFAULT_POLICY } from "./engine.js";
28
+ import { makeProposer } from "./propose.js";
29
+ import { watchdogSettings } from "./watchdog.js";
30
+ import { providerIdentity, replayTrace, continueFrom, diffRuns, serializeTrace, inspectTrace, parseTrace, withComments, definitionHash } from "./trace.js";
31
+ import { randomPropose } from "./random.js";
32
+ import { panePropose } from "./pane-provider.js";
33
+ import { otlpText } from "./otel.js";
34
+ import { riskSettings } from "./risk.js";
35
+ import { importLlmtmTrace, looksLikeLlmtmTrace } from "./llmtm-trace.js";
36
+ import { retentionOf } from "../model/runlog.js";
37
+
38
+ export const PARK_FORMAT = "mallory-parked-machine";
39
+ /** The longest trace a pane keeps in its value and live view. */
40
+ export const TRACE_LIMIT = 500;
41
+
42
+ let noticeHandler = null;
43
+ /** The page registers one handler for what a run reports about itself ({ kind: "finished" | "stopped" | "needs", pane }); it never gets a run's content. */
44
+ export const setNoticeHandler = (fn) => {
45
+ noticeHandler = typeof fn === "function" ? fn : null;
46
+ };
47
+ const notice = (kind, canvas, id) => {
48
+ try {
49
+ noticeHandler?.({ kind, pane: String(canvas.panes.get(id)?.name || id) });
50
+ } catch {
51
+ /* a notification must never change a run */
52
+ }
53
+ };
54
+
55
+ let versionHandler = null;
56
+ /**
57
+ * The page registers one handler for the definition a run is about to use (`{ canvas, pane, name, hash, machine, lockedCells }`: the pane's own definition and
58
+ * the content hash its run header will name), so the person's version history (src/ui/run-stores-ui.js) can keep it. It gets nothing a run produced, and what it
59
+ * does is the person's store's business; a failure there never changes a run.
60
+ */
61
+ export const setVersionHandler = (fn) => {
62
+ versionHandler = typeof fn === "function" ? fn : null;
63
+ };
64
+ const noteVersion = (canvas, id, pane, c, protect) => {
65
+ if (!versionHandler) return;
66
+ try {
67
+ void Promise.resolve(versionHandler({ canvas: canvas.root?.id ?? canvas.id, pane: id, name: String(pane?.name || id), hash: definitionHash(c), machine: pane.machine, lockedCells: [...protect] })).catch(() => {});
68
+ } catch {
69
+ /* a history must never change a run */
70
+ }
71
+ };
72
+
73
+ const sessions = new WeakMap(); // canvas -> Map(pane id -> session)
74
+ const intents = new WeakMap(); // canvas -> Map(pane id -> "step" | "run" | "reset" | "resume")
75
+ const answers = new WeakMap(); // canvas -> Map(pane id -> the person's answer to a parked request)
76
+ const forks = new WeakMap(); // canvas -> Map(pane id -> a fork or resume the person asked for, already checked: { k, c, resume })
77
+ const served = new WeakMap(); // canvas -> Map(pane id -> the request of `mallory serve --model-endpoint` that this run answers: { inject }), taken by the run
78
+ const history = new WeakMap(); // canvas -> Map(pane id -> the runs of this page's sessions, newest last: { id, label, c, driver })
79
+ const HISTORY_LIMIT = 40;
80
+ /** The most events a parked run's record keeps; a longer trace is cut at its front and the run header goes with it, so the restored run says so. */
81
+ const PARK_EVENTS_LIMIT = 5000;
82
+ const newRunId = () => `run-${Date.now().toString(36)}-${(globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2)).slice(0, 8)}`;
83
+ const perCanvas = (weak, canvas) => weak.get(canvas) ?? (weak.set(canvas, new Map()), weak.get(canvas));
84
+ let seq = 0;
85
+
86
+ /** The live view of machine pane `id`: `{ status, value?, events, pending, usage, ... }` (a signal; the body draws it). */
87
+ export const machineLive = (canvas, id) => liveOf(canvas, id);
88
+ export const sessionOf = (canvas, id) => sessions.get(canvas)?.get(id);
89
+
90
+ /** Ask for something of the pane on its next run: "step", "run" or "reset" (the person's controls). */
91
+ export function requestMachine(canvas, id, intent) {
92
+ if (!["step", "run", "reset"].includes(intent)) throw new Error(`unknown machine control "${intent}"`);
93
+ perCanvas(intents, canvas).set(id, intent);
94
+ canvas.run(id);
95
+ }
96
+
97
+ /** The settings of the pane as the driver reads them, in bounds. */
98
+ /** How the proposer asks the model: the pane's `llm.schema` "flat" offers the propose tool without nested objects (hosted backends that reject them); anything else is the nested one. */
99
+ export const proposerOptions = (llm) => ({ onText: undefined, schema: llm?.schema });
100
+
101
+ export function settingsOf(pane) {
102
+ const mode = (v, fallback) => (POLICIES.includes(v) ? v : fallback);
103
+ const r = pane.rejections && typeof pane.rejections === "object" ? pane.rejections : {};
104
+ const num = (v, fallback, lo, hi) => (Number.isFinite(Number(v)) && v !== null && v !== "" ? Math.min(hi, Math.max(lo, Number(v))) : fallback);
105
+ return {
106
+ kind: pane.llm?.provider ?? "recorded",
107
+ limits: {
108
+ maxSteps: pane.capSteps === undefined ? DEFAULT_MAX_STEPS : pane.capSteps,
109
+ maxCostUsd: Number(pane.capUsd) > 0 ? Number(pane.capUsd) : 0,
110
+ maxDurationMs: Number(pane.capMs) > 0 ? Number(pane.capMs) : 0,
111
+ price: cleanPrice(pane.price),
112
+ model: typeof pane.llm?.model === "string" && pane.llm.model ? pane.llm.model : undefined,
113
+ routing: pane.llm?.routing,
114
+ watchdog: watchdogSettings(pane.watchdog),
115
+ },
116
+ policy: { invalid: mode(r.invalid, DEFAULT_POLICY.invalid), apply: mode(r.apply, DEFAULT_POLICY.apply), retries: Math.floor(num(r.retries, DEFAULT_POLICY.retries, 0, 10)), backoffMs: Math.round(num(r.backoffMs, 0, 0, 60_000)), jitter: num(r.jitter, 0.25, 0, 1) },
117
+ gate: pane.needsApproval && typeof pane.needsApproval === "object" && !Array.isArray(pane.needsApproval) ? pane.needsApproval : {},
118
+ noApproval: Array.isArray(pane.noApproval) ? pane.noApproval.map(String) : [],
119
+ canAsk: pane.canAsk === true,
120
+ risk: riskSettings(pane.riskGate),
121
+ inject: pane.inject && typeof pane.inject === "object" && !Array.isArray(pane.inject) && Object.keys(pane.inject).length ? Object.fromEntries(Object.entries(pane.inject).map(([k, v]) => [k, String(v)])) : undefined,
122
+ protect: Array.isArray(pane.lockedCells) ? pane.lockedCells.map(String) : [],
123
+ restart: pane.restart,
124
+ parkMs: Math.max(0, Math.floor(Number(pane.parkMs) || 0)),
125
+ askTimeoutMs: Math.max(0, Math.floor(Number(pane.askTimeoutMs) || 0)),
126
+ approvalTimeoutMs: Math.max(0, Math.floor(Number(pane.approvalTimeoutMs) || 0)),
127
+ };
128
+ }
129
+
130
+ /** A child's limits inside its parent's remainder (`left`: { maxSteps, maxCostUsd, maxDurationMs }, 0 for none): the smaller of each cap that is set. */
131
+ function nestLimits(own, left) {
132
+ if (!left) return own;
133
+ const least = (a, b) => (a > 0 && b > 0 ? Math.min(a, b) : a > 0 ? a : b > 0 ? b : 0);
134
+ return { ...own, maxSteps: Math.max(1, Math.min(Number.isFinite(own.maxSteps) ? own.maxSteps : DEFAULT_MAX_STEPS, left.maxSteps)), maxCostUsd: least(own.maxCostUsd, left.maxCostUsd), maxDurationMs: least(own.maxDurationMs, left.maxDurationMs) };
135
+ }
136
+
137
+ /** A digest of what decides what a run does: a session whose pane changed under it is stale and starts again. */
138
+ export const fingerprintOf = (pane) => digest(JSON.stringify(["machine", "llm", "replies", "lockedCells", "needsApproval", "noApproval", "rejections", "canAsk", "riskGate", "askTimeoutMs", "approvalTimeoutMs", "capSteps", "capUsd", "capMs", "price", "watchdog", "restart", "parkMs", "inject"].map((k) => pane[k] ?? null)));
139
+
140
+ /** The content hash the pane's definition would name in a run header, or "" when the pane can't run (a definition with problems has none). */
141
+ export function definitionHashOf(pane) {
142
+ if (!pane?.machine || paneProblems(pane).length) return "";
143
+ try {
144
+ return definitionHash(compile(pane.machine, { protect: settingsOf(pane).protect }));
145
+ } catch {
146
+ return "";
147
+ }
148
+ }
149
+
150
+ /** The pane's problems before it can run: the definition, the step cap, and any other setting that cannot be read. [] when it can. */
151
+ export function paneProblems(pane) {
152
+ const out = machineProblems(pane.machine);
153
+ const cap = stepCapProblem(pane.capSteps === undefined ? DEFAULT_MAX_STEPS : pane.capSteps);
154
+ if (cap) out.push(cap);
155
+ if (pane.inject !== undefined && !(pane.inject && typeof pane.inject === "object" && !Array.isArray(pane.inject) && Object.values(pane.inject).every((v) => typeof v === "string"))) out.push("inject: { cellId: text }");
156
+ else for (const id of Object.keys(pane.inject ?? {})) {
157
+ if (!(pane.machine?.tape?.cells ?? []).some((c) => c?.id === id)) out.push(`inject: there is no cell ${JSON.stringify(id)} on the tape`);
158
+ else if (Array.isArray(pane.lockedCells) && pane.lockedCells.includes(id)) out.push(`inject: cell ${JSON.stringify(id)} is locked, so nothing is injected into it (remove it from inject, or unlock it)`);
159
+ }
160
+ // A lock or a gate that names nothing in the definition is a problem, not a quiet no-op (S2): the machine does not run until the person fixes it.
161
+ out.push(...orphanedProtections(pane.machine, pane).map((p) => `${p}; the machine does not run until you fix it`));
162
+ const wired = new Set((pane.inputs ?? []).map((i) => i?.name));
163
+ for (const [name, st] of Object.entries(pane.machine?.states ?? {})) {
164
+ if (st?.tool && typeof st.tool.name === "string" && !wired.has(st.tool.name)) out.push(`states.${name}.tool.name: no pane named "${st.tool.name}" is wired into this machine (add it as an input)`);
165
+ if (st?.submachine && typeof st.submachine.machine === "string" && !wired.has(st.submachine.machine)) out.push(`states.${name}.submachine.machine: no machine pane named "${st.submachine.machine}" is wired into this machine (add it as an input)`);
166
+ }
167
+ (pane.machine?.tape?.cells ?? []).forEach((cell, i) => {
168
+ if (typeof cell?.meta?.ref === "string" && !wired.has(cell.meta.ref)) out.push(`tape.cells[${i}].meta.ref: no pane named "${cell.meta.ref}" is wired into this machine (add it as an input)`);
169
+ });
170
+ // `modelEndpoint` (mallory serve --model-endpoint): the person's opt-in to be served as a model; the conversation is written into `cell`.
171
+ if (pane.modelEndpoint !== undefined) {
172
+ const me = pane.modelEndpoint;
173
+ const cells = pane.machine?.tape?.cells ?? [];
174
+ if (!(me && typeof me === "object" && !Array.isArray(me) && Object.keys(me).every((k) => k === "cell"))) out.push("modelEndpoint: { cell?: the id of the cell the conversation is written into }");
175
+ else if (me.cell !== undefined && !cells.some((c) => c?.id === me.cell)) out.push(`modelEndpoint.cell: there is no cell ${JSON.stringify(me.cell)} on the tape`);
176
+ else if (Array.isArray(pane.lockedCells) && pane.lockedCells.includes(me.cell ?? cells[0]?.id)) out.push(`modelEndpoint.cell: cell ${JSON.stringify(me.cell ?? cells[0]?.id)} is locked, so no conversation can be written into it`);
177
+ }
178
+ if (pane.llm?.provider === "pane") {
179
+ if (typeof pane.llm.pane !== "string" || !pane.llm.pane) out.push("llm.pane: the provider \"pane\" needs the name of a pane wired into this machine");
180
+ else if (!wired.has(pane.llm.pane)) out.push(`llm.pane: no pane named "${pane.llm.pane}" is wired into this machine (add it as an input)`);
181
+ }
182
+ if (pane.riskGate !== undefined && !(pane.riskGate && typeof pane.riskGate === "object" && !Array.isArray(pane.riskGate))) out.push("riskGate: { autoLow?, high?: delegate | block | park, mediumChars?, highChars?, words? }");
183
+ for (const key of ["askTimeoutMs", "approvalTimeoutMs"]) if (pane[key] !== undefined && !(Number.isInteger(pane[key]) && pane[key] >= 0 && pane[key] <= MAX_ELICIT_MS)) out.push(`${key}: a whole number of milliseconds from 0 (never) to ${MAX_ELICIT_MS}`);
184
+ if (pane.noApproval !== undefined && !(Array.isArray(pane.noApproval) && pane.noApproval.every((x) => typeof x === "string"))) out.push("noApproval: a list of state names");
185
+ if (pane.lockedCells !== undefined && !(Array.isArray(pane.lockedCells) && pane.lockedCells.every((x) => typeof x === "string"))) out.push("lockedCells: a list of cell ids");
186
+ return out;
187
+ }
188
+
189
+ const cardArgs = (req) => {
190
+ const a = req.proposal.action;
191
+ return { state: req.state, action: a.kind, ...(a.tool !== undefined ? { tool: a.tool } : {}), ...(a.text !== undefined ? { text: a.text } : {}), ...(a.reason !== undefined ? { reason: a.reason } : {}), move: req.proposal.move, nextState: req.proposal.nextState, ...(req.problem ? { problem: req.problem } : {}) };
192
+ };
193
+
194
+ /** A trace for the value: the events as the driver recorded them, the newest TRACE_LIMIT (with the run header first, so a long run still says what it was). */
195
+ export const traceOf = (events) => (events.length > TRACE_LIMIT ? [events[0], ...events.slice(-(TRACE_LIMIT - 1))] : events); // a cut trace keeps its header: it says what ran
196
+
197
+ function eventLine(e) {
198
+ switch (e.type) {
199
+ case "step_committed":
200
+ return `step ${e.step}: ${e.proposal.action.kind} → ${e.after.state}, head ${e.after.head}${e.routedBy ? ` (routed by ${e.routedBy})` : ""}`;
201
+ case "proposal_rejected":
202
+ return `refused (${e.tier}): ${e.reason}`;
203
+ case "halt":
204
+ return `halt (${e.kind}): ${e.reason}`;
205
+ default:
206
+ return e.text ?? e.type;
207
+ }
208
+ }
209
+ export { eventLine };
210
+
211
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
212
+
213
+ /** A wired `http` pane (send mode) as a tool: `{ url?, method?, headers?, query?, body? }` laid over the pane's own request. */
214
+ function httpTool(canvas, id, runtime, source, name) {
215
+ const label = String(source.name || source.id);
216
+ const names = ["url", "method", "headers", "query", "body"];
217
+ const prepare = (args) => prepareSend(source.http, args ?? {}, Object.keys(args ?? {}).filter((k) => names.includes(k)));
218
+ return {
219
+ name,
220
+ kind: "http",
221
+ server: label,
222
+ gateTool: "send",
223
+ ask: false,
224
+ async inspect(args) {
225
+ if (source.http?.send?.via === "companion") return { error: "a tool state does not send through the companion: use the pane's own send" };
226
+ try {
227
+ const { request } = await prepare(args);
228
+ const unsafe = !SAFE_METHODS.has(String(request.method).toUpperCase());
229
+ return { destructive: unsafe, ask: unsafe };
230
+ } catch (error) {
231
+ return { error: `http: ${error.message}` };
232
+ }
233
+ },
234
+ async call(args, { signal } = {}) {
235
+ const prepared = await prepare(args);
236
+ const value = await performSend({ prepared, send: (url, init, context) => runtime.request(url, init, context), pane: canvas.runawayKey(id), signal });
237
+ if (value.superseded) throw Object.assign(new Error("superseded by a newer run"), { name: "AbortError" });
238
+ if (value.error) throw Object.assign(new Error(`${value.error.kind}: ${value.error.message}`), { code: value.error.kind, ...(value.error.kind === "refused" || value.error.kind === "secret" ? { gate: `network-${value.error.kind}` } : {}) });
239
+ if (!value.ok) throw Object.assign(new Error(`HTTP ${value.status}${value.statusText ? ` ${value.statusText}` : ""}`), { code: "http-status" });
240
+ return value.body?.json !== undefined ? value.body.json : (value.body?.text ?? "");
241
+ },
242
+ };
243
+ }
244
+
245
+ /** A tool of a wired MCP server pane, or null when the input is not one. The hub gates the call; a call that names no tool is a problem. */
246
+ async function mcpTool(canvas, id, source, name, callName) {
247
+ if (!source) return null;
248
+ const { findServer, hubOf } = await import("../mcp/hub.js");
249
+ let found;
250
+ try {
251
+ found = findServer(canvas, source.name || source.id);
252
+ } catch {
253
+ return null;
254
+ }
255
+ if (found?.id !== source.id) return null;
256
+ if (!callName) return { name, problem: `${name} is an MCP server pane: name the tool to call (tool.call)` };
257
+ const hub = hubOf(found.canvas);
258
+ return { name, kind: "mcp", selfGated: true, call: (args, ctx) => hub.call(found.id, callName, args, { origin: { canvas, paneId: id }, signal: ctx?.signal }) };
259
+ }
260
+
261
+ /**
262
+ * The tool a tool state names: a subgraph pane wired into the machine (called with arguments, in its own namespace) or an eval pane that returns
263
+ * a function. The same two the agent pane calls (src/agent/tools.js); nothing else is reachable from a machine, and only through its inputs.
264
+ */
265
+ async function wiredTool(canvas, id, runId, runtime, pane, name, callName) {
266
+ const input = (pane.inputs ?? []).find((i) => i?.name === name);
267
+ if (!input) return null;
268
+ const role = inputRole(canvas, input);
269
+ const source = canvas.panes.get(input.source);
270
+ // An `http` pane in send mode: its request overlaid with the call's arguments, sent through the network policy like the pane's own send. Non-2xx fails.
271
+ if (source?.http?.mode === "send") return httpTool(canvas, id, runtime, source, name);
272
+ // A `files` pane wired in: read, write, list, mkdir or remove in THIS canvas's own folder, through the page broker and the person's grant; every change asks first (src/machine/files-tool.js).
273
+ // A `shell` pane wired in: `run` a command line in a fresh clsh shell in the sandbox, over this canvas's own folder through the person's grant; a line that writes asks first (src/machine/shell-tool.js).
274
+ // A `vm` pane wired in: `send` a line to a running guest (always asks), `read` its console, `list` its shared folder, only when the person set `vm.machine` (src/machine/vm-tool.js).
275
+ if (source && trait(source.type, "machineVm") === true) return vmTool({ name, call: callName, pane: source, hub: canvas.vmHub ?? (await import("../vm/hub.js")).vmHubOf(canvas) });
276
+ if (source && trait(source.type, "machineTool") === true) return trait(source.type, "machineShell") === true ? shellTool({ name, call: callName, pane: source, runtime, canvas }) : filesTool({ name, call: callName, pane: source, broker: canvas.root?.filesBroker });
277
+ // An MCP server pane wired in: one of its tools (`tool.call`), through its hub, which gates every call.
278
+ const mcp = await mcpTool(canvas, id, source, name, callName);
279
+ if (mcp) return mcp;
280
+ if (role === "tool" && source) {
281
+ return { name, kind: "subgraph", schema: subgraphSchema(source), ask: graphFetches(graphPanes(source)), call: (args, ctx) => callSubgraph(canvas, id, input.source, args, ctx) };
282
+ }
283
+ if (role !== "value") return null;
284
+ const prep = await runtime.agent({ id, runId, op: "prepare", sources: [canvas.sourceKey(id, input)], names: [name], payload: { system: "", prompt: "", label: pane.name || id } });
285
+ const f = (prep?.functions ?? []).find((x) => x.name === name);
286
+ if (!f) return null;
287
+ const home = canvas.homeOf(input.source);
288
+ const code = home && canvas.attached.has(home.node) && home.node === input.source ? canvas.panes.get(input.source)?.code : undefined;
289
+ const decl = functionTool({ ...f, code, description: f.description || input.description });
290
+ return {
291
+ name,
292
+ kind: "function",
293
+ schema: decl.schema,
294
+ ask: usesFetch(code) || usesFetch(f.source),
295
+ async call(args) {
296
+ const out = await runtime.agent({ id, runId, op: "call", sources: [home.key], payload: { args, positional: decl.positional } });
297
+ if (out?.error !== undefined) throw Object.assign(new Error(out.error), typeof out.code === "string" ? { code: out.code } : {});
298
+ return out?.value;
299
+ },
300
+ };
301
+ }
302
+
303
+ /** Build the session for a pane: a compiled program, a provider, a driver. Throws an Error naming the problems. */
304
+ async function createSession(canvas, id, { runId, signal, runtime, from, continuation, nextProposal, replyOffset = 0, run: traceRun, depth = 0, quiet = false, budget = null, inject: requested, grant = null }) {
305
+ const pane = canvas.panes.get(id);
306
+ const problems = paneProblems(pane);
307
+ if (problems.length) throw new Error(`The machine can't run: ${problems.slice(0, 4).join("; ")}${problems.length > 4 ? `; and ${problems.length - 4} more` : ""}.`);
308
+ const s = settingsOf(pane);
309
+ const c = compile(pane.machine, { protect: s.protect });
310
+ noteVersion(canvas, id, pane, c, s.protect);
311
+ const live = liveOf(canvas, id);
312
+ const llm = pane.llm ?? {};
313
+ const wantsLocal = s.kind === "local" || (s.kind === "router" && Array.isArray(llm.routing?.chain) && llm.routing.chain.some((m) => m?.provider === "local"));
314
+ const stoppable = (call) => {
315
+ if (!signal) return call;
316
+ const stop = () => void runtime?.agent?.({ id, runId, op: "cancel" })?.catch?.(() => {});
317
+ signal.addEventListener("abort", stop, { once: true });
318
+ return call.finally(() => signal.removeEventListener("abort", stop));
319
+ };
320
+ const providers = new Map();
321
+ const providerFor = (model) => {
322
+ const key = model || llm.model || "";
323
+ if (!providers.has(key)) {
324
+ providers.set(key, createProvider(s.kind, {
325
+ model: key,
326
+ baseUrl: llm.baseUrl,
327
+ keyName: llm.keyName,
328
+ recorded: replyOffset > 0 && Array.isArray(pane.replies) ? pane.replies.slice(replyOffset) : pane.replies, // a fork goes on from the reply its source used next
329
+ router: llm.routing,
330
+ scope: `${canvas.root.id}|${id}`,
331
+ transport: runtime?.agent
332
+ ? {
333
+ http: (request, stream) => stoppable(runtime.agent({ id, runId, op: "http", payload: { ...request, ...(stream ? { stream: true } : {}) }, ...(stream ? { onProgress: stream.onChunk } : {}) })),
334
+ chrome: (op, payload = {}, stream) => stoppable(runtime.agent({ id, runId, op: "chrome", payload: { op, ...payload, ...(stream ? { stream: true } : {}) }, ...(stream ? { onProgress: stream.onChunk } : {}) })),
335
+ ...(wantsLocal ? { local: localTransport({ access: runtime.companion, pane: canvas.runawayKey(id), conversation: `${id}:${runId}`, signal }) } : {}),
336
+ }
337
+ : undefined,
338
+ }));
339
+ }
340
+ return providers.get(key);
341
+ };
342
+ const canPark = s.parkMs > 0 && !cannotReplayInto(s.kind);
343
+ const toDecision = (a) => {
344
+ if (a?.park) return { decision: "park" };
345
+ const choice = typeof a === "string" ? a : a?.choice;
346
+ if (choice === undefined) return { decision: "none", reason: a?.reason };
347
+ if (choice !== "approve" && choice !== "always") return { decision: "deny", ...(a?.reason ? { reason: a.reason } : {}), ...(a?.scripted ? { scripted: true } : {}) };
348
+ const text = typeof a?.text === "string" ? a.text : typeof a?.args?.text === "string" ? a.args.text : undefined;
349
+ return { decision: "approve", ...(text !== undefined ? { text } : {}), ...(a?.scripted ? { scripted: true } : {}) };
350
+ };
351
+ const safety = personsSafety(); // one safety stage for this run: a tainted result is remembered for its later calls (src/gate/seams.js)
352
+ const session = {
353
+ id,
354
+ c,
355
+ pane,
356
+ fingerprint: fingerprintOf(pane),
357
+ stepwise: false,
358
+ pause: false,
359
+ settings: s,
360
+ live,
361
+ problems: [],
362
+ };
363
+ const env = {
364
+ depth,
365
+ propose: s.kind === "random" ? randomPropose({ seed: llm.seed }) : s.kind === "pane" ? panePropose({ name: llm.pane, call: (a) => env.callTool(a) }) : makeProposer(providerFor, proposerOptions(llm)),
366
+ policy: s.policy,
367
+ gate: s.gate,
368
+ noApproval: s.noApproval,
369
+ questionTimeoutMs: s.askTimeoutMs || undefined,
370
+ approvalTimeoutMs: s.approvalTimeoutMs || undefined,
371
+ canAsk: s.canAsk,
372
+ risk: s.risk,
373
+ // A cell that refers to a pane (TAPE-08): only a value pane wired into this machine, read-only, and only when the head is on that cell.
374
+ readRef: async (name) => {
375
+ const input = /^[A-Za-z_]\w*$/.test(String(name)) ? (pane.inputs ?? []).find((i) => i?.name === name) : undefined;
376
+ if (!input) return { error: `no pane named "${name}" is wired into this machine` };
377
+ if (inputRole(canvas, input) !== "value") return { error: `"${name}" is not a value pane` };
378
+ const prep = await runtime.agent({ id, runId, op: "prepare", sources: [canvas.sourceKey(id, input)], names: [name], payload: { system: "", prompt: textBody(`\${${name}}`), label: pane.name || id } });
379
+ return typeof prep?.prompt === "string" ? { text: prep.prompt } : { error: "the pane has no value yet" };
380
+ },
381
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
382
+ // A tool state's call (wave L-I): only a pane wired into this machine, and only through the person's gate. The gate decides first (policy, the inbox, the
383
+ // approvals script); a tool that fetches asks the person too; a refusal has no effect. The engine has already asked for the state's own approval.
384
+ callTool: async ({ tool: name, call, args, signal: stop }) => {
385
+ const tool = await wiredTool(canvas, id, runId, runtime, pane, name, call);
386
+ if (!tool) return { error: `no pane named "${name}" is wired into this machine as a tool${call ? ` (an MCP server pane, for the tool ${call})` : ""}`, refused: "no-such-tool" };
387
+ if (tool.problem) return { error: tool.problem, refused: "unusable" };
388
+ // An MCP pane's hub gates its own calls (the grants, the policy, the inbox, the script), and so does nothing else need to: it throws with `gate` set on a refusal.
389
+ if (tool.selfGated) {
390
+ try {
391
+ return { value: await tool.call(args, { signal: stop }) };
392
+ } catch (error) {
393
+ if (error?.name === "AbortError") throw error;
394
+ return { error: error?.message ?? String(error), ...(error?.gate ? { refused: error.gate } : {}) };
395
+ }
396
+ }
397
+ // A request is looked at before the gate: its method says whether it is a side effect (an unsafe method asks, and the gate sees it as destructive).
398
+ const meta = tool.inspect ? await tool.inspect(args) : null;
399
+ if (meta?.error) return { error: meta.error, refused: "request" };
400
+ if (meta) Object.assign(tool, meta);
401
+ const ticket = await beginCall({ canvasId: canvas.root.id, server: tool.server ?? AGENT_SERVER, tool: tool.gateTool ?? tool.name, destructive: tool.destructive === true, args, signal: stop, interactive: canvas.root.interactive === true, script: canvas.root.approvalScript ?? null, names: [tool.name], origin: { canvas, paneId: id }, ...callSeams(canvas, { paneId: id, paneName: pane.name, safety, verdict: true }) });
402
+ if (!ticket.ok) return { error: ticket.reason, refused: ticket.outcome };
403
+ let given = ticket.args !== undefined && ticket.args !== args ? ticket.args : args;
404
+ if (!ticket.approved && tool.ask) {
405
+ const answer = await askPerson(canvas, id, live, { tool: { name: tool.name, kind: tool.kind, server: tool.server ?? AGENT_SERVER, gateTool: tool.gateTool ?? tool.name }, call: { args: given }, signal: stop, canPark: false });
406
+ const choice = typeof answer === "string" ? answer : answer?.choice;
407
+ if (choice !== "approve" && choice !== "always") {
408
+ const reason = answer?.reason || "The person using mallory denied this tool call.";
409
+ return { error: (await ticket.finish({ error: reason, refused: "denied" })).error ?? reason, refused: "denied" };
410
+ }
411
+ if (answer?.args !== undefined) given = answer.args;
412
+ }
413
+ try {
414
+ const value = await tool.call(given, { signal: stop });
415
+ const out = await ticket.finish({ value });
416
+ return out?.error !== undefined ? { error: out.error } : { value: out?.value ?? value };
417
+ } catch (error) {
418
+ if (error?.name === "AbortError") {
419
+ await ticket.finish({ error: "stopped", stopped: true });
420
+ throw error;
421
+ }
422
+ const out = await ticket.finish({ error: error?.message ?? String(error) });
423
+ return { error: out?.error ?? error?.message ?? String(error), ...(typeof error?.code === "string" ? { code: error.code } : {}), ...(error?.gate ? { refused: error.gate } : {}) }; // a refusal by the network policy has no effect and is not retried
424
+ }
425
+ },
426
+ // A submachine state's child (wave L-I): a machine pane wired into this one, run on a fresh tape with the parent's head text injected, its caps nested
427
+ // inside what is left of the parent's, its approvals asked on its own pane. Its final head cell is the result.
428
+ runChild: async ({ machine: name, into, text, step, budget: left, signal: stop }) => {
429
+ if (depth >= MAX_DEPTH) return { error: `submachines are nested ${depth} deep, the most allowed (${MAX_DEPTH})`, haltKind: "depth", final: true };
430
+ const input = (pane.inputs ?? []).find((i) => i?.name === name);
431
+ const childPane = input ? canvas.panes.get(input.source) : undefined;
432
+ if (!childPane?.machine) return { error: `no machine pane named "${name}" is wired into this machine`, refused: "no-such-machine" };
433
+ if (childPane.id === id) return { error: "a machine cannot be its own submachine", refused: "self" };
434
+ const bad = paneProblems(childPane);
435
+ if (bad.length) return { error: `the child can't run: ${bad.slice(0, 2).join("; ")}`, refused: "child-unsound" };
436
+ if (left && left.maxSteps < 1) return { error: "no steps are left in the parent's cap for the child", final: true };
437
+ const cell = into ?? childPane.machine.tape?.cells?.[childPane.machine.tape.head]?.id;
438
+ // The child's locks are the child's person's: the parent's text is never written into a locked cell (S1).
439
+ if ((childPane.lockedCells ?? []).includes(cell)) return { error: `cell ${JSON.stringify(cell)} of ${name} is locked, so the parent's text is not written into it`, refused: "locked" };
440
+ let child;
441
+ try {
442
+ child = await createSession(canvas, childPane.id, { runId: `${runId}.${step}`, signal: stop, runtime, depth: depth + 1, quiet: true, budget: left, grant, continuation: { events: [], inject: { [cell]: text }, parent: { run: headerRun, at: step, step } } });
443
+ await child.driver.run();
444
+ } catch (error) {
445
+ if (error?.name === "AbortError") throw error;
446
+ return { error: error?.message ?? String(error) };
447
+ }
448
+ const r = child.driver.current;
449
+ const u = child.driver.usage;
450
+ const base = { steps: child.driver.totalSteps, halt: r.haltKind, usage: { cost: u.cost, inputTokens: u.inputTokens, outputTokens: u.outputTokens, modelCalls: u.modelCalls } };
451
+ if (r.haltKind === "terminal" || r.haltKind === "halt") return { value: r.tape.cells[r.tape.head].content, ...base };
452
+ return { error: `${r.haltKind}: ${r.haltReason}`, haltKind: r.haltKind, final: ["cost", "time", "approval", "parkExpired", "depth", "autonomy"].includes(r.haltKind), ...base };
453
+ },
454
+ approve: (req, io) => {
455
+ // A parked answer comes through `resume`; this is the live ask.
456
+ notice("needs", canvas, id);
457
+ return askPerson(canvas, id, live, { tool: { name: "machine", kind: "machine", server: "machine", gateTool: "machine" }, call: { args: cardArgs(req) }, signal: io?.signal, canPark }).then(toDecision);
458
+ },
459
+ ask: (req, io) => {
460
+ notice("needs", canvas, id);
461
+ return askPerson(canvas, id, live, { tool: { name: "machine", kind: "machine-question", server: "machine", gateTool: "ask" }, call: { args: { question: req.message } }, signal: io?.signal, canPark }).then((a) => {
462
+ if (a?.park) return { park: true };
463
+ const choice = typeof a === "string" ? a : a?.choice;
464
+ if (choice === undefined) return { none: true };
465
+ const text = typeof a?.text === "string" ? a.text : typeof a?.args?.answer === "string" ? a.args.answer : typeof a?.args?.text === "string" ? a.args.text : undefined;
466
+ // The run being stopped while the question waits closes the card as a deny: that is a cancel, not the person's no.
467
+ return choice === "cancel" || (choice === "deny" && io?.signal?.aborted) ? { declined: true, cancelled: true } : choice !== "approve" && choice !== "always" ? { declined: true } : text === undefined ? { declined: true } : { answer: text };
468
+ });
469
+ },
470
+ };
471
+ const publish = () => {
472
+ const d = session.driver;
473
+ live.value = { ...live.value, runId, status: live.value.status === "parked" ? "parked" : d.current.halted ? "halted" : live.value.status, value: runValue(c, d.current), events: traceOf(d.events), usage: d.usage, activeMs: d.activeMs, restarts: d.restarts, stepwise: session.stepwise };
474
+ };
475
+ session.publish = publish;
476
+ const headerRun = traceRun ?? newRunId();
477
+ session.driver = createDriver(c, {
478
+ env,
479
+ // An unattended run (#1047): the caps are the grant's (already the lowest of the pane's, the grant's and what the ledger has left), and the grant is asked before every step.
480
+ // A child machine runs inside its parent's remainder, so it takes the parent's grant check and the nested budget.
481
+ limits: grant ? { ...nestLimits(s.limits, budget), ...(budget ? {} : { maxCostUsd: grant.caps.maxCostUsd, maxDurationMs: grant.caps.maxDurationMs }), authority: () => grant.check() } : nestLimits(s.limits, budget),
482
+ restart: s.restart,
483
+ signal,
484
+ inject: continuation?.inject ?? requested ?? s.inject,
485
+ from,
486
+ header: {
487
+ run: headerRun,
488
+ provider: providerIdentity(llm, pane.replies),
489
+ // What decides what a run does, as an identity: no key and no name of one (src/machine/trace.js runHeader).
490
+ settings: { policy: s.policy, gate: s.gate, ...(s.noApproval.length ? { noApproval: s.noApproval } : {}), canAsk: s.canAsk, ...(s.risk ? { risk: s.risk } : {}), restart: s.restart ?? null, parkMs: s.parkMs, limits: { ...s.limits, price: s.limits.price ?? null } },
491
+ },
492
+ continuation,
493
+ nextProposal,
494
+ paused: () => session.pause,
495
+ onRestart: () => providers.clear(), // a fresh start asks a fresh provider (a recording replays from its first reply)
496
+ onEvent: () => publish(),
497
+ onRun: () => {
498
+ publish();
499
+ if (!quiet) checkpointSave(canvas, id, session);
500
+ },
501
+ });
502
+ session.grant = grant; // (an unattended run drives only a session made inside its grant)
503
+ session.rebind = (newSignal, newRunId) => session.driver.rebind?.(newSignal);
504
+ // This page's runs of the pane, kept for the replay stepper and the diff (ephemeral, like the tape).
505
+ const runs = perCanvas(history, canvas);
506
+ const mine = (runs.get(id) ?? []).filter((r) => r.driver !== session.driver);
507
+ if (!quiet) runs.set(id, [...mine, { id: headerRun, c, driver: session.driver }].slice(-HISTORY_LIMIT));
508
+ return session;
509
+ }
510
+
511
+ // ── parking (the agent's park store; a record of its own format) ──────────────────────────────
512
+
513
+ const timers = new WeakMap();
514
+ const cardOf = (key, request) => ({ key, parked: true, machine: true, tool: "machine", kind: request.kind === "question" ? "machine-question" : "machine", args: request.kind === "question" ? { question: request.message } : request.args });
515
+
516
+ function showParked(canvas, id, live, request) {
517
+ const key = `m${++seq}`;
518
+ const card = cardOf(key, request);
519
+ live.value = { ...live.value, status: "parked", pending: [card] };
520
+ approvals.value = { ...approvals.value, pending: [...approvals.value.pending.filter((p) => !(p.canvas === canvas && p.id === id)), { canvas, id, ...card }] };
521
+ }
522
+ function forgetParked(canvas, id) {
523
+ approvals.value = { ...approvals.value, pending: approvals.value.pending.filter((p) => !(p.canvas === canvas && p.id === id && p.parked)) };
524
+ clearTimeout(perCanvas(timers, canvas).get(id));
525
+ }
526
+
527
+ /** Keep a parked run beside the canvas: its state, the proposal it holds and what it spent. Returns false when it cannot be kept. */
528
+ async function parkSave(canvas, id, session) {
529
+ const { parkMs } = session.settings;
530
+ const d = session.driver;
531
+ const run = d.current;
532
+ if (!parkMs || !run.parked) return false;
533
+ const [storeCanvas, storePane] = parkKey(canvas, id);
534
+ const now = Date.now();
535
+ const record = {
536
+ format: PARK_FORMAT,
537
+ version: 1,
538
+ canvasId: storeCanvas,
539
+ paneId: storePane,
540
+ parkedAt: now,
541
+ deadlineAt: now + parkMs,
542
+ parkMs,
543
+ fingerprint: session.fingerprint,
544
+ request: { ...run.parked.request, ...(run.parked.request.kind === "approval" ? { args: cardArgs({ state: run.state, proposal: run.parked.proposal }) } : {}) },
545
+ proposal: run.parked.proposal,
546
+ run: { state: run.state, step: run.step, tape: run.tape },
547
+ usage: { ...d.usage },
548
+ activeMs: d.activeMs,
549
+ restarts: d.restarts,
550
+ // The trace so far, so a run that goes on after a reload is still one replayable trace (a longer one is kept whole or not at all).
551
+ events: d.events.length <= PARK_EVENTS_LIMIT ? d.events : undefined,
552
+ };
553
+ await (await parkStoreOf(canvas)).set(storeCanvas, storePane, JSON.parse(JSON.stringify(record)));
554
+ showParked(canvas, id, session.live, record.request);
555
+ const timer = setTimeout(() => canvas.run(id), Math.max(0, record.deadlineAt - now));
556
+ timer.unref?.();
557
+ perCanvas(timers, canvas).set(id, timer);
558
+ return true;
559
+ }
560
+
561
+ /** A stored park for this pane that is still good: `{ record }`, `{ expired }` or null. Records of another definition are dropped. */
562
+ async function parkLoad(canvas, id, fingerprint) {
563
+ const [storeCanvas, storePane] = parkKey(canvas, id);
564
+ const store = await parkStoreOf(canvas);
565
+ const record = await store.get(storeCanvas, storePane);
566
+ if (!record) return null;
567
+ if (record.format !== PARK_FORMAT || record.fingerprint !== fingerprint || !record.run?.tape?.cells) {
568
+ await store.delete(storeCanvas, storePane);
569
+ return null;
570
+ }
571
+ if (Date.now() >= record.deadlineAt) {
572
+ await store.delete(storeCanvas, storePane);
573
+ return { expired: record };
574
+ }
575
+ return { record };
576
+ }
577
+ // ── checkpoints (#1034): a run in progress, kept beside the canvas, so a crash or a closed page does not lose it ──────────────────────────────
578
+
579
+ export const CHECKPOINT_FORMAT = "mallory-checkpoint-machine";
580
+ const checkpointKey = (canvas, id) => {
581
+ const [c, p] = parkKey(canvas, id);
582
+ return [c, `${p}~checkpoint`];
583
+ };
584
+ const checkpointQueue = new WeakMap(); // canvas -> Map(pane id -> the last write, so writes happen in order)
585
+
586
+ /**
587
+ * Keep (or, when the run has ended or is too long to keep whole, drop) the checkpoint of a session. Only for a person who opted into durable state
588
+ * (parkMs). The run's step is set a moment before its events are written, so the record is read after that moment and kept only when the trace
589
+ * has the step the run says it is at: a checkpoint always replays to the step it names.
590
+ */
591
+ function checkpointSave(canvas, id, session) {
592
+ const { parkMs } = session.settings;
593
+ if (!parkMs || cannotReplayInto(session.settings.kind)) return;
594
+ const queue = perCanvas(checkpointQueue, canvas);
595
+ const [storeCanvas, storePane] = checkpointKey(canvas, id);
596
+ queue.set(id, (queue.get(id) ?? Promise.resolve()).then(async () => {
597
+ const d = session.driver;
598
+ const run = d.current;
599
+ const lastStep = [...d.events].reverse().find((e) => e.type === "step_committed")?.step ?? 0;
600
+ const store = await parkStoreOf(canvas);
601
+ if (run.halted || d.events.length > PARK_EVENTS_LIMIT) await store.delete(storeCanvas, storePane);
602
+ else if (run.step > 0 && lastStep === run.step && d.events[0]?.type === "run_meta") await store.set(storeCanvas, storePane, { format: CHECKPOINT_FORMAT, version: 1, canvasId: storeCanvas, paneId: storePane, savedAt: Date.now(), fingerprint: session.fingerprint, step: run.step, events: JSON.parse(JSON.stringify(d.events)) });
603
+ }).catch(() => {}));
604
+ }
605
+ const checkpointDelete = async (canvas, id) => {
606
+ const queue = perCanvas(checkpointQueue, canvas);
607
+ await (queue.get(id) ?? Promise.resolve());
608
+ const [c, p] = checkpointKey(canvas, id);
609
+ await (await parkStoreOf(canvas)).delete(c, p).catch(() => {});
610
+ };
611
+
612
+ /** The kept checkpoint of a pane if it is for the pane as it is now, else null (another definition's is dropped). */
613
+ export async function checkpointOf(canvas, id) {
614
+ const pane = canvas.panes.get(id);
615
+ if (!pane) return null;
616
+ await (perCanvas(checkpointQueue, canvas).get(id) ?? Promise.resolve());
617
+ const [c, p] = checkpointKey(canvas, id);
618
+ const store = await parkStoreOf(canvas);
619
+ const record = await store.get(c, p);
620
+ if (!record) return null;
621
+ if (record.format !== CHECKPOINT_FORMAT || record.fingerprint !== fingerprintOf(pane) || !Array.isArray(record.events) || record.events[0]?.type !== "run_meta") {
622
+ await store.delete(c, p).catch(() => {});
623
+ return null;
624
+ }
625
+ return record;
626
+ }
627
+
628
+ /** The person chose to go on with the interrupted run: it is continued from its last committed step as one trace (a `resume` event, why "interrupted"). Never called by a tool. */
629
+ export async function resumeInterrupted(canvas, id) {
630
+ const record = await checkpointOf(canvas, id);
631
+ if (!record) return { error: "There is no interrupted run to resume." };
632
+ return requestFork(canvas, id, { source: { events: record.events }, resume: true, why: "interrupted" });
633
+ }
634
+
635
+ const parkDelete = async (canvas, id) => {
636
+ const [c, p] = parkKey(canvas, id);
637
+ await (await parkStoreOf(canvas)).delete(c, p).catch(() => {});
638
+ forgetParked(canvas, id);
639
+ };
640
+
641
+ const failureOf = (session, result) => {
642
+ const run = result.run;
643
+ const error = new AgentStop(run.haltKind, run.haltReason);
644
+ error.machine = { value: runValue(session.c, run), events: traceOf(result.events) };
645
+ error.partial = undefined;
646
+ error.agent = { steps: traceOf(result.events).map((e) => ({ type: e.type, text: eventLine(e) })), usage: result.usage };
647
+ return error;
648
+ };
649
+
650
+ /** Is this halt a way a machine ends well? (A terminal state, or the model's own HALT.) */
651
+ const succeeded = (run) => run.haltKind === "terminal" || run.haltKind === "halt";
652
+
653
+ /**
654
+ * The runner of a machine pane (src/model/runners/machine.js). The pane runs to a halt, unless the person is stepping (a stepwise session
655
+ * is kept and published as it is) or asked for one control (requestMachine). A failure halt (a cap, the watchdog, a refusal under the
656
+ * halt policy, nobody to approve) is an error of the pane with its halt kind, as for an agent; a terminal state or the model's own HALT
657
+ * sets the value. A run that parked is kept in the park store and skips until a person answers.
658
+ */
659
+ export async function runMachinePane(canvas, id, ctx) {
660
+ // An unattended run (a schedule: `canvas.root.unattended`, set by src/autonomy/unattended.js, never by a document or a tool) runs only inside a grant, as an agent does
661
+ // (src/agent/run.js; #1047): `begin()` before the first model call, the grant asked before every step, the run settled here whatever way it ends. A machine that parks in
662
+ // an unattended run is not resumed there: the schedule's inbox lists agent parks only, and the next sweep drops the record (docs/design/scheduled-runs.md).
663
+ if (canvas.root.unattended !== true) return runMachinePaneNow(canvas, id, ctx, null);
664
+ const unat = { auth: null, outcome: undefined, session: undefined, failure: undefined };
665
+ try {
666
+ const result = await runMachinePaneNow(canvas, id, ctx, unat);
667
+ if (unat.outcome === undefined) unat.outcome = "aborted"; // a skip or a supersede says nothing about whether the routine works
668
+ return result;
669
+ } catch (error) {
670
+ unat.failure = error;
671
+ unat.outcome = error?.name === "AbortError" ? "aborted" : unat.outcome === "parked" ? "parked" : "failed";
672
+ throw error;
673
+ } finally {
674
+ if (unat.auth) {
675
+ const u = unat.session?.driver.usage;
676
+ await unat.auth.settle({ outcome: unat.outcome ?? "failed", cost: u ? Math.max(0, u.cost - (unat.carry ?? 0)) : 0, unpriced: u?.unpriced ?? 0, reason: unat.failure?.message });
677
+ }
678
+ }
679
+ }
680
+
681
+ /** The unattended run's grant, asked for once before this pane's first session is made: no authority, a refusal or an unsound handle is a stop (fail closed). */
682
+ async function grantFor(canvas, id, unat) {
683
+ if (!unat) return null;
684
+ if (unat.auth) return unat.auth;
685
+ const authority = canvas.root.autonomy;
686
+ if (!authority || typeof authority.begin !== "function") throw new AgentStop("autonomy", "The machine didn't start: it was asked to run unattended and nothing here can check a grant, so it was refused. Make a grant and run it from a schedule.");
687
+ const pane = canvas.panes.get(id);
688
+ const got = await authority.begin({ canvasId: canvas.root.id, paneId: canvas === canvas.root ? id : `${canvas.id}:${id}`, pane: { maxCostUsd: pane?.capUsd, maxDurationMs: pane?.capMs } });
689
+ if (!got?.ok) throw new AgentStop("autonomy", got?.reason ?? "The machine didn't start: its grant could not be checked.");
690
+ const sound = (n) => Number.isFinite(n) && n > 0;
691
+ if (!sound(got.caps?.maxCostUsd) || !sound(got.caps?.maxDurationMs) || typeof got.check !== "function" || typeof got.settle !== "function") {
692
+ await got.settle?.({ outcome: "failed", reason: "an unsound grant handle" });
693
+ throw new AgentStop("autonomy", "The machine didn't start: its grant came back without the caps it must run inside.");
694
+ }
695
+ unat.auth = got;
696
+ return got;
697
+ }
698
+
699
+ async function runMachinePaneNow(canvas, id, { runId, signal, runtime, view }, unat) {
700
+ const live = liveOf(canvas, id);
701
+ const map = perCanvas(sessions, canvas);
702
+ const take = (weak) => {
703
+ const v = perCanvas(weak, canvas).get(id);
704
+ perCanvas(weak, canvas).delete(id);
705
+ return v;
706
+ };
707
+ const intent = take(intents);
708
+ const answer = take(answers);
709
+ const fork = take(forks);
710
+ const request = take(served);
711
+ const pane = canvas.panes.get(id);
712
+ // A machine the person opted in to be served as a model (`modelEndpoint`) runs under `mallory serve` only when a request asks: never on its own at start.
713
+ if (!request && canvas.root.serving && pane?.modelEndpoint && !fork && !intent && !answer) return skip("served as a model: it runs when a request asks");
714
+ const fp = fingerprintOf(pane);
715
+ let session = map.get(id);
716
+ try {
717
+ if (session && session.fingerprint !== fp) {
718
+ // The pane was edited under its session: that session (and any park of it) is over.
719
+ session.pause = true;
720
+ map.delete(id);
721
+ session = undefined;
722
+ await parkDelete(canvas, id);
723
+ await checkpointDelete(canvas, id);
724
+ }
725
+ // A run parked earlier (and the page reloaded since), or one whose park is over.
726
+ if (fork) {
727
+ // A fork or a resume the person asked for (requestFork checked it): a stepwise session on the tape of that step, with the lineage in its trace.
728
+ if (session) session.pause = true;
729
+ await parkDelete(canvas, id);
730
+ const k = fork.k;
731
+ session = await createSession(canvas, id, { runId, signal, runtime, from: { run: k.run, ...(fork.resume ? { usage: k.usage } : {}) }, continuation: { events: k.events, parent: k.parent, inject: k.inject }, nextProposal: k.nextProposal, replyOffset: k.replyOffset });
732
+ map.set(id, session);
733
+ session.stepwise = true;
734
+ session.driver.begin();
735
+ live.value = { runId, status: "idle", events: [], pending: [], value: undefined };
736
+ }
737
+ if (!fork && !intent && !answer && (!session || session.driver.current.haltKind === "parked")) {
738
+ const parked = await parkLoad(canvas, id, fp);
739
+ if (parked?.expired) {
740
+ map.delete(id);
741
+ throw new AgentStop("parkExpired", `The machine was parked for ${Math.round(parked.expired.parkMs / 1000)} s and nobody answered, so the proposal it held was dropped: an expired approval is not an approval.`);
742
+ }
743
+ if (parked?.record) {
744
+ if (!session) {
745
+ const r = parked.record;
746
+ const events = Array.isArray(r.events) && r.events[0]?.type === "run_meta" ? r.events : undefined;
747
+ session = await createSession(canvas, id, { runId, signal, runtime, run: events?.[0]?.run, from: { run: { ...r.run, halted: true, haltKind: "parked", haltReason: "waiting for a person", parked: { request: r.request, proposal: r.proposal } }, usage: r.usage, activeMs: r.activeMs, restarts: r.restarts, ...(events ? { events, restored: true } : { restored: true }) } });
748
+ map.set(id, session);
749
+ }
750
+ showParked(canvas, id, live, parked.record.request);
751
+ session.publish();
752
+ return skip("parked: waiting for a person's answer");
753
+ }
754
+ }
755
+ // A run that was cut off (a crash, a closed page) and kept: offered, never continued on its own (it may hold tool calls and spend).
756
+ if (!session && !fork && !intent && !answer) {
757
+ const cp = await checkpointOf(canvas, id);
758
+ if (cp) {
759
+ live.value = { runId, status: "interrupted", interrupted: { step: cp.step, savedAt: cp.savedAt }, events: [], pending: [], value: undefined };
760
+ return skip(`interrupted: a run was cut off at step ${cp.step}; resume it or start over`);
761
+ }
762
+ }
763
+ if (intent === "reset" || (intent && !session)) await checkpointDelete(canvas, id);
764
+ // A stepwise session the person is working in is published as it stands; any other run starts fresh.
765
+ if (!session || intent === "reset" || (!session.stepwise && !intent && !answer)) {
766
+ if (session) {
767
+ session.pause = true;
768
+ await parkDelete(canvas, id);
769
+ }
770
+ session = await createSession(canvas, id, { runId, signal, runtime, ...(request ? { inject: request.inject } : {}), grant: await grantFor(canvas, id, unat) });
771
+ if (unat) unat.session = session;
772
+ map.set(id, session);
773
+ session.stepwise = !request && (pane.stepwise === true || Boolean(intent));
774
+ live.value = { runId, status: "running", events: [], pending: [], value: undefined };
775
+ }
776
+ session.pause = false;
777
+ session.driver.rebind(signal);
778
+ session.publish();
779
+ if (intent === "reset" || (session.stepwise && !intent && !answer)) {
780
+ live.value = { ...live.value, runId, status: "idle", pending: [] };
781
+ session.publish();
782
+ return await publishValue(canvas, id, runId, session, runtime, view);
783
+ }
784
+ live.value = { ...live.value, runId, status: "running", pending: [] };
785
+ forgetParked(canvas, id);
786
+ // Unattended: only a session made inside this run's grant is driven (a person's step, an answer or a restored park never is: nobody is here).
787
+ if (unat && (!unat.auth || session.grant !== unat.auth)) throw new AgentStop("autonomy", "The machine didn't run: it was asked to run unattended and this session is not inside a grant, so it was refused.");
788
+ if (answer) await session.driver.resume(answer);
789
+ if (intent === "step") await session.driver.step();
790
+ else await session.driver.run();
791
+ session.publish();
792
+ if (signal?.aborted) return { superseded: true };
793
+ const run = session.driver.current;
794
+ if (run.halted && run.haltKind === "parked") {
795
+ if (await parkSave(canvas, id, session)) {
796
+ if (unat) unat.outcome = "parked";
797
+ return skip("parked: waiting for a person's answer"); // the "needs" notice went out when the card was asked
798
+ }
799
+ throw new AgentStop("approval", "The machine needs a person and could not keep itself parked.");
800
+ }
801
+ if (run.halted || answer) await parkDelete(canvas, id);
802
+ if (run.halted) await checkpointDelete(canvas, id);
803
+ if (!run.halted && !intent) {
804
+ live.value = { ...live.value, status: "paused" };
805
+ return await publishValue(canvas, id, runId, session, runtime, view);
806
+ }
807
+ if (run.halted && !succeeded(run)) {
808
+ live.value = { ...live.value, status: "stopped", error: run.haltReason };
809
+ notice("stopped", canvas, id);
810
+ throw failureOf(session, { run, events: session.driver.events, usage: session.driver.usage });
811
+ }
812
+ live.value = { ...live.value, status: run.halted ? "done" : "idle" };
813
+ if (unat && run.halted) unat.outcome = "done";
814
+ if (run.halted) notice("finished", canvas, id);
815
+ return await publishValue(canvas, id, runId, session, runtime, view);
816
+ } catch (error) {
817
+ if (error?.name === "AbortError" || signal?.aborted) {
818
+ live.value = { ...live.value, status: "superseded", pending: [] };
819
+ return { superseded: true };
820
+ }
821
+ if (!(error instanceof AgentStop)) live.value = { ...live.value, status: "error", error: error?.message ?? String(error), pending: [] };
822
+ throw error;
823
+ }
824
+ }
825
+
826
+ async function publishValue(canvas, id, runId, session, runtime, view) {
827
+ const d = session.driver;
828
+ const pane = canvas.panes.get(id);
829
+ // The lint (src/machine/lint.js: advice on a sound definition) is part of the value when there is any, so a pane downstream can check it (LTM-YAML-05, 06).
830
+ const lint = pane?.machine ? lintMachine(pane.machine, { protect: pane.lockedCells }) : [];
831
+ const value = { ...runValue(session.c, d.current), ...(lint.length ? { lint } : {}), trace: traceOf(d.events).map((e) => ({ ...e })), usage: { ...d.usage }, ...(d.restarts ? { restarts: d.restarts } : {}) };
832
+ const result = await runtime.set({ id, runId, value, view: view ?? "auto" });
833
+ return { ...result, agent: { steps: value.trace.map((e) => ({ type: e.type, text: eventLine(e) })), usage: d.usage } };
834
+ }
835
+
836
+ /** The person's answer to a card of a parked machine (Approve, Deny, with an edit); the run goes on from the kept proposal. Only a card calls this. */
837
+ export function answerMachine(canvas, id, choice, { text } = {}) {
838
+ const request = sessions.get(canvas)?.get(id)?.driver.current.parked?.request;
839
+ if (!request) return false;
840
+ const chose = choice === "approve" || choice === "always";
841
+ perCanvas(answers, canvas).set(id, request.kind === "question" ? (chose && typeof text === "string" ? { answer: text } : { declined: true }) : { decision: chose ? "approve" : "deny", ...(chose && typeof text === "string" ? { text } : {}) });
842
+ canvas.run(id);
843
+ return true;
844
+ }
845
+
846
+ /** A card of a live (not parked) request: delegates to the agent's. */
847
+ export const answerLive = (canvas, id, key, choice, extra) => answerApproval(canvas, id, key, choice, extra);
848
+
849
+ /**
850
+ * The person edits a cell of the live session (UI-03, GUARD-09): allowed on protected cells, recorded in the trace, never reachable from a tool.
851
+ * `patch`: { content?, kind? }. Returns an error text, or "".
852
+ */
853
+ export function editCell(canvas, id, cellId, patch) {
854
+ const session = sessions.get(canvas)?.get(id);
855
+ if (!session) return "Step or run the machine first: a cell is edited in a running session.";
856
+ const driver = session.driver;
857
+ const run = driver.current;
858
+ const at = run.tape.cells.findIndex((x) => x.id === cellId);
859
+ if (at < 0) return `There is no cell ${cellId}.`;
860
+ const cell = { ...run.tape.cells[at] };
861
+ if (patch.kind !== undefined) {
862
+ if (!session.c.kinds.includes(patch.kind)) return `${patch.kind} is not one of the machine's cell kinds.`;
863
+ cell.kind = patch.kind;
864
+ }
865
+ if (patch.content !== undefined) {
866
+ if (patch.content.length > session.c.content.maxChars) return `A cell holds at most ${session.c.content.maxChars} characters.`;
867
+ cell.content = patch.content;
868
+ }
869
+ driver.edit({ ...run, tape: { ...run.tape, cells: run.tape.cells.map((x, i) => (i === at ? cell : x)) } }, { type: "person_edit", step: run.step, cell: cellId, ...(patch.kind !== undefined ? { kind: patch.kind } : {}), ...(patch.content !== undefined ? { content: patch.content } : {}) });
870
+ return "";
871
+ }
872
+
873
+ /**
874
+ * Run machine pane `id` for one request of `mallory serve --model-endpoint` (src/headless/serve.js): the conversation `inject` ({ cellId: text }) goes onto
875
+ * its tape and the pane runs once, from a fresh session, under its own caps, gates and watchdog. The caller waits for the canvas to settle and reads the
876
+ * outcome with `servedOutcome`. Nothing is approved on the way: a state that needs a person finds nobody (or the person's own approvals script).
877
+ */
878
+ export function runServed(canvas, id, inject) {
879
+ sessions.get(canvas)?.delete(id);
880
+ perCanvas(served, canvas).set(id, { inject });
881
+ canvas.run(id);
882
+ }
883
+
884
+ /**
885
+ * How a served run ended: `{ ok: true, text, usage, run }` (a terminal state or the machine's own HALT: the final head cell is the reply), `{ ok: false, haltKind,
886
+ * reason }` (a cap, the watchdog, a refusal, nobody to approve), or `{ ok: false, error }` when the pane never ran (a definition that cannot run).
887
+ */
888
+ export function servedOutcome(canvas, id) {
889
+ const d = sessions.get(canvas)?.get(id)?.driver;
890
+ const run = d?.current;
891
+ if (!run?.halted) return { ok: false, error: String(canvas.stateOf(id)?.value?.error ?? "the machine did not run") };
892
+ if (!succeeded(run)) return { ok: false, haltKind: run.haltKind, reason: run.haltReason };
893
+ return { ok: true, text: run.tape.cells[run.tape.head].content, usage: { ...d.usage }, run: run.haltKind };
894
+ }
895
+
896
+ /** Pause a running machine after its current step (a pending approval stays). */
897
+ export function pauseMachine(canvas, id) {
898
+ const session = sessions.get(canvas)?.get(id);
899
+ if (session) session.pause = true;
900
+ return Boolean(session);
901
+ }
902
+
903
+ export const forgetMachine = (canvas, id) => sessions.get(canvas)?.delete(id);
904
+
905
+ // ── the trace as a file, replay, fork, resume and diff (wave L-H; docs/design/machine-pane.md, "The trace") ──────────────────────────
906
+
907
+ const labelOf = (r) => {
908
+ const run = r.driver.current;
909
+ const parent = r.driver.events[0]?.parent;
910
+ return `${r.id.slice(-8)} · ${run.step} step${run.step === 1 ? "" : "s"} · ${run.halted ? `halted (${run.haltKind})` : "not finished"}${parent ? ` · ${parent.resumed ? "resumes" : "forks"} ${String(parent.run).slice(-8)} at ${parent.at}` : ""}`;
911
+ };
912
+
913
+ /** The runs this page has made of the pane, newest last: `{ id, label, steps, events, halted, haltKind?, parent? }` (`events`: how long its trace is now). */
914
+ export const machineRuns = (canvas, id) =>
915
+ (history.get(canvas)?.get(id) ?? []).map((r) => ({ id: r.id, label: labelOf(r), definition: r.driver.events[0]?.definition?.hash, steps: r.driver.current.step, events: r.driver.events.length, halted: r.driver.current.halted, haltKind: r.driver.current.haltKind, haltReason: r.driver.current.haltReason, ...(r.driver.events[0]?.parent ? { parent: r.driver.events[0].parent } : {}) }));
916
+
917
+ /**
918
+ * What a source names: `{ runId }` is a run of this page, replayed on the definition it ran; `{ events }` is a trace read from a file,
919
+ * replayed on the pane's definition now (its header says whether that is the one it ran). Returns `{ events, c }` or `{ error }`.
920
+ */
921
+ function sourceOf(canvas, id, source) {
922
+ if (source?.runId) {
923
+ const r = (history.get(canvas)?.get(id) ?? []).find((x) => x.id === source.runId);
924
+ return r ? { events: [...r.driver.events], c: r.c } : { error: `There is no run ${source.runId} on this page.` };
925
+ }
926
+ if (Array.isArray(source?.events)) {
927
+ const pane = canvas.panes.get(id);
928
+ const problems = paneProblems(pane);
929
+ if (problems.length) return { error: `The machine can't run: ${problems.slice(0, 3).join("; ")}.` };
930
+ return { events: source.events, c: compile(pane.machine, { protect: settingsOf(pane).protect }) };
931
+ }
932
+ const last = (history.get(canvas)?.get(id) ?? []).at(-1);
933
+ return last ? { events: [...last.driver.events], c: last.c } : { error: "This machine has no run to look at yet: run or step it first, or load a trace." };
934
+ }
935
+
936
+ /** Replay a run or a trace file on its definition, with no model: `{ frames, problems, header, definitionMatches, events }` or `{ error }`. */
937
+ export function replayMachine(canvas, id, source) {
938
+ const s = sourceOf(canvas, id, source);
939
+ if (s.error) return { error: s.error };
940
+ return { ...replayTrace(s.c, s.events), events: s.events, c: s.c };
941
+ }
942
+
943
+ /**
944
+ * The person forks a run at a frame, or resumes one that stopped (their controls; no tool reaches this). `source` as for replayMachine,
945
+ * `at` the frame (0 is the start; a resume defaults to the last), `edit` ({ cell, content?, kind? }) one cell changed first, `proposal` what
946
+ * the next step takes instead of asking the model, `resume` to go on with the run's own spend instead of starting a new one, `why` the
947
+ * reason the trace records. Checked at once; the pane then runs once to start the session (stopped, stepwise). Returns { error } or { ok }.
948
+ */
949
+ export function requestFork(canvas, id, { source, at, edit, proposal, resume = false, why } = {}) {
950
+ if (machineLive(canvas, id).value.status === "running") return { error: "Pause the machine first: a fork replaces the session." };
951
+ const s = sourceOf(canvas, id, source);
952
+ if (s.error) return { error: s.error };
953
+ const frames = replayTrace(s.c, s.events).frames;
954
+ const frame = at ?? (resume ? frames.length - 1 : undefined);
955
+ let k;
956
+ try {
957
+ k = continueFrom(s.c, s.events, frame, { edit, proposal, resume, why });
958
+ } catch (error) {
959
+ return { error: error.message };
960
+ }
961
+ // The definition it continues on is the pane's: a recorded run of an older definition can't be put onto this one (continueFrom checks the hash against `c`).
962
+ const pane = canvas.panes.get(id);
963
+ const now = compile(pane.machine, { protect: settingsOf(pane).protect });
964
+ if (now !== s.c && JSON.stringify(now) !== JSON.stringify(s.c)) return { error: "The pane's definition changed since that run: it can't be continued on the new one." };
965
+ perCanvas(forks, canvas).set(id, { k, resume });
966
+ canvas.run(id);
967
+ return { ok: true, at: frame };
968
+ }
969
+
970
+ /** A trace as the person may save it: JSON Lines, redacted by the pane's capture policy and the one redaction policy. `{ text, name }` or `{ error }`. */
971
+ export function exportMachineTrace(canvas, id, source, { comments } = {}) {
972
+ const s = sourceOf(canvas, id, source);
973
+ if (s.error) return { error: s.error };
974
+ const pane = canvas.panes.get(id);
975
+ try {
976
+ // The person's comments on the run (their own store, passed in by the panel) ride in the file as `comment` events, through the same redaction.
977
+ return { text: serializeTrace(comments?.length ? withComments(s.events, comments) : s.events, { policy: retentionOf(canvas, id) }), name: `${String(pane?.name || id).replace(/[^\w.-]+/g, "-")}-${String(s.events[0]?.run ?? "trace").slice(-8)}.trace.jsonl` };
978
+ } catch (error) {
979
+ return { error: error.message };
980
+ }
981
+ }
982
+
983
+ /** A trace as OpenTelemetry spans (OTLP/JSON, a file: nothing is sent anywhere), redacted like the trace file. `{ text, name }` or `{ error }`. */
984
+ export function exportMachineOtlp(canvas, id, source) {
985
+ const s = sourceOf(canvas, id, source);
986
+ if (s.error) return { error: s.error };
987
+ const pane = canvas.panes.get(id);
988
+ return { text: otlpText(s.events, { policy: retentionOf(canvas, id), startMs: Date.now() }), name: `${String(pane?.name || id).replace(/[^\w.-]+/g, "-")}-${String(s.events[0]?.run ?? "trace").slice(-8)}.otlp.json` };
989
+ }
990
+
991
+ /** Two runs (of this page or from files) against each other, by step and by tape (diffRuns); `{ error }` when either can't be read. */
992
+ export function diffMachineRuns(canvas, id, a, b) {
993
+ const x = sourceOf(canvas, id, a);
994
+ const y = sourceOf(canvas, id, b);
995
+ if (x.error || y.error) return { error: x.error ?? y.error };
996
+ return diffRuns(x.c, { events: x.events }, { events: y.events });
997
+ }
998
+
999
+ /** A trace file read: `{ events, header, problems, unknown }` (parseTrace; fails closed). */
1000
+ export const readTraceFile = (text) => parseTrace(text);
1001
+
1002
+ /**
1003
+ * A trace file of either format for pane `id`: mallory's own, or a llmtm trace (converted on the pane's definition, LTM-TRACE-13). Returns
1004
+ * parseTrace's shape (`{ events, header, problems, unknown }`) plus `notes` and `imported`.
1005
+ */
1006
+ export function readAnyTrace(canvas, id, text) {
1007
+ if (!looksLikeLlmtmTrace(text)) return { ...parseTrace(text), notes: [], imported: false };
1008
+ const pane = canvas.panes.get(id);
1009
+ const bad = paneProblems(pane);
1010
+ if (bad.length) return { events: [], header: null, problems: [`the pane's definition is not sound, so a llmtm trace can't be read onto it: ${bad[0]}`], unknown: [], notes: [], imported: true };
1011
+ const c = compile(pane.machine, { protect: settingsOf(pane).protect });
1012
+ const r = importLlmtmTrace(text, c, { maxSteps: settingsOf(pane).limits.maxSteps });
1013
+ const unknown = [...new Set(r.events.filter((e) => String(e.type).startsWith("llmtm:")).map((e) => e.type))];
1014
+ return { events: r.events, header: r.events[0] ?? null, problems: r.problems, unknown, notes: r.notes, imported: true };
1015
+ }
1016
+ export { inspectTrace };
1017
+ export { usd, makeCell, approvals, parkStoreOf, parkKey };