@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,354 @@
1
+ // The WebSocket proxy of `mallory serve` (prism parity wave P-F; ws-client pane in proxy mode, src/panes/ws-client.js). A client connects to
2
+ // /<canvas>/<ws.proxy.path>; the server dials ONE upstream the canvas author fixed (`ws.proxy.upstream`, a person-only setting), relays the frames both
3
+ // ways and logs them. It is the WebSocket twin of the http proxy (src/model/proxy.js, src/model/runners/http-proxy.js) and keeps its rules:
4
+ //
5
+ // - No target is client-steerable. The upstream is fixed text; the client's path, query and headers pick nothing. Its subprotocols are offered
6
+ // upstream (tokens only) and the upstream's choice is what the client is told.
7
+ // - Outbound goes through the same socket policy as a page's (src/network/sockets.js): only the hosts `--allow-host` names (or every public host with
8
+ // --allow-all-hosts), nothing on this computer or the local network without --allow-local, and a name that resolves there is refused at connect time
9
+ // (src/headless/ws-connect.js pins the address it checked). A refused or failed dial answers 502 before the client's handshake is accepted.
10
+ // - Credentials: the client's headers, cookies and Authorization never go upstream (none of its headers do). The upstream's come from the person-set
11
+ // `ws.proxy.headers`, as secret placeholders the policy fills in for the hosts a key allows, over wss only. A request that carries a placeholder
12
+ // in ANY spelling the filler accepts (mallory- or miso-, any case, ":" or "%3a", URL-encoded once or twice) in its URL, a header or a subprotocol is
13
+ // refused (400) before anything is dialled: a client cannot ask the proxy to spend the operator's key. Upstream frames are scrubbed of the key's value.
14
+ // - Origin: a web page's upgrade (it says where it comes from) is accepted only from the origin `--cors` allows; `Origin: null` never. The Host
15
+ // header must name this listener when it listens on loopback (DNS rebinding). A bearer token is required when the server has one.
16
+ // - Bounds per proxy: open connections, one message's size (the frame reader refuses a bigger one before it is buffered), messages per second in each
17
+ // direction, and idle time. A frame over a limit closes the connection (1009, 1008, 1001).
18
+ // - Frames are logged through the redaction policy (src/model/ws-frames.js): text only when the person turned `ws.proxy.bodies` on, sizes otherwise.
19
+ // The log is the canvas's served log; with --traffic-history a finished connection is recorded in it too.
20
+ //
21
+ // Node only.
22
+ import { TICKET_MARKER } from "./ws-ticket.js";
23
+ import { createTap } from "../model/http-tap.js";
24
+ import { normalizeTraffic } from "../model/traffic.js";
25
+ import { cleanWs, parseSocketUpstream } from "../model/ws-client.js";
26
+ import { socketLabel } from "../model/ws-served.js";
27
+ import { secretNames } from "../model/proxy.js";
28
+ import { createSocketPolicy, cleanProtocols } from "../network/sockets.js";
29
+ import { redactText } from "../network/secrets.js";
30
+ import { headlessRefusal } from "./net.js";
31
+ import { loadWs, nodeSocketConnect } from "./ws-connect.js";
32
+
33
+ export const PROXY_SERVER_LIMITS = Object.freeze({ open: 32, syncMs: 100, dialMs: 5000, backlog: 4, dialsPerAddress: 30, dialWindowMs: 60000, addresses: 1024 });
34
+ const STATUS = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 426: "Upgrade Required", 429: "Too Many Requests", 502: "Bad Gateway", 503: "Service Unavailable" };
35
+
36
+ /** Answer an upgrade request with a plain refusal and drop the connection. */
37
+ export function rejectUpgrade(socket, status) {
38
+ const body = JSON.stringify({ error: STATUS[status] ?? "error" });
39
+ try {
40
+ socket.write(`HTTP/1.1 ${status} ${STATUS[status] ?? "Error"}\r\nconnection: close\r\ncontent-type: application/json; charset=utf-8\r\ncontent-length: ${Buffer.byteLength(body)}\r\nx-content-type-options: nosniff\r\ncache-control: no-store\r\n\r\n${body}`);
41
+ } catch {}
42
+ socket.destroy();
43
+ }
44
+
45
+ /**
46
+ * Close codes a peer may send in a close frame; 1005 (no code), 1006 (the connection dropped) and 1015 (TLS) are for the API, never the wire. A dropped
47
+ * or failed upstream is told to the client as 1011; one that closed without a code, as a normal close.
48
+ */
49
+ const wireCode = (code) => (Number.isInteger(code) && ((code >= 1000 && code <= 1003) || (code >= 1007 && code <= 1014) || (code >= 3000 && code <= 4999)) ? code : code === 1006 || code === 1015 ? 1011 : 1000);
50
+ const keyOk = (key) => typeof key === "string" && /^[A-Za-z0-9+/]{22}==$/.test(key);
51
+ const toBytes = (data) => (Buffer.isBuffer(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : Array.isArray(data) ? new Uint8Array(Buffer.concat(data)) : new Uint8Array(data));
52
+
53
+ /**
54
+ * @param {{
55
+ * net: { restrictFor?: (route) => ({ hosts: () => string[] }) | null, allowHosts?: string[], allowAllHosts?: boolean, allowLocal?: boolean, secrets?: Map<string, { value: string, hosts: string[] }>, resolve?: Function },
56
+ * stderr?: (line: string) => void,
57
+ * now?: () => number,
58
+ * connections?: ReturnType<typeof import("./ws-connections.js").createConnectionLog>, // GET /ws/connections: each accepted connection's counts (never a frame)
59
+ * }} options
60
+ */
61
+ export function createWsProxies({ net = {}, stderr = () => {}, now = () => Date.now(), connections = null } = {}) {
62
+ const proxies = new Map(); // "<route>/<pane id>" -> { key, policy, tap, open: Set, settings }
63
+ const open = new Set(); // every proxied connection: { ws, link, close(code, reason) }
64
+ let dialing = 0; // upgrades being dialled upstream (they count against the caps too: a flood of half-open ones is not free)
65
+ let reserved = 0; // upgrades that passed the global cap and are loading or checking limits: the slot is taken at once, not after an await
66
+ let wss;
67
+ let WSClass;
68
+
69
+ const secretsMap = net.secrets ?? new Map();
70
+ const scrub = (text) => redactText(text, [...secretsMap].map(([name, { value }]) => ({ name, value })));
71
+
72
+ async function load() {
73
+ WSClass ??= await loadWs();
74
+ if (!wss) {
75
+ const { WebSocketServer } = await import("ws");
76
+ wss = WebSocketServer;
77
+ }
78
+ }
79
+
80
+ function stateFor(host, entry) {
81
+ const settings = cleanWs({ mode: "proxy", proxy: entry.settings }).proxy;
82
+ const id = `${host.route}/${entry.id}`;
83
+ const key = JSON.stringify(settings);
84
+ let st = proxies.get(id);
85
+ if (st && st.key === key) return st;
86
+ const label = socketLabel(entry.name);
87
+ const tap = createTap({ maxEntries: settings.keep, maxBytes: 4 * 1048576, capture: () => ({ bodies: settings.bodies }), scrub, nameOf: () => label });
88
+ const sent = new Set(); // tap entry ids already handed to the history
89
+ let timer = null;
90
+ const sync = (final = false) => {
91
+ timer = null;
92
+ const { entries } = tap.snapshot();
93
+ const read = normalizeTraffic({ mode: "tap", entries }, { max: settings.keep }).entries.map((e, i) => ({ ...e, id: `ws-${host.route}-${entry.id}-${entries[i]?.id ?? i}`, source: "proxy", pane: label }));
94
+ host.recordSockets(label, read, final ? read.filter((e) => e.result !== "pending" && !sent.has(e.id)) : []);
95
+ if (final) for (const e of read) sent.add(e.id);
96
+ };
97
+ tap.subscribe(() => {
98
+ if (!timer) {
99
+ timer = setTimeout(() => sync(false), PROXY_SERVER_LIMITS.syncMs);
100
+ timer.unref?.();
101
+ }
102
+ });
103
+ const restrict = net.restrictFor?.(host.route) ?? null;
104
+ const policy = createSocketPolicy({
105
+ connect: nodeSocketConnect({ WS: WSClass, allowLocal: net.allowLocal === true && !restrict, ...(net.resolve ? { resolve: net.resolve } : {}), maxPayload: settings.frameBytes }),
106
+ // A route the operator gave a --grant reaches only its grant's hosts that --allow-host also lists (`restrict.hosts()`, read live): never --allow-all-hosts or --allow-local.
107
+ rules: () => (restrict ? { mode: "block", allowLocal: false, allowed: restrict.hosts(), blocked: [] } : { mode: net.allowAllHosts ? "allow" : "ask", allowLocal: net.allowLocal === true, allowed: net.allowHosts ?? [], blocked: [] }),
108
+ secrets: () => secretsMap,
109
+ onRefused: (verdict) => {
110
+ throw headlessRefusal(verdict);
111
+ },
112
+ tap,
113
+ limits: { frameBytes: settings.frameBytes, framesPerSecond: settings.framesPerSecond, open: settings.connections, handshakeMs: net.dialMs ?? PROXY_SERVER_LIMITS.dialMs },
114
+ });
115
+ st = { key, settings, policy, tap, open: new Set(), dialing: 0, byAddress: new Map(), dialLog: new Map(), label, flush: () => sync(true) };
116
+ proxies.set(id, st);
117
+ return st;
118
+ }
119
+
120
+ /**
121
+ * One client's upgrade. The caller (src/headless/serve.js) has already checked Host, Origin and the token and found the proxy;
122
+ * `refuse(status, note)` answers and records a refusal. Resolves when the connection is accepted, refused or gone.
123
+ * @param {{ host: { route: string, recordSockets: Function }, entry: { id: string, name: string, path: string, settings: object }, refuse: (status: number, note: string) => void }} ctx
124
+ */
125
+ async function upgrade(req, socket, head, { host, entry, refuse }) {
126
+ const answer = (status, note) => {
127
+ refuse(status, note);
128
+ rejectUpgrade(socket, status);
129
+ };
130
+ socket.on("error", () => {});
131
+ let held = false;
132
+ const unreserve = () => {
133
+ if (held) {
134
+ held = false;
135
+ reserved--;
136
+ }
137
+ };
138
+ try {
139
+ if (req.method !== "GET" || String(req.headers.upgrade).toLowerCase() !== "websocket" || !/\bupgrade\b/i.test(String(req.headers.connection))) return answer(426, "not a WebSocket upgrade");
140
+ if (req.headers["sec-websocket-version"] !== "13" || !keyOk(req.headers["sec-websocket-key"])) return answer(400, "a bad WebSocket handshake");
141
+ // A placeholder in any spelling, anywhere the client controls: nothing is dialled. (The client's headers never go upstream, so this is
142
+ // belt and braces: the policy would fill a placeholder wherever it found one.)
143
+ const texts = [req.url ?? "", ...(req.rawHeaders ?? [])];
144
+ if (texts.some((t) => secretNames(t).length)) return answer(400, "the request carries a secret placeholder, which a proxy does not forward");
145
+ let protocols = [];
146
+ const offered = req.headers["sec-websocket-protocol"];
147
+ if (offered !== undefined) {
148
+ try {
149
+ protocols = cleanProtocols(String(offered).split(",").map((p) => p.trim()).filter((p) => p && p !== TICKET_MARKER)); // the ticket marker (src/headless/ws-ticket.js) is ours, never the upstream's
150
+ } catch {
151
+ return answer(400, "the subprotocols are not valid");
152
+ }
153
+ }
154
+ if (open.size + dialing + reserved >= PROXY_SERVER_LIMITS.open) return answer(503, "too many proxied connections");
155
+ reserved++; // taken in the same turn as the check, so a burst cannot all pass it while one of them awaits
156
+ held = true;
157
+ await load();
158
+ const st = stateFor(host, entry);
159
+ if (st.open.size + st.dialing >= st.settings.connections) return answer(503, "too many connections to this proxy");
160
+ const address = String(socket.remoteAddress ?? "?");
161
+ if ((st.byAddress.get(address) ?? 0) >= st.settings.perAddress) return answer(503, "too many connections from this address");
162
+ // Dials per address per window, per proxy: a client that connects and drops over and over spends the upstream's (and the operator's) goodwill.
163
+ const t = now();
164
+ const stamps = (st.dialLog.get(address) ?? []).filter((at) => t - at < PROXY_SERVER_LIMITS.dialWindowMs);
165
+ if (stamps.length >= PROXY_SERVER_LIMITS.dialsPerAddress) {
166
+ st.dialLog.set(address, stamps);
167
+ return answer(429, "too many connection attempts from this address");
168
+ }
169
+ stamps.push(t);
170
+ st.dialLog.delete(address);
171
+ st.dialLog.set(address, stamps); // (newest last: the map's oldest address is its first key)
172
+ while (st.dialLog.size > PROXY_SERVER_LIMITS.addresses) st.dialLog.delete(st.dialLog.keys().next().value);
173
+ let slot = false;
174
+ const freeSlot = () => {
175
+ if (!slot) return;
176
+ slot = false;
177
+ const n = (st.byAddress.get(address) ?? 1) - 1;
178
+ if (n > 0) st.byAddress.set(address, n);
179
+ else st.byAddress.delete(address);
180
+ };
181
+ const up = parseSocketUpstream(st.settings.upstream);
182
+ if (!up.ok) return answer(502, `the proxy's upstream is not valid: ${up.why}`);
183
+
184
+ const gone = new AbortController();
185
+ socket.once("close", () => gone.abort());
186
+ let clientWs = null;
187
+ const pending = [];
188
+ let pendingBytes = 0;
189
+ const conn = { ws: null, link: null, close: () => {} };
190
+ let idle = null;
191
+ let done = false;
192
+ let log = null; // this connection's entry in the connection list, once the client is accepted
193
+ let endCode;
194
+ const touch = () => {
195
+ clearTimeout(idle);
196
+ idle = setTimeout(() => conn.close(1001, "idle"), st.settings.idleMs);
197
+ idle.unref?.();
198
+ };
199
+ let pinger = null;
200
+ const finish = () => {
201
+ if (done) return;
202
+ done = true;
203
+ clearTimeout(idle);
204
+ clearInterval(pinger);
205
+ open.delete(conn);
206
+ st.open.delete(conn);
207
+ log?.end(endCode);
208
+ freeSlot();
209
+ setTimeout(() => st.flush(), 0).unref?.();
210
+ };
211
+ // A peer that stops reading would otherwise make the proxy buffer for it without end. Past this many bytes waiting to be written, the connection
212
+ // is closed (1013, "try again later") and the operator's log says so.
213
+ const backlog = st.settings.frameBytes * PROXY_SERVER_LIMITS.backlog;
214
+ let slowed = false;
215
+ const slow = (who) => {
216
+ if (slowed) return; // one cut-off, one log line, however many writes notice it
217
+ slowed = true;
218
+ stderr(`mallory serve: ws proxy ${st.label}: closed a slow ${who} (more than ${backlog} bytes waiting to be written)`);
219
+ conn.close(1013, "slow peer");
220
+ };
221
+ /** Hand a message from the upstream to the client. True when it was written (not held, not refused): only that counts as activity. */
222
+ const deliver = (data) => {
223
+ if (clientWs) {
224
+ try {
225
+ clientWs.send(typeof data === "string" ? data : toBytes(data), { binary: typeof data !== "string" });
226
+ } catch {
227
+ return false;
228
+ }
229
+ log?.frame("in", typeof data === "string" ? Buffer.byteLength(data) : data.byteLength);
230
+ if (clientWs.bufferedAmount > backlog) {
231
+ slow("client");
232
+ return false;
233
+ }
234
+ return true;
235
+ }
236
+ pendingBytes += typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
237
+ if (pendingBytes > backlog) void conn.close(1008, "too much before the client was ready");
238
+ else pending.push(data);
239
+ return false;
240
+ };
241
+ let link;
242
+ dialing++;
243
+ unreserve(); // (counted as dialing from here)
244
+ st.dialing++;
245
+ slot = true;
246
+ st.byAddress.set(address, (st.byAddress.get(address) ?? 0) + 1); // a slot for this address from the dial until the connection is over
247
+ try {
248
+ link = await st.policy(up.href, { protocols, headers: st.settings.headers.map((h) => [h.name, h.value]) }, {
249
+ pane: st.label,
250
+ signal: gone.signal,
251
+ // The idle timer follows what the CLIENT does (a message or a pong from it), never the upstream alone.
252
+ onmessage: (data) => {
253
+ deliver(data); // (what the upstream sends is not activity: only the client's own messages and pongs are)
254
+ },
255
+ onclose: ({ code, reason }) => {
256
+ endCode ??= code;
257
+ finish();
258
+ if (clientWs) clientWs.close(wireCode(code), String(reason ?? "").slice(0, 100));
259
+ else socket.destroy();
260
+ },
261
+ });
262
+ } catch (error) {
263
+ st.flush();
264
+ // The client is told nothing about why: the operator's flags, the upstream's address and its errors are for the log.
265
+ stderr(`mallory serve: ws proxy ${st.label}: ${scrub(String(error?.message ?? error)).slice(0, 300)}`);
266
+ freeSlot();
267
+ return answer(502, "the upstream could not be reached");
268
+ } finally {
269
+ dialing--;
270
+ st.dialing--;
271
+ }
272
+ conn.link = link;
273
+ if (socket.destroyed) {
274
+ link.close(1000, "client gone");
275
+ freeSlot();
276
+ return;
277
+ }
278
+ conn.close = (code, reason) => {
279
+ endCode ??= code;
280
+ try {
281
+ link.close(code, reason);
282
+ } catch {}
283
+ if (clientWs) {
284
+ try {
285
+ clientWs.close(wireCode(code), reason);
286
+ } catch {}
287
+ setTimeout(() => clientWs.terminate(), 2000).unref?.();
288
+ } else socket.destroy();
289
+ finish();
290
+ };
291
+ open.add(conn);
292
+ st.open.add(conn);
293
+ touch();
294
+ const server = new wss({ noServer: true, maxPayload: st.settings.frameBytes, perMessageDeflate: false, clientTracking: false, handleProtocols: (set) => (link.protocol && set.has(link.protocol) ? link.protocol : set.has(TICKET_MARKER) ? TICKET_MARKER : false) });
295
+ // If `ws` aborts the handshake (it never calls back) or the client goes before it completes, nothing else would ever free this connection's slots.
296
+ socket.once("close", () => {
297
+ if (clientWs) return;
298
+ try {
299
+ link.close(1001, "client gone");
300
+ } catch {}
301
+ finish();
302
+ });
303
+ server.handleUpgrade(req, socket, head, (ws) => {
304
+ clientWs = ws;
305
+ conn.ws = ws;
306
+ log = connections?.begin({ kind: "proxy", canvas: host.route, pane: st.label }) ?? null;
307
+ // The client is alive while it answers pings (a reader that never sends is a client; a half-open or stalled one is not).
308
+ pinger = setInterval(() => {
309
+ try {
310
+ ws.ping();
311
+ } catch {}
312
+ }, Math.min(30000, Math.max(250, Math.floor(st.settings.idleMs / 3))));
313
+ pinger.unref?.();
314
+ ws.on("pong", touch);
315
+ ws.on("message", (data, isBinary) => {
316
+ touch();
317
+ log?.frame("out", Buffer.isBuffer(data) ? data.byteLength : Array.isArray(data) ? data.reduce((n, b) => n + b.byteLength, 0) : data.byteLength);
318
+ try {
319
+ link.send(isBinary ? toBytes(data) : (Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.concat(data).toString("utf8")));
320
+ } catch {
321
+ return void conn.close(1008, "limit");
322
+ }
323
+ if (link.bufferedAmount > backlog) slow("upstream");
324
+ });
325
+ ws.on("close", (code) => {
326
+ endCode = code;
327
+ try {
328
+ link.close(wireCode(code), "");
329
+ } catch {}
330
+ finish();
331
+ });
332
+ ws.on("error", () => conn.close(1011, "error"));
333
+ for (const data of pending.splice(0)) deliver(data);
334
+ });
335
+ } catch (error) {
336
+ stderr(`mallory serve: ws proxy: ${scrub(String(error?.message ?? error)).slice(0, 300)}`);
337
+ answer(502, "the proxy failed");
338
+ } finally {
339
+ unreserve();
340
+ }
341
+ }
342
+
343
+ return {
344
+ upgrade,
345
+ /** Open proxied connections. */
346
+ get open() {
347
+ return open.size;
348
+ },
349
+ /** Close every proxied connection (the server is closing). */
350
+ closeAll() {
351
+ for (const conn of [...open]) conn.close(1001, "server closing");
352
+ },
353
+ };
354
+ }
@@ -0,0 +1,48 @@
1
+ // Tickets for WebSocket upgrades to a token-protected `mallory serve` (#997). A browser WebSocket cannot send `Authorization`, and a token in the
2
+ // URL would end up in logs and history. So a caller that holds the token asks `POST /ws-ticket` (the normal bearer check) for a ticket, and offers it
3
+ // as a subprotocol, `mallory-ticket.<ticket>` beside `mallory-ws`, and the server reads and removes the ticket: it is never forwarded upstream, never echoed back (the answer is the upstream's choice, else `mallory-ws`), never in a URL.
4
+ // A ticket is random (128 bits), good for one upgrade, for one canvas route and proxy path, for the Origin that asked for it (none for a script),
5
+ // and for a short time. Nothing else is accepted in its place: a bearer token offered as a subprotocol is not.
6
+ import { randomBytes } from "node:crypto";
7
+
8
+ export const TICKET_PREFIX = "mallory-ticket.";
9
+ /** Offered beside the ticket and answered when the upstream picks no subprotocol: a browser fails a socket whose server picks none of the ones it offered. Never forwarded upstream. */
10
+ export const TICKET_MARKER = "mallory-ws";
11
+ export const TICKET_TTL_MS = 30_000;
12
+ const MAX_OUTSTANDING = 64;
13
+ const SHAPE = /^[0-9a-f]{32}$/;
14
+
15
+ export function createWsTickets({ now = () => Date.now(), ttlMs = TICKET_TTL_MS } = {}) {
16
+ const live = new Map(); // ticket -> { route, path, origin, expires }
17
+ const sweep = () => {
18
+ const t = now();
19
+ for (const [k, v] of live) if (v.expires <= t) live.delete(k);
20
+ };
21
+ return {
22
+ /** A new ticket for `route`/`path` and the `origin` the request carried (undefined for a script), or null when too many are waiting. */
23
+ mint({ route, path, origin }) {
24
+ sweep();
25
+ if (live.size >= MAX_OUTSTANDING) return null;
26
+ const ticket = randomBytes(16).toString("hex");
27
+ live.set(ticket, { route: String(route), path: String(path), origin: origin ?? "", expires: now() + ttlMs });
28
+ return { ticket, expiresInMs: ttlMs };
29
+ },
30
+ /** Spend a ticket: true once, for the route, path and origin it was made for. A wrong guess spends nothing; a right one is spent whatever else is wrong. */
31
+ take(ticket, { route, path, origin }) {
32
+ sweep();
33
+ if (typeof ticket !== "string" || !SHAPE.test(ticket)) return false;
34
+ const t = live.get(ticket);
35
+ if (!t) return false;
36
+ live.delete(ticket);
37
+ return t.route === String(route) && t.path === String(path) && t.origin === (origin ?? "") && t.expires > now();
38
+ },
39
+ size: () => (sweep(), live.size),
40
+ };
41
+ }
42
+
43
+ /** The ticket in a `Sec-WebSocket-Protocol` header value, and the header value without it (undefined when nothing else was offered). */
44
+ export function splitTicket(header) {
45
+ const offered = String(header ?? "").split(",").map((p) => p.trim()).filter(Boolean);
46
+ const mine = offered.filter((p) => p.startsWith(TICKET_PREFIX));
47
+ return { ticket: mine.length === 1 ? mine[0].slice(TICKET_PREFIX.length) : undefined, many: mine.length > 1, rest: offered.filter((p) => !p.startsWith(TICKET_PREFIX)) };
48
+ }
@@ -0,0 +1,50 @@
1
+ // The person's hook rules (CLW-SET-30): kept in this browser's localStorage, NEVER in a canvas document, so a share link or a file can't bring a hook along or take one
2
+ // away. They apply to every agent run in this browser. Agents (WebMCP) have no tool for them (WHY_NOT.HOOKS). A set that can't be read is not "no hooks": it is a
3
+ // broken set, which refuses every tool call (src/hooks/engine.js applyBefore), so damage to the stored rules can never loosen anything.
4
+ import { signal } from "@johnhenry/signalle";
5
+ import { localStore } from "../storage.js";
6
+ import { applyAfter, applyBefore, rulesProblem } from "./engine.js";
7
+
8
+ const KEY = "mallory:hooks";
9
+ const store = localStore("agent hooks");
10
+
11
+ export const hooksVersion = signal(0);
12
+ globalThis.addEventListener?.("storage", (e) => (e.key === null || e.key === KEY) && (hooksVersion.value = hooksVersion.value + 1));
13
+
14
+ // A headless process (mallory run / serve / test) has no browser settings: the operator's guard file gives the rules once, at start (src/headless/guards.js), and they
15
+ // replace the stored ones for good. A canvas, an agent or a person's page can't change them: `setHookRules` refuses while they are in force.
16
+ let fixed = null;
17
+ /** Headless only: use these rules (already checked) instead of the browser's; `null` goes back to the browser's. */
18
+ export function useFixedHookRules(rules) {
19
+ fixed = Array.isArray(rules) ? Object.freeze(rules.map((r) => Object.freeze({ ...r }))) : null;
20
+ }
21
+
22
+ /** The stored rules: a list (empty when none were ever saved), or null when what is stored can't be read. */
23
+ export function hookRules() {
24
+ if (fixed) return fixed;
25
+ const raw = store.getItem(KEY);
26
+ if (raw === null || raw === undefined) return [];
27
+ try {
28
+ const rules = JSON.parse(raw);
29
+ return Array.isArray(rules) ? rules : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ /** Save the rules, refusing a set that isn't sound: `{ ok: true }` or `{ ok: false, message }`. */
36
+ export function setHookRules(rules) {
37
+ if (fixed) return { ok: false, message: "hooks: this server's rules come from its guard file (--guards-file); change the file and restart" };
38
+ const problem = rulesProblem(rules);
39
+ if (problem) return { ok: false, message: problem };
40
+ if (rules.length) store.setItem(KEY, JSON.stringify(rules));
41
+ else store.removeItem(KEY);
42
+ hooksVersion.value = hooksVersion.value + 1;
43
+ return { ok: true };
44
+ }
45
+
46
+ /** What an agent run hands the gate (src/gate/gate.js `hooks`): reads the rules afresh at each call, so a change applies at once. */
47
+ export const personsHooks = () => ({
48
+ before: (call) => applyBefore(hookRules(), call),
49
+ after: (call, value) => applyAfter(hookRules(), call, value),
50
+ });
@@ -0,0 +1,189 @@
1
+ // Hooks on the agent's tool calls (CLW-AGT-02, CLW-SET-30; decision OQ10, docs/guide/agents-and-machines.md "Hooks"). FIRST-PARTY ONLY: a hook is a small DATA RULE the
2
+ // person writes in settings, read by this pure interpreter. There is no hook code: nothing is evaluated, nothing can reach the page, storage or the network, so a hook
3
+ // "runs in the sandbox" in the strictest way there is. Third-party plugins that rewrite tool calls are dropped by decision (OQ10's default).
4
+ //
5
+ // A hook can only NARROW. It may refuse a call, redact words or patterns in its arguments or its result, clamp a number or a text to a smaller one, or drop optional
6
+ // arguments. It can never add an argument, raise a number, add a tool or allow what the gate refused: `narrows` checks every rewrite against the original, and a rewrite
7
+ // that is not strictly a narrowing refuses the call. Fails closed: a rule set that is not sound, a rule that throws and a rewrite that fails the check all REFUSE the call.
8
+ // The gate (src/gate/gate.js beginCall) runs the hooks BEFORE its policy and its verdict, which keep their say: a hook never approves anything.
9
+ export const HOOK_POINTS = Object.freeze(["before-call", "after-result"]);
10
+ export const HOOK_ACTIONS = Object.freeze({ "before-call": ["refuse", "redact", "limit", "drop"], "after-result": ["redact", "truncate"] });
11
+ export const HOOK_LIMITS = Object.freeze({ rules: 50, text: 200, words: 20, keys: 20, max: 1_000_000 });
12
+ export const REDACTED = "[redacted]";
13
+
14
+ // Named patterns: fixed, bounded expressions (no backtracking traps). A person's own words are matched as plain text, never as an expression.
15
+ export const PATTERNS = Object.freeze({
16
+ email: /[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,
17
+ card: /\b(?:\d[ -]?){13,19}\b/g,
18
+ "secret-key": /\b(?:sk|pk|ghp|gho|ghs|xox[abp])[-_][A-Za-z0-9_-]{16,}\b/g,
19
+ bearer: /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/g,
20
+ });
21
+
22
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
23
+ const list = (v) => (Array.isArray(v) ? v : []);
24
+
25
+ /** `*` matches any run of characters; everything else is literal. Linear: no expression is built. */
26
+ export function glob(pattern, text) {
27
+ const parts = String(pattern ?? "*").split("*");
28
+ if (parts.length === 1) return pattern === text;
29
+ if (!String(text).startsWith(parts[0])) return false;
30
+ let at = parts[0].length;
31
+ for (const part of parts.slice(1, -1)) {
32
+ const i = String(text).indexOf(part, at);
33
+ if (i < 0) return false;
34
+ at = i + part.length;
35
+ }
36
+ const last = parts[parts.length - 1];
37
+ return String(text).length - last.length >= at && String(text).endsWith(last);
38
+ }
39
+
40
+ /** Why a rule set is not sound, or "". An unsound set is not applied in part: it refuses every call it covers (see `applyBefore`). */
41
+ export function rulesProblem(rules) {
42
+ if (!Array.isArray(rules)) return "hooks: a list of rules";
43
+ if (rules.length > HOOK_LIMITS.rules) return `hooks: at most ${HOOK_LIMITS.rules} rules`;
44
+ const ids = new Set();
45
+ for (const [i, r] of rules.entries()) {
46
+ const at = `rule ${i + 1}`;
47
+ if (!isObject(r)) return `${at}: an object`;
48
+ if (typeof r.id !== "string" || !r.id || r.id.length > 40 || ids.has(r.id)) return `${at}: a unique id of up to 40 characters`;
49
+ ids.add(r.id);
50
+ if (!HOOK_POINTS.includes(r.on)) return `${at}: on is ${HOOK_POINTS.join(" or ")}`;
51
+ if (!HOOK_ACTIONS[r.on].includes(r.action)) return `${at}: ${r.on} can ${HOOK_ACTIONS[r.on].join(", ")}`;
52
+ for (const k of ["server", "tool"]) if (typeof r[k] !== "string" || !r[k] || r[k].length > HOOK_LIMITS.text) return `${at}: ${k} is a name or a pattern with *`;
53
+ if (r.reason !== undefined && (typeof r.reason !== "string" || r.reason.length > HOOK_LIMITS.text)) return `${at}: reason is short text`;
54
+ for (const [k, max] of [["words", HOOK_LIMITS.words], ["keys", HOOK_LIMITS.keys], ["patterns", Object.keys(PATTERNS).length]]) {
55
+ if (r[k] !== undefined && (!Array.isArray(r[k]) || r[k].length > max || r[k].some((w) => typeof w !== "string" || !w || w.length > HOOK_LIMITS.text))) return `${at}: ${k} is a list of up to ${max} short texts`;
56
+ }
57
+ if (list(r.patterns).some((p) => !Object.hasOwn(PATTERNS, p))) return `${at}: patterns are ${Object.keys(PATTERNS).join(", ")}`;
58
+ if (r.action === "refuse" && !r.reason) return `${at}: a refusal says why`;
59
+ if (r.action === "redact" && !list(r.words).length && !list(r.patterns).length && !list(r.keys).length) return `${at}: redact needs words, patterns or keys`;
60
+ if (r.action === "limit" && (typeof r.key !== "string" || !r.key || !(Number.isFinite(r.max) && r.max >= 0 && r.max <= HOOK_LIMITS.max))) return `${at}: limit needs a key and a max`;
61
+ if (r.action === "drop" && !list(r.keys).length) return `${at}: drop needs keys`;
62
+ if (r.action === "truncate" && !(Number.isInteger(r.max) && r.max >= 1 && r.max <= HOOK_LIMITS.max)) return `${at}: truncate needs a length`;
63
+ const extra = Object.keys(r).filter((k) => !["id", "name", "on", "server", "tool", "action", "reason", "words", "patterns", "keys", "key", "max"].includes(k));
64
+ if (extra.length) return `${at}: ${extra[0]} isn't something a hook has`;
65
+ }
66
+ return "";
67
+ }
68
+
69
+ const redactText = (text, rule) => {
70
+ let out = text;
71
+ for (const word of list(rule.words)) {
72
+ const lower = out.toLowerCase();
73
+ const w = word.toLowerCase();
74
+ let at = 0;
75
+ let built = "";
76
+ for (let i = lower.indexOf(w); i >= 0; i = lower.indexOf(w, at)) {
77
+ built += out.slice(at, i) + REDACTED;
78
+ at = i + w.length;
79
+ }
80
+ out = built + out.slice(at);
81
+ }
82
+ for (const p of list(rule.patterns)) out = out.replace(PATTERNS[p], REDACTED);
83
+ return out;
84
+ };
85
+
86
+ const mapStrings = (v, fn, depth = 0) => {
87
+ if (depth > 12) throw new Error("the value is nested too deeply to check");
88
+ if (typeof v === "string") return fn(v);
89
+ if (Array.isArray(v)) return v.map((x) => mapStrings(x, fn, depth + 1));
90
+ if (isObject(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, mapStrings(x, fn, depth + 1)]));
91
+ return v;
92
+ };
93
+
94
+ /**
95
+ * Is `after` a narrowing of `before`? Objects keep a subset of their keys, arrays keep their length, a number keeps its sign and doesn't grow, and a text is the original
96
+ * with stretches replaced by "[redacted]" or cut short. Anything else (a new key, a bigger number, a different type, a longer or different text) is not.
97
+ */
98
+ export function narrows(before, after, depth = 0) {
99
+ if (depth > 12) return false;
100
+ if (before === after) return true;
101
+ if (typeof before === "number" && typeof after === "number") return Number.isFinite(after) && Math.sign(after) === Math.sign(before) && Math.abs(after) <= Math.abs(before);
102
+ if (typeof before === "string" && typeof after === "string") {
103
+ let at = 0;
104
+ for (const piece of after.split(REDACTED)) {
105
+ const i = before.indexOf(piece, at);
106
+ if (i < 0) return false;
107
+ at = i + piece.length;
108
+ }
109
+ return true;
110
+ }
111
+ if (Array.isArray(before) && Array.isArray(after)) return before.length === after.length && before.every((v, i) => narrows(v, after[i], depth + 1));
112
+ if (isObject(before) && isObject(after)) return Object.keys(after).every((k) => Object.hasOwn(before, k) && narrows(before[k], after[k], depth + 1));
113
+ return false;
114
+ }
115
+
116
+ const matches = (rule, call) => glob(rule.server, call.server) && glob(rule.tool, call.tool);
117
+
118
+ function applyOne(rule, args) {
119
+ if (rule.action === "redact") {
120
+ const keys = new Set(list(rule.keys));
121
+ const walk = (v, depth = 0) => {
122
+ if (depth > 12) throw new Error("the arguments are nested too deeply to check");
123
+ if (Array.isArray(v)) return v.map((x) => walk(x, depth + 1));
124
+ if (isObject(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, keys.has(k) && x !== undefined && x !== null ? (typeof x === "string" ? REDACTED : x === false ? false : x === 0 ? 0 : typeof x === "object" ? walk(x, depth + 1) : REDACTED) : walk(x, depth + 1)]));
125
+ return typeof v === "string" ? redactText(v, rule) : v;
126
+ };
127
+ return walk(args);
128
+ }
129
+ if (rule.action === "limit" && isObject(args) && Object.hasOwn(args, rule.key)) {
130
+ const v = args[rule.key];
131
+ if (typeof v === "number") return { ...args, [rule.key]: Math.sign(v) * Math.min(Math.abs(v), rule.max) };
132
+ if (typeof v === "string") return { ...args, [rule.key]: v.slice(0, rule.max) };
133
+ if (Array.isArray(v)) return { ...args, [rule.key]: v.slice(0, rule.max) };
134
+ }
135
+ if (rule.action === "drop" && isObject(args)) return Object.fromEntries(Object.entries(args).filter(([k]) => !list(rule.keys).includes(k)));
136
+ return args;
137
+ }
138
+
139
+ const broken = (problem) => ({ ok: false, reasons: [`the hook rules are not sound (${problem}), so the call is refused`] });
140
+
141
+ /**
142
+ * The hooks' say on a call before it runs: `{ ok: true, args, changed, notes }` (args narrowed) or `{ ok: false, reasons }`. Applies every matching "before-call" rule
143
+ * in order, then checks the result against the original with `narrows`. Never throws.
144
+ */
145
+ export function applyBefore(rules, call) {
146
+ try {
147
+ const problem = rulesProblem(rules);
148
+ if (problem) return broken(problem);
149
+ let args = structuredClone(call.args ?? {});
150
+ const notes = [];
151
+ for (const rule of rules) {
152
+ if (rule.on !== "before-call" || !matches(rule, call)) continue;
153
+ if (rule.action === "refuse") return { ok: false, reasons: [`hook "${rule.name || rule.id}": ${rule.reason}`] };
154
+ const next = applyOne(rule, args);
155
+ if (JSON.stringify(next) !== JSON.stringify(args)) notes.push(`hook "${rule.name || rule.id}" ${rule.action === "drop" ? "dropped arguments" : rule.action === "limit" ? `limited ${rule.key}` : "redacted"}`);
156
+ args = next;
157
+ }
158
+ if (!narrows(call.args ?? {}, args)) return { ok: false, reasons: ["a hook's rewrite was not a narrowing of the call, so the call is refused"] };
159
+ return { ok: true, args, changed: notes.length > 0, notes };
160
+ } catch (error) {
161
+ return { ok: false, reasons: [`a hook failed (${String(error?.message ?? error).slice(0, 80)}), so the call is refused`] };
162
+ }
163
+ }
164
+
165
+ /**
166
+ * The hooks' say on a result before the model sees it: the value redacted or cut (a narrowing, checked), or on any fault the value replaced by "[redacted]"
167
+ * (fails closed: the model gets less, never more). `{ value, changed }`.
168
+ */
169
+ export function applyAfter(rules, call, value) {
170
+ try {
171
+ if (rulesProblem(rules)) return { value: REDACTED, changed: true };
172
+ let out = value;
173
+ for (const rule of rules) {
174
+ if (rule.on !== "after-result" || !matches(rule, call)) continue;
175
+ out = rule.action === "truncate" ? mapStrings(out, (s) => s.slice(0, rule.max)) : mapStrings(out, (s) => redactText(s, rule));
176
+ }
177
+ if (!narrows(value, out)) return { value: REDACTED, changed: true };
178
+ return { value: out, changed: JSON.stringify(out) !== JSON.stringify(value) };
179
+ } catch {
180
+ return { value: REDACTED, changed: true };
181
+ }
182
+ }
183
+
184
+ /** The one-line description of a rule for the settings list. */
185
+ export function describeRule(r) {
186
+ const who = `${r.server === "*" ? "any server" : r.server} · ${r.tool === "*" ? "any tool" : r.tool}`;
187
+ const what = r.action === "refuse" ? `refuse: ${r.reason}` : r.action === "redact" ? `redact ${[...list(r.words).map((w) => `"${w}"`), ...list(r.patterns), ...list(r.keys).map((k) => `${k}=`)].join(", ")}` : r.action === "limit" ? `limit ${r.key} to ${r.max}` : r.action === "drop" ? `drop ${list(r.keys).join(", ")}` : `cut results to ${r.max} characters`;
188
+ return `${r.on === "before-call" ? "before the call" : "after the result"}: ${who} → ${what}`;
189
+ }