@arnilo/prism-hosts 0.0.0-stage → 0.13.1

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 (322) hide show
  1. package/CHANGELOG.md +394 -0
  2. package/LICENSE +21 -0
  3. package/README.md +34 -2
  4. package/acp/README.md +87 -0
  5. package/acp/src/capabilities.ts +184 -0
  6. package/acp/src/errors.ts +24 -0
  7. package/acp/src/host.ts +36 -0
  8. package/acp/src/index.ts +25 -0
  9. package/acp/src/limits.ts +49 -0
  10. package/acp/src/mapper.ts +419 -0
  11. package/acp/src/permission.ts +37 -0
  12. package/acp/src/projection.ts +39 -0
  13. package/acp/src/prompt.ts +170 -0
  14. package/acp/src/serve.ts +345 -0
  15. package/acp/src/session-map.ts +49 -0
  16. package/ag-ui/README.md +56 -0
  17. package/ag-ui/src/a2ui.ts +570 -0
  18. package/ag-ui/src/ag-ui-mapper.ts +507 -0
  19. package/ag-ui/src/encrypted-value.ts +40 -0
  20. package/ag-ui/src/errors.ts +29 -0
  21. package/ag-ui/src/handler.ts +642 -0
  22. package/ag-ui/src/index.ts +177 -0
  23. package/ag-ui/src/input.ts +190 -0
  24. package/ag-ui/src/limits.ts +279 -0
  25. package/ag-ui/src/mcp-apps.ts +256 -0
  26. package/ag-ui/src/mcp.ts +94 -0
  27. package/ag-ui/src/projection.ts +201 -0
  28. package/ag-ui/src/projectors.ts +272 -0
  29. package/ag-ui/src/renderer/bind.ts +152 -0
  30. package/ag-ui/src/renderer/core.ts +270 -0
  31. package/ag-ui/src/renderer/index.ts +165 -0
  32. package/ag-ui/src/replay.ts +189 -0
  33. package/ag-ui/src/types.ts +66 -0
  34. package/channels/README.md +139 -0
  35. package/channels/src/admission.ts +8 -0
  36. package/channels/src/approvals.ts +262 -0
  37. package/channels/src/checkpoint-contract.ts +97 -0
  38. package/channels/src/delivery.ts +116 -0
  39. package/channels/src/host-ui.ts +356 -0
  40. package/channels/src/identity.ts +46 -0
  41. package/channels/src/index.ts +82 -0
  42. package/channels/src/limits.ts +49 -0
  43. package/channels/src/memory-stores.ts +112 -0
  44. package/channels/src/pairing.ts +178 -0
  45. package/channels/src/runtime-admit.ts +389 -0
  46. package/channels/src/runtime-core.ts +621 -0
  47. package/channels/src/runtime-reconcile.ts +299 -0
  48. package/channels/src/runtime-turn.ts +664 -0
  49. package/channels/src/runtime-types.ts +95 -0
  50. package/channels/src/runtime.ts +86 -0
  51. package/channels/src/secret-ref.ts +42 -0
  52. package/channels/src/signal.ts +790 -0
  53. package/channels/src/state.ts +355 -0
  54. package/channels/src/telegram.ts +1317 -0
  55. package/channels/src/types.ts +442 -0
  56. package/devtools/README.md +92 -0
  57. package/devtools/bin/prism-devtools.ts +63 -0
  58. package/devtools/src/args.ts +71 -0
  59. package/devtools/src/bun.d.ts +27 -0
  60. package/devtools/src/compare.ts +190 -0
  61. package/devtools/src/errors.ts +15 -0
  62. package/devtools/src/index.ts +25 -0
  63. package/devtools/src/replay.ts +36 -0
  64. package/devtools/src/security.ts +80 -0
  65. package/devtools/src/serve.ts +259 -0
  66. package/devtools/src/ui/assets.ts +108 -0
  67. package/devtools/src/ui/inspector.ts +182 -0
  68. package/driver-process/README.md +197 -0
  69. package/driver-process/src/abort.ts +74 -0
  70. package/driver-process/src/adapter.ts +211 -0
  71. package/driver-process/src/driver.ts +303 -0
  72. package/driver-process/src/errors.ts +17 -0
  73. package/driver-process/src/extend.ts +72 -0
  74. package/driver-process/src/index.ts +5 -0
  75. package/driver-process/src/inspect.ts +33 -0
  76. package/driver-process/src/session.ts +72 -0
  77. package/driver-process/src/testing.ts +394 -0
  78. package/driver-process/src/transports/json-rpc.ts +147 -0
  79. package/driver-process/src/transports/jsonl-stream.ts +12 -0
  80. package/driver-process/src/transports/types.ts +11 -0
  81. package/driver-process/src/turn.ts +106 -0
  82. package/evals/README.md +843 -0
  83. package/evals/src/calibration.ts +179 -0
  84. package/evals/src/citation-integrity.ts +98 -0
  85. package/evals/src/citations.ts +45 -0
  86. package/evals/src/compare-experiments.ts +153 -0
  87. package/evals/src/comparison.ts +230 -0
  88. package/evals/src/curate.ts +257 -0
  89. package/evals/src/dataset.ts +81 -0
  90. package/evals/src/erp-invariants.ts +163 -0
  91. package/evals/src/errors.ts +23 -0
  92. package/evals/src/experiment.ts +537 -0
  93. package/evals/src/failure-injection.ts +77 -0
  94. package/evals/src/feedback.ts +53 -0
  95. package/evals/src/index.ts +198 -0
  96. package/evals/src/injection.ts +247 -0
  97. package/evals/src/judge-panel.ts +109 -0
  98. package/evals/src/judge.ts +89 -0
  99. package/evals/src/limits.ts +50 -0
  100. package/evals/src/report-record.ts +47 -0
  101. package/evals/src/rubric-judge.ts +334 -0
  102. package/evals/src/scenario-runner.ts +317 -0
  103. package/evals/src/scenarios.ts +81 -0
  104. package/evals/src/score.ts +328 -0
  105. package/evals/src/scorer.ts +21 -0
  106. package/evals/src/state-match.ts +130 -0
  107. package/evals/src/stats.ts +635 -0
  108. package/evals/src/threshold.ts +117 -0
  109. package/evals/src/timeline.ts +38 -0
  110. package/evals/src/toolless-session.ts +33 -0
  111. package/evals/src/trace.ts +80 -0
  112. package/evals/src/trajectory.ts +623 -0
  113. package/evals/src/types.ts +672 -0
  114. package/evals/src/user-simulator.ts +101 -0
  115. package/evals/src/util.ts +207 -0
  116. package/headless/README.md +172 -0
  117. package/headless/src/answers.ts +91 -0
  118. package/headless/src/authority.ts +32 -0
  119. package/headless/src/errors.ts +36 -0
  120. package/headless/src/index.ts +17 -0
  121. package/headless/src/limits.ts +11 -0
  122. package/headless/src/pending.ts +16 -0
  123. package/headless/src/policy.ts +36 -0
  124. package/headless/src/resume.ts +103 -0
  125. package/headless/src/route.ts +153 -0
  126. package/headless/src/scheduler/clock.ts +22 -0
  127. package/headless/src/scheduler/cron.ts +19 -0
  128. package/headless/src/scheduler/firing.ts +58 -0
  129. package/headless/src/scheduler/index.ts +399 -0
  130. package/headless/src/scheduler/lease.ts +38 -0
  131. package/headless/src/scheduler/missed.ts +12 -0
  132. package/headless/src/scheduler/state.ts +132 -0
  133. package/host-builder/README.md +251 -0
  134. package/host-builder/bin/prism-host-builder.ts +169 -0
  135. package/host-builder/data/api.json +6197 -0
  136. package/host-builder/data/errors.json +558 -0
  137. package/host-builder/data/examples/acp.ts +63 -0
  138. package/host-builder/data/examples/adapters/conformance.ts +34 -0
  139. package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
  140. package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
  141. package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
  142. package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
  143. package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
  144. package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
  145. package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
  146. package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
  147. package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
  148. package/host-builder/data/examples/advisor.ts +94 -0
  149. package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
  150. package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
  151. package/host-builder/data/examples/ag-ui-server.ts +118 -0
  152. package/host-builder/data/examples/agent-durable-approval.ts +43 -0
  153. package/host-builder/data/examples/api-key-auth.ts +23 -0
  154. package/host-builder/data/examples/approval.ts +92 -0
  155. package/host-builder/data/examples/attention-compiler.ts +81 -0
  156. package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
  157. package/host-builder/data/examples/behavior-evaluation.ts +303 -0
  158. package/host-builder/data/examples/build-workflow.ts +334 -0
  159. package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
  160. package/host-builder/data/examples/caveman-ponytail.ts +197 -0
  161. package/host-builder/data/examples/cli.ts +31 -0
  162. package/host-builder/data/examples/coding-approval.ts +115 -0
  163. package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
  164. package/host-builder/data/examples/coding-compaction.ts +30 -0
  165. package/host-builder/data/examples/coding-goal-verify.ts +121 -0
  166. package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
  167. package/host-builder/data/examples/compaction.ts +36 -0
  168. package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
  169. package/host-builder/data/examples/context.ts +29 -0
  170. package/host-builder/data/examples/custom-adapter.ts +256 -0
  171. package/host-builder/data/examples/custom-builders.ts +66 -0
  172. package/host-builder/data/examples/custom-loop.ts +89 -0
  173. package/host-builder/data/examples/custom-provider.ts +70 -0
  174. package/host-builder/data/examples/custom-session-store.ts +72 -0
  175. package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
  176. package/host-builder/data/examples/decision-models.ts +98 -0
  177. package/host-builder/data/examples/define-package.ts +188 -0
  178. package/host-builder/data/examples/delegate.ts +200 -0
  179. package/host-builder/data/examples/discover-skills.ts +65 -0
  180. package/host-builder/data/examples/drive-rag-sync.ts +44 -0
  181. package/host-builder/data/examples/durable-approval.ts +139 -0
  182. package/host-builder/data/examples/durable-investigation.ts +93 -0
  183. package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
  184. package/host-builder/data/examples/enterprise-identity.ts +21 -0
  185. package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
  186. package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
  187. package/host-builder/data/examples/eval-injection.ts +73 -0
  188. package/host-builder/data/examples/eval-judges.ts +145 -0
  189. package/host-builder/data/examples/evals.ts +86 -0
  190. package/host-builder/data/examples/evaluation-gate.ts +40 -0
  191. package/host-builder/data/examples/execution-timeline.ts +173 -0
  192. package/host-builder/data/examples/external-agent.ts +541 -0
  193. package/host-builder/data/examples/external-app-db-backed.ts +344 -0
  194. package/host-builder/data/examples/governance-deny.ts +122 -0
  195. package/host-builder/data/examples/guardrail-packs.ts +240 -0
  196. package/host-builder/data/examples/headless-host.ts +245 -0
  197. package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
  198. package/host-builder/data/examples/hooks-json.ts +87 -0
  199. package/host-builder/data/examples/host-builder-agent.ts +150 -0
  200. package/host-builder/data/examples/host-hooks.ts +71 -0
  201. package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
  202. package/host-builder/data/examples/hosted-sandbox.ts +48 -0
  203. package/host-builder/data/examples/instruction-injection.ts +127 -0
  204. package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
  205. package/host-builder/data/examples/long-term-memory.ts +158 -0
  206. package/host-builder/data/examples/manifest.ts +112 -0
  207. package/host-builder/data/examples/mcp-server.ts +48 -0
  208. package/host-builder/data/examples/mcp-trust.ts +173 -0
  209. package/host-builder/data/examples/memory-and-wiki.ts +315 -0
  210. package/host-builder/data/examples/memory-lifecycle.ts +302 -0
  211. package/host-builder/data/examples/memory-system.ts +255 -0
  212. package/host-builder/data/examples/messaging-agent.ts +70 -0
  213. package/host-builder/data/examples/minimal-host-app.ts +41 -0
  214. package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
  215. package/host-builder/data/examples/model-router.ts +106 -0
  216. package/host-builder/data/examples/obscura.ts +48 -0
  217. package/host-builder/data/examples/observability.ts +116 -0
  218. package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
  219. package/host-builder/data/examples/openai-compatible.ts +70 -0
  220. package/host-builder/data/examples/package-skills.ts +85 -0
  221. package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
  222. package/host-builder/data/examples/provider-registration.ts +29 -0
  223. package/host-builder/data/examples/provider-resolver.ts +39 -0
  224. package/host-builder/data/examples/rag.ts +40 -0
  225. package/host-builder/data/examples/remote-agent-server.ts +45 -0
  226. package/host-builder/data/examples/remote-agent.ts +124 -0
  227. package/host-builder/data/examples/research-ledger.ts +79 -0
  228. package/host-builder/data/examples/revocation-propagation.ts +287 -0
  229. package/host-builder/data/examples/run-feedback.ts +93 -0
  230. package/host-builder/data/examples/scanned-document-rag.ts +48 -0
  231. package/host-builder/data/examples/sdk-basics.ts +21 -0
  232. package/host-builder/data/examples/secure-agent.ts +55 -0
  233. package/host-builder/data/examples/semantic-memory.ts +52 -0
  234. package/host-builder/data/examples/serve-tools.ts +495 -0
  235. package/host-builder/data/examples/session-memory.ts +318 -0
  236. package/host-builder/data/examples/session-search.ts +131 -0
  237. package/host-builder/data/examples/session.ts +52 -0
  238. package/host-builder/data/examples/side-call.ts +68 -0
  239. package/host-builder/data/examples/signal-agent.ts +9 -0
  240. package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
  241. package/host-builder/data/examples/skills.ts +19 -0
  242. package/host-builder/data/examples/sqlite-resume.ts +147 -0
  243. package/host-builder/data/examples/system-project-prompts.ts +74 -0
  244. package/host-builder/data/examples/system-prompts.ts +19 -0
  245. package/host-builder/data/examples/telegram-agent.ts +30 -0
  246. package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
  247. package/host-builder/data/examples/tools.ts +29 -0
  248. package/host-builder/data/examples/validator.ts +67 -0
  249. package/host-builder/data/examples/web-no-key.ts +85 -0
  250. package/host-builder/data/examples/web-research.ts +35 -0
  251. package/host-builder/data/examples/workflow-event-sink.ts +114 -0
  252. package/host-builder/data/examples/workflow-loop.ts +93 -0
  253. package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
  254. package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
  255. package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
  256. package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
  257. package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
  258. package/host-builder/data/examples.json +130 -0
  259. package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
  260. package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
  261. package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
  262. package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
  263. package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
  264. package/host-builder/skills/prism-host-builder/references/security.md +52 -0
  265. package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
  266. package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
  267. package/host-builder/src/check/child.ts +108 -0
  268. package/host-builder/src/check/conformance.ts +13 -0
  269. package/host-builder/src/check/inspect.ts +20 -0
  270. package/host-builder/src/check/manifest.ts +23 -0
  271. package/host-builder/src/check/runner.ts +181 -0
  272. package/host-builder/src/check/targets.ts +65 -0
  273. package/host-builder/src/errors.ts +35 -0
  274. package/host-builder/src/index.ts +25 -0
  275. package/host-builder/src/indexes.ts +145 -0
  276. package/host-builder/src/install/install.ts +400 -0
  277. package/host-builder/src/install/targets.ts +50 -0
  278. package/host-builder/src/lookup/api.ts +127 -0
  279. package/host-builder/src/lookup/bound.ts +38 -0
  280. package/host-builder/src/lookup/docs.ts +238 -0
  281. package/host-builder/src/lookup/errors.ts +92 -0
  282. package/host-builder/src/lookup/examples.ts +117 -0
  283. package/host-builder/src/lookup/text.ts +60 -0
  284. package/host-builder/src/server.ts +300 -0
  285. package/host-builder/src/version.ts +38 -0
  286. package/mcp-server/README.md +219 -0
  287. package/mcp-server/src/bounds.ts +23 -0
  288. package/mcp-server/src/host.ts +31 -0
  289. package/mcp-server/src/index.ts +27 -0
  290. package/mcp-server/src/serve-tools.ts +408 -0
  291. package/mcp-server/src/serve.ts +329 -0
  292. package/mcp-server/src/server.ts +331 -0
  293. package/mcp-server/src/session-map.ts +47 -0
  294. package/mcp-server/src/skill-resources.ts +85 -0
  295. package/mcp-server/src/types.ts +215 -0
  296. package/package.json +130 -4
  297. package/remote/README.md +244 -0
  298. package/remote/src/attribution.ts +22 -0
  299. package/remote/src/auth.ts +30 -0
  300. package/remote/src/bun-module.d.ts +34 -0
  301. package/remote/src/channel.ts +86 -0
  302. package/remote/src/connect.ts +212 -0
  303. package/remote/src/dispatcher.ts +282 -0
  304. package/remote/src/errors.ts +59 -0
  305. package/remote/src/host-ui.ts +152 -0
  306. package/remote/src/http-gate.ts +43 -0
  307. package/remote/src/index.ts +53 -0
  308. package/remote/src/jsonl.ts +69 -0
  309. package/remote/src/limits.ts +43 -0
  310. package/remote/src/mirror.ts +90 -0
  311. package/remote/src/pending.ts +22 -0
  312. package/remote/src/protocol.ts +107 -0
  313. package/remote/src/serve.ts +560 -0
  314. package/remote/src/session-proxy.ts +219 -0
  315. package/remote/src/sse.ts +38 -0
  316. package/remote/src/stdio-client.ts +41 -0
  317. package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
  318. package/remote/src/testing.ts +230 -0
  319. package/remote/src/transport.ts +139 -0
  320. package/remote/src/transports/client.ts +126 -0
  321. package/remote/src/transports/network.ts +268 -0
  322. package/remote/src/wire.ts +244 -0
@@ -0,0 +1,244 @@
1
+ # @arnilo/prism-hosts/remote
2
+
3
+ Host library that serves a Prism `Agent` to remote clients and connects to remote agents over `prism.remote/1`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ bun add @arnilo/prism @arnilo/prism-hosts
9
+ ```
10
+
11
+ This is a host library, not a native package: import it in the host; do not add it to an agent's manifest or `packages` list. Network serving requires Bun. It registers no tools, skills, commands, hooks, slots, or services and declares no package capabilities.
12
+
13
+ ## What it does
14
+
15
+ - `serveAgent(agent, { transport, authenticate?, ownershipFor?, operator?, allowModifiedArguments?, hostUi?, resumeAuthority?, limits?, endpointId? })` serves any `Agent` over `prism.remote/1`: open, list, and resume sessions; `run` with events streamed as unchanged `run.event` notifications, then `run.settled`; `steer`, `abort`, `commands.*`, `inspect`, `models.list`, and `sessions.messages`.
16
+ - `remoteHostUi()` is a plain `HostUi`. Create the agent with it as `host.ui` and pass the same object to `serveAgent({ hostUi })`. Session-scoped requests route to a connection of the session's owning principal; agent-scoped requests (`sessionId` absent) route only to operator connections (`operator(principal) === true`, or single-principal connections). With no matching connection, or after a disconnect, it answers `unavailable`, so the kernel suspends the run durably (`suspended_run`). Package requests that do not suspend fail closed under their own contract.
17
+ - When the owning principal next initializes or reopens a suspended session, the server sends one `hostUi.request` per pending decision (read from the session's branch, so it works after a restart). The answers become `session.resume(decisions)`.
18
+ - Notifications for a run can arrive before the `run` response. Route them by `sessionId`.
19
+
20
+ - `connectAgent(endpoint, { host?, mirror?, ownership?, endpointId?, limits? })` returns an `Agent` proxy (`endpoint` is `{ kind: "stdio", command, env?, cwd? }` `{ kind: "memory", transport }`, `{ kind: "websocket", url, token? }`, or `{ kind: "http", url, token? }`). Use it anywhere an `Agent` goes, for example `agentNode({ agent: remote })`.
21
+ - Forwarded events keep their catalog `type` and gain `origin.remote`. An event that already has a nested `origin` keeps it. Every `tool.*` event carries `origin.executedBy: "external"`: the remote ran the tool under its own `tool.call` gate, so no local hook fires.
22
+ - The remote's `hostUi.request`s go to `host.ui`. With no local UI they answer `unavailable`, the remote run suspends, and `run()` resolves `status: "suspended"` with the pending decisions; `session.resume(decisions)` continues it.
23
+ - `mirror: store` archives each remote session into `store`: one links `metadata` entry (the session's `parent`, plus `actor: { kind: "prism", agent }`), then one `message` entry per `message.completed` (never per delta). `createSessionIndex(store).search({ query, workflowRunId })` finds them. Mirroring trusts the remote's redaction: entries are stored as received.
24
+ - `run`/`stream` send only `metadata`, `limits`, and `interactive`; `principal`, `ownership`, `redactor`, `runLedger`, and `signal` stay local (an aborted `signal` sends `abort`).
25
+ - Unsupported on a remote: `fork`, `checkout`, `compact`, `contextMeter`, `entries()` without a mirror, `models.resolve`, and `sessions.get/delete/search`. They fail with `remote_unsupported`.
26
+ - A disconnect rejects the active run with `disconnected`; the remote run suspends at its next ask.
27
+
28
+ ## When to use it
29
+
30
+ Serve an agent in another process, connect a workflow to a remote worker, or route a remote approval to the host's UI. The remote agent owns its packages, tools, persistence, and gates.
31
+
32
+ ## Configuration
33
+
34
+ ### `serveAgent(agent, options)`
35
+
36
+ | Field | Type | Default | Purpose |
37
+ | --- | --- | --- | --- |
38
+ | `transport` | stdio, WebSocket, HTTP, or `RemoteTransport` | required | Listener or frame transport. |
39
+ | `hostUi` | `HostUi` from `remoteHostUi()` | absent | Same object used as the agent's `host.ui`. |
40
+ | `resumeAuthority` | `RemoteResumeAuthority` | absent | Host-owned resume coordinator shared with other entry points, such as a headless router. |
41
+ | `authenticate` | `(Request) => { principal } \| undefined`, optionally async | bearer auth | Network authentication override; throwing denies access. |
42
+ | `ownershipFor` | `(principal: Principal) => OwnershipScope` | absent | Derives the kernel `OwnershipScope` for an authenticated principal across `sessions.open`, `sessions.list`, `run`, `sessions.resume`, and pending-decision resume. |
43
+ | `operator` | `(principal: Principal) => boolean` | absent | Marks a principal as an operator allowed to receive agent-scoped `hostUi` requests and `agent.event` notifications. |
44
+ | `allowModifiedArguments` | `boolean` | `false` | Allows clients to send `Decision.modifiedArguments` in `sessions.resume` (re-gated by the kernel before execution). |
45
+ | `endpointId` | string | random id | Endpoint attribution sent to clients. |
46
+ | `limits` | `RemoteLimitOptions` | below | Bounds shared by dispatchers and transports. |
47
+
48
+ Network `transport` fields:
49
+
50
+ | Field | Type | Default | Purpose |
51
+ | --- | --- | --- | --- |
52
+ | `kind` | `"websocket" \| "http"` | required | WebSocket or HTTP with SSE. |
53
+ | `hostname` | string | `127.0.0.1` | Non-loopback requires `authenticate`. |
54
+ | `port` | number | `0` | Ephemeral port. |
55
+ | `token` | secret ref only (`env:` / `keyring:`) | generated | Resolved once; literals refused. |
56
+ | `allowedHosts` | string[] | loopback hosts with bound port | Exact Host allow-list. |
57
+ | `allowedOrigins` | string[] | loopback HTTP origins | Exact Origin allow-list when Origin is present. |
58
+ | `maxRequestBytes` | number | `limits.maxFrameBytes` | Can narrow, never exceed the frame cap. |
59
+
60
+ Stdio accepts optional `input` and `output`, defaulting to process stdin/stdout. Keep stdout reserved for protocol frames.
61
+
62
+ ### `connectAgent(endpoint, options?)`
63
+
64
+ | Field | Type | Default | Purpose |
65
+ | --- | --- | --- | --- |
66
+ | `endpoint` | stdio, WebSocket, HTTP, or memory endpoint | required | Stdio: `{ kind: "stdio", command: string[], env?, cwd? }`; network: `{ kind, url, token? }`; memory: `{ kind: "memory", transport }`. |
67
+ | `host.ui` | `HostUi` | absent | Answers remote requests; absent answers `unavailable`. |
68
+ | `mirror` | `SessionStore` | absent | Opt-in local archive. |
69
+ | `ownership` | `OwnershipScope` | absent | Scope stamped on mirrored entries. |
70
+ | `endpointId` | string | server endpoint id | Override attribution for this connection. |
71
+ | `limits` | `RemoteLimitOptions` | below | Client dispatcher bounds. |
72
+
73
+ Network endpoint `token` is the resolved bearer value (for example `served.token`), unlike the server transport's ref-only `token`. Stdio `command` is an argv array, never shell text; its `env` overlays the inherited environment. Dispose the proxy to close the connection and terminate its owned child.
74
+
75
+ ### Limits
76
+
77
+ | Field | Default | Hard maximum | Purpose |
78
+ | --- | --- | --- | --- |
79
+ | `maxFrameBytes` | 1,048,576 | 16,777,216 | UTF-8 bytes per frame (minimum 1024). |
80
+ | `maxConnections` | 64 | 1024 | Network connections. |
81
+ | `keepAliveMs` | 15,000 | 60,000 | SSE keep-alive interval. |
82
+ | `maxConcurrentRequests` | 16 | 256 | Concurrent inbound handlers. |
83
+ | `maxPendingRequests` | 64 | 1024 | Outstanding outbound requests. |
84
+ | `maxQueuedEvents` | 1000 | 100,000 | Queued transport events. |
85
+
86
+ All limits are positive safe integers; values above hard maxima are rejected. Slow consumers disconnect rather than grow an unbounded queue.
87
+
88
+ ## Protocol
89
+
90
+ JSON-RPC 2.0 frames negotiate `prism.remote/1` in `initialize`. Unsupported versions fail with `protocol_unsupported` before sessions open. Capabilities are the intersection of both peers' known `hostUi`, `hostUi.secret`, and `agentEvents` flags; unknown flags are ignored.
91
+
92
+ | Method | Direction | Behavior |
93
+ | --- | --- | --- |
94
+ | `initialize` | client → server | Protocol, capabilities, endpoint and agent descriptors. |
95
+ | `sessions.open` | client → server | Create or reopen a session, optionally with parent links. |
96
+ | `sessions.list` | client → server | List sessions with a query. |
97
+ | `sessions.resume` | client → server | Resume pending decisions. |
98
+ | `sessions.messages` | client → server | Read branch messages. |
99
+ | `run` | client → server | Start a run; returns run id. |
100
+ | `steer` | client → server | Steer an active session. |
101
+ | `abort` | client → server | Abort an active session. |
102
+ | `commands.list` | client → server | List command descriptors. |
103
+ | `commands.run` | client → server | Run a command, optionally in a session. |
104
+ | `inspect` | client → server | Agent inspection. |
105
+ | `models.list` | client → server | List models. |
106
+ | `hostUi.request` | server → client | Request a negotiated UI answer. |
107
+ | `run.event` | server → client notification | Unchanged catalog event with session/run ids. |
108
+ | `run.settled` | server → client notification | Final run result. |
109
+ | `agent.event` | server → client notification | Negotiated agent-scoped event. |
110
+
111
+ ### Wire parameter allow-lists (`wire.ts`)
112
+
113
+ Every inbound wire payload is validated before reaching the kernel; unknown or out-of-range fields fail closed with `invalid_params`:
114
+
115
+ | Surface | Allowed fields & bounds | Rejected / stripped |
116
+ | --- | --- | --- |
117
+ | `run.options` / `sessions.resume.options` | `metadata` (object), `limits` (object), `interactive` (boolean) | `principal`, `ownership`, `redactor`, `runLedger`, `signal`, and any unknown key (`invalid_params`). |
118
+ | `sessions.resume.decisions[]` | `approvalId` (non-empty string ≤ 256), `outcome` (`allow_once` \| `allow_for_run` \| `reject_once` \| `reject_for_run`), `reason` (string ≤ 2 KiB), `elicitation` (JSON object, only for pending `elicitation` decisions), `modifiedArguments` (JSON object, only when `allowModifiedArguments: true`) | `modifiedArguments` when `allowModifiedArguments` is omitted/`false`, `elicitation` on `tool_approval` decisions, and any extra key (`invalid_params`). |
119
+ | `steer.options` | `softInterrupt` (boolean) | Any other key or non-boolean `softInterrupt` (`invalid_params`). |
120
+ | `sessions.list.query` | `cursor` (non-empty string ≤ 512), `limit` (integer `1..100`), `order` (`"asc"` \| `"desc"`), `agentId`, `parentSessionId`, `workflowRunId`, `delegationId`, `actorAgent` (non-empty strings ≤ `MAX_SESSION_LINK_ID_LENGTH`), `actorKind` (`"prism"` \| `"external"`) | Client-supplied `tenantId`, `accountId`, `userId` are stripped (server `ownershipFor` scope applies); any other key or out-of-range value is `invalid_params`. |
121
+ | `sessions.open.parent` | `sessionId`, `agentId`, `workflowRunId`, `delegationId` (non-empty strings ≤ `MAX_SESSION_LINK_ID_LENGTH`) | Any other key, empty string, or string > 256 chars (`invalid_params`). |
122
+
123
+ Stdio uses newline-delimited JSON; WebSocket uses one frame per message; HTTP uses JSON POST bodies and SSE `data` frames. A run's notifications can precede its request response: route by session id.
124
+
125
+ ## Attribution and mirroring
126
+
127
+ An event without an origin gains `{ kind: "prism", agent, agentId, remote: endpointId, depth: 0 }`. Existing origins keep every field and gain `remote` only if absent: the innermost endpoint wins across multiple hops. Every forwarded `tool.*` event sets `origin.executedBy: "external"`, even when `origin.kind` is `"prism"`. This means external to the connecting host: the remote's tool gate ran, and no local `tool.call` hook fires.
128
+
129
+ Mirroring is off by default. Enabling it adds one links metadata write when a session is new and one write per completed message, never per delta. Entries chain through `parentId`, retain workflow `parent` links, and carry `metadata.remote` and optional local ownership. Only `message.completed` is archived; user inputs and remote internal entries are not copied. Search with `createSessionIndex(store).search({ query: "report", workflowRunId })`. Run settlement waits for mirror writes; a write failure rejects locally even if execution completed remotely.
130
+
131
+ Mirroring trusts the remote's redaction and stores messages as received, without a second redactor. Choose a trusted remote and scope the local store appropriately.
132
+
133
+ ## Suspension and failure behavior
134
+
135
+ `remoteHostUi()` is a plain `HostUi`. Pass the same object to `createAgent({ host: { ui } })` and `serveAgent(agent, { hostUi: ui })`. No attached client or a lost connection answers `unavailable`. Only kernel asks and elicitations have durable suspension semantics; other package requests fail closed under their own contract. Use a persistent store on the served agent to survive restarts.
136
+
137
+ A later client initializes and opens the suspended session; the server reads pending decisions from the remote branch and sends UI requests, then resumes from answers. Unavailable answers leave decisions pending. Explicit `session.resume(decisions)` also works. A disconnected active proxy run rejects with `disconnected`; reconnect and reopen the session to inspect or continue it. Disposing a stdio proxy terminates its owned child, so persistence is needed for later recovery.
138
+
139
+ The proxy caches `inspect()` and command descriptors at initialization. Unsupported local operations fail with `remote_unsupported`; there is no local execution fallback. No extra model calls are made by this library.
140
+
141
+ ## Network transports
142
+
143
+ ```ts
144
+ const served = serveAgent(agent, { transport: { kind: "http", port: 0 }, hostUi: ui });
145
+ const remote = await connectAgent({ kind: "http", url: served.url!, token: served.token });
146
+ // Use remote as an Agent, then await remote.dispose() and served.close().
147
+ ```
148
+
149
+ Use `kind: "websocket"` on both sides for WebSocket. Each socket or SSE stream owns a dispatcher connection. HTTP uses `GET /events` for notifications and server requests; its `x-prism-connection` header identifies the stream. `POST /rpc?connection=<id>` carries client frames, returning RPC responses in the POST body. Server-request answers and notifications return 202.
150
+
151
+ The default bind is `127.0.0.1` on an ephemeral port, with a random 32-byte bearer token available only on `served.token`. Server configuration accepts `token: "env:NAME"` or `"keyring:name"`; literals fail with `literal_secret`. Keyring uses Bun's OS secret store, service `prism`; await `served.ready` before reading `url` or `token` for a keyring ref. Resolution failure rejects `ready` without opening a listener. Env refs resolve synchronously once at startup.
152
+
153
+ `authenticate(request)` on `serveAgent` replaces bearer authentication and must return `{ principal }` or `undefined`. Throws deny access. Non-loopback binds require this hook. Its principal supplies every run and resume; HTTP reauthenticates every POST and requires the same principal as the SSE stream. Wire callers cannot choose a principal.
154
+
155
+ Authorization travels only in `Authorization: Bearer`, never query parameters. Browser WebSocket clients cannot set this header: use a host authentication hook or HTTP with SSE. The client rejects credential-bearing URLs and redirects.
156
+
157
+ Host matching includes the port and is exact, case insensitive. Default allowed hosts are `127.0.0.1:<port>`, `localhost:<port>`, and `[::1]:<port>`. Default allowed origins are their `http://` origins. Missing Origin is accepted; a present unlisted Origin is rejected. Set `allowedHosts`/`allowedOrigins` on the transport to customize; an explicit empty list disables that gate, matching the MCP host library.
158
+
159
+ `maxRequestBytes` defaults to `limits.maxFrameBytes` and can only narrow it. Bodies are capped while reading. Authentication, Host and Origin gates run before dispatch, including WebSocket upgrades. Errors use fixed codes and do not echo credentials or hook errors.
160
+
161
+ `limits.maxConnections` defaults to 64 (hard maximum 1024); `limits.keepAliveMs` defaults to 15000 (hard maximum 60000). SSE comments keep the stream alive, and cancellation releases its dispatcher and HostUi binding. Queues and WebSocket backpressure are bounded; slow consumers disconnect.
162
+
163
+ ## Multi-user deployments
164
+
165
+ Every connection opened on a served agent is partitioned by its authenticated `Principal` (`kind` and `id`). Single-principal transports (`stdio`, memory, or loopback bearer authentication where `authenticate` is omitted) share the default single-principal partition, which also acts as operator.
166
+
167
+ - **Session isolation floor:** `ServerState.sessions` is keyed by principal and session id, backed by an $O(1)$ `sessionOwners` map. Independently of `ownershipFor`, any wire call (`sessions.open(id)`, `sessions.messages`, `run`, `steer`, `abort`, `sessions.resume`, or `commands.run` with `sessionId`) for a session owned by another principal rejects with `session_not_found`.
168
+ - **Kernel ownership scope (`ownershipFor`):** When `ownershipFor: (principal) => OwnershipScope` is configured on `serveAgent`, the derived scope is passed into `sessions.open` (`SessionOptions.ownership`), `sessions.list` (stripping any client-supplied ownership keys), `run`, `sessions.resume`, and reconnect pending-decision resume (`RunOptions.ownership`).
169
+ - **Owner-routed `remoteHostUi` and pending delivery:** Requests carrying `request.sessionId` route in $O(1)$ to a bound connection of that session's owning principal, or return `unavailable` (suspending the run durably) if that principal has no bound connection. On connect, `deliverPending` delivers only the connecting principal's suspended sessions.
170
+ - **Operator-only agent-scoped requests and events (`operator`):** `hostUi` requests without a `sessionId` and `agent.event` notifications without a `sessionId` (or from host-local sessions not owned by a remote principal) route only to connections where `operator(principal) === true` (or single-principal connections). Session-scoped `agent.event` notifications (`session.opened`, `background.*`) reach only that session's owning principal.
171
+
172
+ ```ts
173
+ serveAgent(agent, {
174
+ transport: { kind: "websocket", hostname: "0.0.0.0", port: 8443 },
175
+ authenticate: verifyJwt,
176
+ ownershipFor: (p) => ({ userId: p.id }),
177
+ operator: (p) => p.kind === "service",
178
+ hostUi,
179
+ });
180
+ ```
181
+
182
+ ## Conformance
183
+
184
+ `@arnilo/prism-hosts/remote/testing` exercises run, stream, steer, abort, resume,
185
+ inline HostUi answers, commands, and suspension on disconnect over stdio,
186
+ WebSocket, and HTTP with SSE. Every collected event must carry `origin.remote`
187
+ and must exclude the network bearer token. Results identify each transport and leg.
188
+
189
+ ```ts
190
+ import { remoteConformance } from "@arnilo/prism-hosts/remote/testing";
191
+
192
+ const result = await remoteConformance({
193
+ module: new URL("./fixture-agent.ts", import.meta.url).href,
194
+ prompts: { run: "hello", approve: "write the file" },
195
+ });
196
+ if (result.failures.length) throw new Error(JSON.stringify(result.failures));
197
+ ```
198
+
199
+ The module exports `async create({ hostUi, stateDirectory })`, returning a fresh
200
+ Agent with the supplied HostUi. The `run` prompt must complete without approval;
201
+ `approve` must request approval before completing. Include at least one command
202
+ that accepts no arguments and returns a deterministic result. The suite compares
203
+ stream event types and order with a fresh in-process agent.
204
+
205
+ Use `stateDirectory` for the fixture's persistent store. Stdio reconnect starts a
206
+ new child using the same directory; its fixture drains the pending approval before
207
+ exiting. The fixture module is loaded in both the caller and a Bun child process,
208
+ so its imports must resolve in both. The suite creates and removes its temporary
209
+ directories; it never constructs an agent or imports kernel testing helpers.
210
+
211
+ The optional second argument accepts `transports` (default all three) and
212
+ `timeoutMs` (default 2000 per leg). A timeout reports the transport and leg name.
213
+ The stdio fixture ships under `src/testing-fixtures` with the package.
214
+
215
+ ## Example
216
+
217
+ A manifest-free host can serve an already constructed agent:
218
+
219
+ ```ts
220
+ import { createAgent, providerDone, providerTextDelta } from "@arnilo/prism";
221
+ import { mockProvider } from "@arnilo/prism/testing";
222
+ import { connectAgent, remoteHostUi, serveAgent } from "@arnilo/prism-hosts/remote";
223
+
224
+ const ui = remoteHostUi();
225
+ const agent = await createAgent({
226
+ model: { provider: "mock", model: "demo" },
227
+ packages: [mockProvider([[providerTextDelta("Hello"), providerDone()]])],
228
+ host: { ui },
229
+ });
230
+ const served = serveAgent(agent, { transport: { kind: "http", port: 0 }, hostUi: ui });
231
+ await served.ready;
232
+ const remote = await connectAgent({ kind: "http", url: served.url!, token: served.token });
233
+ try {
234
+ console.log((await (await remote.session()).run("hello")).text);
235
+ } finally {
236
+ await remote.dispose();
237
+ await served.close();
238
+ await agent.dispose();
239
+ }
240
+ ```
241
+
242
+ Run `bun examples/remote-agent.ts` from the repository for the offline stdio example: a child mock agent asks approval through local scripted UI, runs beside a local workflow agent, prints the merged event stream with `origin.remote`, and finds both replies in one SQLite search. The paired `remote-agent-server.ts` owns stdout for protocol traffic.
243
+
244
+ When a headless router can also resume this agent, pass the same `createResumeAuthority(agent)` instance to `serveAgent` and `routeHostUi` as `resumeAuthority`. Both reconnect delivery and explicit `sessions.resume` then use its guarded resume stream while preserving connection principal and stream limits. The remote library imports no headless implementation. Without this option the existing remote-only guard applies; separate authorities or direct kernel resumes are not coordinated. Cross-process arbitration remains outside this guard.
@@ -0,0 +1,22 @@
1
+ import type { AgentEvent, EventOrigin } from "@arnilo/prism";
2
+
3
+ export interface AttributionSource {
4
+ /** The remote agent's name and id (from `initialize`). */
5
+ readonly agent: string;
6
+ readonly agentId: string;
7
+ /** The endpoint id stamped as `origin.remote`. */
8
+ readonly endpointId: string;
9
+ }
10
+
11
+ /**
12
+ * The merge rule (plan 170 Task 1 (g)). An event with no `origin` gains the remote agent's. An event with an
13
+ * `origin` keeps it and gains `remote` only when it has none, so the innermost endpoint wins. Every `tool.*`
14
+ * event is `executedBy: "external"`: the remote ran it, so no local `tool.call` hook ever saw it.
15
+ */
16
+ export function attribute(event: AgentEvent, source: AttributionSource): AgentEvent {
17
+ const existing = event.origin;
18
+ const origin: EventOrigin = existing
19
+ ? { ...existing, ...(existing.remote === undefined ? { remote: source.endpointId } : {}) }
20
+ : { kind: "prism", agent: source.agent, agentId: source.agentId, remote: source.endpointId, depth: 0 };
21
+ return { ...event, origin: event.type.startsWith("tool.") ? { ...origin, executedBy: "external" } : origin } as AgentEvent;
22
+ }
@@ -0,0 +1,30 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { secrets } from "bun";
3
+ import { RemoteError } from "./errors.js";
4
+
5
+ export function resolveToken(ref?: string): string | Promise<string> {
6
+ if (ref === undefined) return randomBytes(32).toString("hex");
7
+ if (/^env:[A-Za-z_][A-Za-z0-9_]*$/.test(ref)) {
8
+ const value = process.env[ref.slice(4)];
9
+ if (value) return value;
10
+ throw new RemoteError("unauthorized", "token reference unavailable");
11
+ }
12
+ if (/^keyring:.+$/.test(ref)) {
13
+ return secrets.get({ service: "prism", name: ref.slice(8) }).then(
14
+ (value) => {
15
+ if (!value) throw new RemoteError("unauthorized", "token reference unavailable");
16
+ return value;
17
+ },
18
+ () => {
19
+ throw new RemoteError("unauthorized", "token reference unavailable");
20
+ },
21
+ );
22
+ }
23
+ throw new RemoteError("literal_secret", "literal_secret: token must be an env: or keyring: reference");
24
+ }
25
+
26
+ export function bearerMatches(request: Request, token: string): boolean {
27
+ const actual = Buffer.from(request.headers.get("authorization") ?? "");
28
+ const expected = Buffer.from(`Bearer ${token}`);
29
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
30
+ }
@@ -0,0 +1,34 @@
1
+ // Scoped Bun module types keep unrelated global fetch and SQLite overloads out of host programs.
2
+ declare module "bun" {
3
+ export interface BunServer<T = unknown> {
4
+ readonly hostname: string;
5
+ readonly port: number;
6
+ stop(closeActiveConnections?: boolean): Promise<void> | void;
7
+ upgrade(request: Request, options: { data: T }): boolean;
8
+ }
9
+ export interface BunWebSocket<T> {
10
+ readonly data: T;
11
+ send(payload: string | Uint8Array): number;
12
+ close(code?: number, reason?: string): void;
13
+ }
14
+ export interface BunServeOptions<T = unknown> {
15
+ readonly hostname?: string;
16
+ readonly port?: number;
17
+ readonly maxRequestBodySize?: number;
18
+ fetch(request: Request, server: BunServer<T>): Response | undefined | Promise<Response | undefined>;
19
+ readonly websocket?: {
20
+ readonly data: T;
21
+ readonly maxPayloadLength?: number;
22
+ readonly backpressureLimit?: number;
23
+ readonly closeOnBackpressureLimit?: boolean;
24
+ readonly idleTimeout?: number;
25
+ open?(ws: BunWebSocket<T>): void;
26
+ message?(ws: BunWebSocket<T>, message: string | Uint8Array): void;
27
+ close?(ws: BunWebSocket<T>, code: number, reason: string): void;
28
+ };
29
+ }
30
+ export function serve<T>(options: BunServeOptions<T>): BunServer<T>;
31
+ export const secrets: {
32
+ get(options: { readonly service: string; readonly name: string }): Promise<string | undefined>;
33
+ };
34
+ }
@@ -0,0 +1,86 @@
1
+ import { RemoteError } from "./errors.js";
2
+
3
+ export type Overflow = "close" | "drop_oldest" | "drop_newest";
4
+
5
+ /** A bounded single-consumer async queue. A full queue follows `overflow`; `close` ends the stream with a `limit` error. */
6
+ export interface Channel<T> extends AsyncIterable<T> {
7
+ push(value: T): void;
8
+ /** Ends the stream after the queued values drain. A given error surfaces once the queue is empty. */
9
+ end(error?: Error): void;
10
+ readonly ended: boolean;
11
+ }
12
+
13
+ export function createChannel<T>(maxQueued: number, overflow: Overflow = "close", onReturn?: () => void): Channel<T> {
14
+ const queue: T[] = [];
15
+ let waiter: { resolve: (result: IteratorResult<T>) => void; reject: (error: Error) => void } | undefined;
16
+ let ended = false;
17
+ let failure: Error | undefined;
18
+
19
+ const settle = () => {
20
+ const pending = waiter;
21
+ if (!pending) return;
22
+ if (queue.length > 0) {
23
+ waiter = undefined;
24
+ pending.resolve({ value: queue.shift() as T, done: false });
25
+ } else if (ended) {
26
+ waiter = undefined;
27
+ if (failure) {
28
+ const error = failure;
29
+ failure = undefined;
30
+ pending.reject(error);
31
+ } else pending.resolve({ value: undefined, done: true });
32
+ }
33
+ };
34
+
35
+ return {
36
+ push(value) {
37
+ if (ended) return;
38
+ if (queue.length >= maxQueued) {
39
+ if (overflow === "drop_newest") return;
40
+ if (overflow === "drop_oldest") queue.shift();
41
+ else {
42
+ queue.length = 0;
43
+ ended = true;
44
+ failure = new RemoteError("limit", `subscriber exceeded ${maxQueued} queued events`);
45
+ settle();
46
+ return;
47
+ }
48
+ }
49
+ queue.push(value);
50
+ settle();
51
+ },
52
+ end(error) {
53
+ if (ended) return;
54
+ ended = true;
55
+ if (error) failure = error;
56
+ settle();
57
+ },
58
+ get ended() {
59
+ return ended;
60
+ },
61
+ [Symbol.asyncIterator]() {
62
+ return {
63
+ next: () => {
64
+ if (queue.length > 0) return Promise.resolve({ value: queue.shift() as T, done: false });
65
+ if (ended) {
66
+ if (failure) {
67
+ const error = failure;
68
+ failure = undefined;
69
+ return Promise.reject(error);
70
+ }
71
+ return Promise.resolve({ value: undefined, done: true });
72
+ }
73
+ return new Promise<IteratorResult<T>>((resolve, reject) => {
74
+ waiter = { resolve, reject };
75
+ });
76
+ },
77
+ return: () => {
78
+ ended = true;
79
+ queue.length = 0;
80
+ onReturn?.();
81
+ return Promise.resolve({ value: undefined, done: true });
82
+ },
83
+ };
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,212 @@
1
+ import type {
2
+ Agent,
3
+ AgentEvent,
4
+ AgentInspection,
5
+ HostUi,
6
+ HostUiResponse,
7
+ JsonObject,
8
+ JsonValue,
9
+ OwnershipScope,
10
+ RunResult,
11
+ SessionStore,
12
+ } from "@arnilo/prism";
13
+ import { attribute } from "./attribution.js";
14
+ import { createChannel } from "./channel.js";
15
+ import { createDispatcher, type Dispatcher } from "./dispatcher.js";
16
+ import { RemoteError } from "./errors.js";
17
+ import type { RemoteLimitOptions } from "./limits.js";
18
+ import { createSessionMirror } from "./mirror.js";
19
+ import type { HostUiRequestParams, InitializeResult, RemoteCapabilities } from "./protocol.js";
20
+ import { createSessionProxy, type SessionHandle } from "./session-proxy.js";
21
+ import { type SpawnedTransport, type StdioEndpoint, spawnStdioTransport } from "./stdio-client.js";
22
+ import type { RemoteTransport } from "./transport.js";
23
+
24
+ import { connectNetwork, type NetworkEndpoint } from "./transports/client.js";
25
+
26
+ export type ConnectEndpoint = NetworkEndpoint | StdioEndpoint | { readonly kind: "memory"; readonly transport: RemoteTransport };
27
+
28
+ export interface ConnectAgentOptions {
29
+ /** `host.ui` answers the remote's `hostUi.request`s. Without it they answer `unavailable` and the remote run suspends. */
30
+ readonly host?: { readonly ui?: HostUi };
31
+ /** Archives each remote session into this store: a links entry, then one entry per completed message. */
32
+ readonly mirror?: SessionStore;
33
+ /** Stamped on mirrored entries. */
34
+ readonly ownership?: OwnershipScope;
35
+ /** `origin.remote` for forwarded events. Defaults to the server's `endpointId`. */
36
+ readonly endpointId?: string;
37
+ readonly limits?: RemoteLimitOptions;
38
+ }
39
+
40
+ const isObject = (value: unknown): value is JsonObject => value !== null && typeof value === "object" && !Array.isArray(value);
41
+ const unsupported = (what: string): RemoteError => new RemoteError("remote_unsupported", `${what} is not supported on a remote agent`);
42
+
43
+ /**
44
+ * Connects to a served agent and returns an `Agent` proxy. Forwarded events keep their catalog type and gain
45
+ * `origin.remote`; tool events carry `executedBy: "external"`; the remote's `HostUi` requests go to
46
+ * `options.host.ui`. The remote's own hooks and gates run its tools, so no local `tool.call` fires for them.
47
+ */
48
+ export async function connectAgent(endpoint: ConnectEndpoint, options: ConnectAgentOptions = {}): Promise<Agent> {
49
+ let spawned: SpawnedTransport | undefined;
50
+ let transport: RemoteTransport;
51
+ if (endpoint.kind === "stdio") {
52
+ spawned = spawnStdioTransport(endpoint, options.limits);
53
+ transport = spawned.transport;
54
+ } else if (endpoint.kind === "memory") {
55
+ transport = endpoint.transport;
56
+ } else if (endpoint.kind === "websocket" || endpoint.kind === "http") {
57
+ transport = await connectNetwork(endpoint, options.limits);
58
+ } else {
59
+ throw unsupported(`endpoint kind ${String((endpoint as { kind?: unknown }).kind)}`);
60
+ }
61
+
62
+ const ui = options.host?.ui;
63
+ const handles = new Map<string, SessionHandle>();
64
+ const agentSubscribers = new Set<ReturnType<typeof createChannel<AgentEvent>>>();
65
+ let source = { agent: "", agentId: "", endpointId: options.endpointId ?? "" };
66
+
67
+ const offered: RemoteCapabilities = { agentEvents: true, ...(ui ? { hostUi: true, "hostUi.secret": true } : {}) };
68
+ const dispatcher: Dispatcher = createDispatcher({
69
+ transport,
70
+ role: "client",
71
+ capabilities: offered,
72
+ ...(options.limits ? { limits: options.limits } : {}),
73
+ requests: {
74
+ async "hostUi.request"(params): Promise<JsonValue> {
75
+ const request = (params as unknown as HostUiRequestParams).request;
76
+ if (!ui || !isObject(request)) return { status: "unavailable" };
77
+ try {
78
+ return (await ui.request(request as never)) as unknown as JsonValue;
79
+ } catch {
80
+ return { status: "unavailable" } satisfies HostUiResponse as JsonValue;
81
+ }
82
+ },
83
+ },
84
+ notifications: {
85
+ "run.event"(params) {
86
+ if (typeof params.sessionId === "string" && isObject(params.event))
87
+ handles.get(params.sessionId)?.event(params.event as unknown as AgentEvent);
88
+ },
89
+ "run.settled"(params) {
90
+ if (typeof params.sessionId === "string" && isObject(params.result))
91
+ handles.get(params.sessionId)?.settled(params.result as unknown as RunResult);
92
+ },
93
+ "agent.event"(params) {
94
+ if (!isObject(params.event)) return;
95
+ const event = attribute(params.event as unknown as AgentEvent, source);
96
+ for (const channel of agentSubscribers) channel.push(event);
97
+ },
98
+ },
99
+ });
100
+
101
+ let init: InitializeResult;
102
+ let commands: Agent["commands"];
103
+ try {
104
+ init = await dispatcher.initialize();
105
+ source = { agent: init.agent.name, agentId: init.agent.id, endpointId: options.endpointId ?? init.endpointId };
106
+ const listed = (await dispatcher.request("commands.list")) as unknown as ReturnType<Agent["commands"]["list"]>;
107
+ commands = {
108
+ list: () => listed,
109
+ run: (name, args, runOptions) =>
110
+ dispatcher.request("commands.run", {
111
+ name,
112
+ ...(args ? { args } : {}),
113
+ ...(runOptions?.session ? { sessionId: runOptions.session.id } : {}),
114
+ }),
115
+ };
116
+ } catch (error) {
117
+ await dispatcher.close().catch(() => {});
118
+ spawned?.kill();
119
+ throw error;
120
+ }
121
+
122
+ let disposed = false;
123
+ void dispatcher.closed.then(() => {
124
+ const gone = new RemoteError("disconnected", "connection closed");
125
+ for (const handle of handles.values()) handle.disconnected(gone);
126
+ for (const channel of agentSubscribers) channel.end();
127
+ agentSubscribers.clear();
128
+ });
129
+
130
+ const tools = Object.freeze([...init.agent.tools]) as unknown as Agent["tools"];
131
+ const skills = Object.freeze([...init.agent.skills]) as unknown as Agent["skills"];
132
+ const config = Object.freeze({ id: init.agent.id, name: init.agent.name }) as unknown as Agent["config"];
133
+ const remoteBlock = Object.freeze({
134
+ endpointId: source.endpointId,
135
+ protocol: init.protocol,
136
+ capabilities: Object.freeze({ ...init.capabilities }),
137
+ });
138
+ const inspection = init.agent.inspection;
139
+
140
+ const agent: Agent = {
141
+ id: init.agent.id,
142
+ config,
143
+ commands,
144
+ get tools() {
145
+ return disposed ? [] : tools;
146
+ },
147
+ get skills() {
148
+ return disposed ? [] : skills;
149
+ },
150
+ sessions: {
151
+ async list(query) {
152
+ const { signal: _signal, ...rest } = query ?? {};
153
+ return (await dispatcher.request("sessions.list", { query: rest as JsonObject })) as never;
154
+ },
155
+ async get() {
156
+ throw unsupported("sessions.get()");
157
+ },
158
+ async delete() {
159
+ throw unsupported("sessions.delete()");
160
+ },
161
+ async search() {
162
+ throw unsupported("sessions.search()");
163
+ },
164
+ },
165
+ models: {
166
+ list: async () => (await dispatcher.request("models.list")) as never,
167
+ resolve() {
168
+ throw unsupported("models.resolve()");
169
+ },
170
+ },
171
+ async reload() {
172
+ throw unsupported("reload()");
173
+ },
174
+ async session(sessionOptions = {}) {
175
+ const opened = (await dispatcher.request("sessions.open", {
176
+ ...(sessionOptions.id !== undefined ? { id: sessionOptions.id } : {}),
177
+ ...(sessionOptions.create !== undefined ? { create: sessionOptions.create } : {}),
178
+ ...(sessionOptions.parent ? { parent: { ...sessionOptions.parent } } : {}),
179
+ })) as unknown as { sessionId: string; leafId?: string };
180
+ const mirror = options.mirror
181
+ ? createSessionMirror({
182
+ store: options.mirror,
183
+ sessionId: opened.sessionId,
184
+ endpointId: source.endpointId,
185
+ agent: source.agent,
186
+ ...(sessionOptions.parent ? { parent: sessionOptions.parent } : {}),
187
+ ...(options.ownership ? { ownership: options.ownership } : {}),
188
+ })
189
+ : undefined;
190
+ await mirror?.open();
191
+ const proxy = createSessionProxy({ dispatcher, source }, opened.sessionId, opened.leafId, mirror);
192
+ handles.set(opened.sessionId, proxy.handle);
193
+ return proxy.session;
194
+ },
195
+ subscribe(subscribeOptions) {
196
+ const channel = createChannel<AgentEvent>(subscribeOptions?.maxQueuedEvents ?? 1024, subscribeOptions?.overflow ?? "close", () => {
197
+ agentSubscribers.delete(channel);
198
+ });
199
+ agentSubscribers.add(channel);
200
+ return channel;
201
+ },
202
+ async dispose() {
203
+ disposed = true;
204
+ await dispatcher.close("dispose");
205
+ spawned?.kill();
206
+ },
207
+ inspect() {
208
+ return { ...inspection, remote: remoteBlock } as AgentInspection;
209
+ },
210
+ };
211
+ return agent;
212
+ }