@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,442 @@
1
+ // Plan 079 Task 2: transport-neutral channel contracts. Frozen symbol names come from the
2
+ // Task 1 review (docs/history/079-messaging-primitive-review.md); option fields may grow in
3
+ // later tasks without renaming. Nothing here resolves credentials, reads the environment,
4
+ // opens sockets or starts a listener — hosts compose adapters and call `admit`.
5
+ import { OwnershipScope, SecretRedactor } from "@arnilo/prism";
6
+ import type { CheckpointStore, LeaseStore } from "./checkpoint-contract.js";
7
+ import type { AgentIdentity } from "./identity.js";
8
+ /** What the host is being asked to authorize for one inbound event. */
9
+ export type ChannelAction = "message" | "command" | "approval" | "notify";
10
+
11
+ /** Bounded denial reasons. Never carries message text or transport payloads. */
12
+ export type ChannelDenialReason =
13
+ | "malformed"
14
+ | "oversized"
15
+ | "rejected"
16
+ | "revoked"
17
+ | "authorization_failed"
18
+ | "capacity"
19
+ | "stopped"
20
+ | "awaiting_decision"
21
+ /** The durable journal is configured but unavailable; admission fails closed instead of running unclaimed. */
22
+ | "unavailable";
23
+
24
+ /** Bounded unsupported reasons for authorized humans (no model call). */
25
+ export type ChannelUnsupportedReason = "unknown_command" | "invalid_argument" | "unknown_alias" | "unsupported_media";
26
+
27
+ export type ChannelAdmissionStatus = "accepted" | "denied" | "unsupported";
28
+
29
+ /** Admission outcome returned before the transport acknowledges receipt. */
30
+ export interface ChannelAdmission {
31
+ readonly status: ChannelAdmissionStatus;
32
+ readonly reason?: ChannelDenialReason | ChannelUnsupportedReason;
33
+ /** Stable operation id for correlation; present on accepted ordinary turns. */
34
+ readonly operationId?: string;
35
+ /** True when this exact connection + event id was already admitted in-process. */
36
+ readonly duplicate?: boolean;
37
+ }
38
+
39
+ export interface ChannelCapabilities {
40
+ /** Telegram advances a poll offset; Signal has no transport acknowledgment step. */
41
+ readonly acknowledgement: "telegram_offset" | "none";
42
+ readonly controls: "callback" | "command";
43
+ /** Platform text ceiling for one outbound message, in UTF-16 code units. */
44
+ readonly maxTextCodeUnits: number;
45
+ }
46
+
47
+ /** One parsed inbound transport event. Transport fields are never authority. */
48
+ /** One opaque, transport-parsed approval action. The token never selects a session or agent. */
49
+ export interface ChannelApprovalControl {
50
+ readonly token: string;
51
+ readonly outcome: ChannelApprovalOutcome;
52
+ }
53
+
54
+ export type ChannelApprovalOutcome = "allow_once" | "reject_once";
55
+
56
+ export interface ChannelInboundEvent {
57
+ readonly connectionId: string;
58
+ /** Stable platform conversation key (chat id, Signal conversation/service id). */
59
+ readonly externalConversationId: string;
60
+ /** Stable platform actor key (Telegram user id, Signal service id/UUID) — never a display name. */
61
+ readonly externalActorId: string;
62
+ /** Transport acknowledgment unit: Telegram `update_id`, signal-cli envelope timestamp/id. */
63
+ readonly eventId: string;
64
+ readonly text: string;
65
+ /**
66
+ * Media the transport observed on this event: identifiers only, never bytes. Bytes exist only for
67
+ * the duration of one bounded adapter fetch (or one `ChannelRuntimeOptions.fetchAttachment`
68
+ * call) and are never journaled, logged, or retained on disk.
69
+ */
70
+ readonly attachments?: readonly ChannelAttachmentRef[];
71
+ /** Opaque transport control parsed by the adapter; never becomes model input. */
72
+ readonly approval?: ChannelApprovalControl;
73
+ /** Transport thread id (Telegram forum topic / group reply thread). It is part of the session and reply-binding key. */
74
+ readonly threadId?: string;
75
+ readonly receivedAt?: string;
76
+ /** Untrusted transport fields for host authorization context only. */
77
+ readonly claims?: Readonly<Record<string, unknown>>;
78
+ }
79
+
80
+ /** Modality of one transport attachment reference. `image` is the only kind that can become model input. */
81
+ export type ChannelAttachmentKind = "image" | "document" | "voice";
82
+
83
+ /** One attachment *reference* on an inbound event: never the bytes, never a URL, never model-selected. */
84
+ export interface ChannelAttachmentRef {
85
+ readonly kind: ChannelAttachmentKind;
86
+ /** Transport file handle (Telegram `file_id`). Only the current event's refs are ever fetched. */
87
+ readonly transportFileId: string;
88
+ readonly mimeType?: string;
89
+ readonly byteLength?: number;
90
+ readonly fileName?: string;
91
+ }
92
+
93
+ /** Bounded bytes returned by one attachment fetch; they never enter the journal or a reply. */
94
+ export interface ChannelAttachmentBytes {
95
+ readonly bytes: Uint8Array;
96
+ readonly mimeType?: string;
97
+ readonly fileName?: string;
98
+ }
99
+
100
+ export interface ChannelAuthorizeInput {
101
+ readonly connectionId: string;
102
+ readonly externalConversationId: string;
103
+ readonly externalActorId: string;
104
+ readonly eventId: string;
105
+ /** Bounded inbound text (the channel input cap is enforced before this call). */
106
+ readonly text: string;
107
+ readonly action: ChannelAction;
108
+ readonly threadId?: string;
109
+ readonly receivedAt: string;
110
+ readonly claims?: Readonly<Record<string, unknown>>;
111
+ }
112
+
113
+ /**
114
+ * Host-verified grant for one observed sender. `identity` must satisfy
115
+ * `assertIdentityActive` (host-verified, unexpired, unrevoked); ownership is always
116
+ * derived with `ownershipFromIdentity`, never read from the event or from a narrowing guess.
117
+ */
118
+ export interface ChannelAuthorization {
119
+ readonly identity: AgentIdentity;
120
+ /** Host grant revision, re-read on every event; a changed revision is a new authorization. */
121
+ readonly grantRevision: string;
122
+ /**
123
+ * Opt-in for host-initiated notices (`notify`) to this actor.
124
+ * Missing is treated as `false`; inbound messages never need it.
125
+ */
126
+ readonly notifications?: boolean;
127
+ }
128
+
129
+ /**
130
+ * Host-initiated unicast notice. There is deliberately no fan-out field: the notice goes to
131
+ * exactly one already-bound conversation/thread pair owned by `identity` (a group thread with
132
+ * several bound actors, or any unbound pair, is denied). `notifyId` is the idempotency key.
133
+ */
134
+ export interface ChannelNotifyInput {
135
+ readonly identity: AgentIdentity;
136
+ readonly connectionId: string;
137
+ readonly externalConversationId: string;
138
+ readonly threadId?: string;
139
+ readonly notifyId: string;
140
+ readonly text: string;
141
+ }
142
+
143
+ export interface ChannelBindingInput {
144
+ readonly connectionId: string;
145
+ readonly externalConversationId: string;
146
+ readonly externalActorId: string;
147
+ readonly threadId?: string;
148
+ readonly identity: AgentIdentity;
149
+ readonly ownership: OwnershipScope;
150
+ readonly agentAlias?: string;
151
+ /** Incremented by `/new`; part of the default session derivation. */
152
+ readonly generation: number;
153
+ }
154
+
155
+ /** Owned Prism session (and optional branch leaf) for one binding. */
156
+ export interface ChannelBinding {
157
+ readonly sessionId: string;
158
+ readonly leafId?: string;
159
+ }
160
+
161
+ /** Opaque adapter presentation payload; values are server-issued controls, never model output. */
162
+ export interface ChannelReplyControl {
163
+ readonly label: string;
164
+ readonly value: string;
165
+ }
166
+
167
+ /** Outbound message addressed to the bound destination. */
168
+ export interface ChannelReply {
169
+ readonly connectionId: string;
170
+ readonly externalConversationId: string;
171
+ readonly text: string;
172
+ readonly kind: "final" | "notice";
173
+ readonly controls?: readonly ChannelReplyControl[];
174
+ /** Destination thread (Telegram `message_thread_id`); replies go to the topic the event came from. */
175
+ readonly threadId?: string;
176
+ /** Transport event/message id being answered, when known. */
177
+ readonly inReplyTo?: string;
178
+ }
179
+
180
+ export interface ChannelSendResult {
181
+ readonly delivered: boolean;
182
+ readonly messageId?: string;
183
+ /** Bounded reason when `delivered` is false (transport error class, not payload). */
184
+ readonly reason?: string;
185
+ }
186
+
187
+ /** Channel-imposed caps; store/platform ceilings stay below the hard caps recorded in Task 1. */
188
+ export interface ChannelLimits {
189
+ readonly maxInputBytes?: number;
190
+ readonly maxResponseBytes?: number;
191
+ readonly maxPendingPerBinding?: number;
192
+ readonly maxPendingPerProcess?: number;
193
+ readonly maxActiveSessions?: number;
194
+ readonly maxRoutes?: number;
195
+ readonly maxSeenEventsPerConnection?: number;
196
+ readonly stopDeadlineMs?: number;
197
+ /** Journal/reply retention in days; `prune` deletes older settled records. */
198
+ readonly retentionDays?: number;
199
+ /** Checkpoint list page size for journal sweeps. */
200
+ readonly maxJournalPage?: number;
201
+ /** Per-record bound on a journal value, enforced before save. */
202
+ readonly maxJournalRecordBytes?: number;
203
+ /** Lease TTL used when a `LeaseStore` is configured. */
204
+ readonly leaseTtlMs?: number;
205
+ /** Short-lived approval-control validity. */
206
+ readonly approvalTtlMs?: number;
207
+ /** Per-attachment byte ceiling for one `getFile` download (default 1 MiB, hard 4 MiB). */
208
+ readonly maxAttachmentBytes?: number;
209
+ }
210
+
211
+ export interface ResolvedChannelLimits {
212
+ readonly maxInputBytes: number;
213
+ readonly maxResponseBytes: number;
214
+ readonly maxPendingPerBinding: number;
215
+ readonly maxPendingPerProcess: number;
216
+ readonly maxActiveSessions: number;
217
+ readonly maxRoutes: number;
218
+ readonly maxSeenEventsPerConnection: number;
219
+ readonly stopDeadlineMs: number;
220
+ readonly retentionDays: number;
221
+ readonly maxJournalPage: number;
222
+ readonly maxJournalRecordBytes: number;
223
+ readonly leaseTtlMs: number;
224
+ readonly approvalTtlMs: number;
225
+ readonly maxAttachmentBytes: number;
226
+ }
227
+
228
+ /** Durable lifecycle of one admitted transport event. */
229
+ export type ChannelOperationState =
230
+ | "accepted"
231
+ | "executing"
232
+ | "succeeded"
233
+ | "failed"
234
+ | "cancelled"
235
+ | "suspended"
236
+ /** Dead-letter: never claimed, or explicitly reconciled without replay. */
237
+ | "abandoned"
238
+ /** Claimed work whose outcome cannot be proven after a crash; never replayed automatically. */
239
+ | "execution_unknown";
240
+
241
+ /** Durable delivery state of one staged reply. */
242
+ export type ChannelReplyState = "pending" | "delivered" | "delivery_failed" | "delivery_unknown";
243
+
244
+ /** Journal record for one admitted event; never carries inbound message text. */
245
+ export interface ChannelOperationRecord {
246
+ readonly operationId: string;
247
+ readonly eventId: string;
248
+ readonly kind: ChannelAction;
249
+ readonly connectionId: string;
250
+ readonly externalConversationId: string;
251
+ readonly externalActorId: string;
252
+ readonly threadId?: string;
253
+ readonly agentAlias?: string;
254
+ readonly sessionId?: string;
255
+ /** Core run correlation evidence (`RunResult.runId`), durable for reconciliation. */
256
+ readonly runId?: string;
257
+ readonly state: ChannelOperationState;
258
+ readonly replyStaged: boolean;
259
+ readonly attempts: number;
260
+ readonly createdAt: string;
261
+ readonly updatedAt: string;
262
+ /** Bounded error code/class only; message text is never persisted. */
263
+ readonly errorCode?: string;
264
+ }
265
+
266
+ /** Staged outbound reply; the only journal record that holds payload text, bounded and pruned. */
267
+ export interface ChannelReplyRecord {
268
+ readonly operationId: string;
269
+ readonly connectionId: string;
270
+ readonly externalConversationId: string;
271
+ readonly threadId?: string;
272
+ readonly kind: "final" | "notice";
273
+ readonly text: string;
274
+ readonly controls?: readonly ChannelReplyControl[];
275
+ readonly state: ChannelReplyState;
276
+ readonly attempts: number;
277
+ readonly messageId?: string;
278
+ readonly reason?: string;
279
+ readonly createdAt: string;
280
+ readonly updatedAt: string;
281
+ }
282
+
283
+ /**
284
+ * One operation that still needs host attention (no payload): an unresolved lifecycle state, or
285
+ * a settled operation whose reply was never confirmed (`pending`/`delivery_unknown`/`delivery_failed`).
286
+ */
287
+ export interface ChannelUnresolvedOperation {
288
+ readonly operationId: string;
289
+ readonly connectionId: string;
290
+ readonly state: ChannelOperationState;
291
+ readonly replyState?: ChannelReplyState;
292
+ readonly version: number;
293
+ readonly updatedAt: string;
294
+ }
295
+
296
+ export interface ChannelReconcileInput {
297
+ /** Verified caller identity; ownership is derived from it and must match the record exactly. */
298
+ readonly identity: AgentIdentity;
299
+ readonly connectionId: string;
300
+ readonly operationId: string;
301
+ /** Optimistic version read from `listUnresolved`; stale values are rejected. */
302
+ readonly expectedVersion: number;
303
+ /** Required when an effect may already have happened (unknown execution or ambiguous send). */
304
+ readonly acknowledgeDuplicateRisk?: boolean;
305
+ }
306
+
307
+ export type ChannelReconcileOutcome =
308
+ | "abandoned"
309
+ | "execution_unknown"
310
+ | "reply_delivered"
311
+ | "reply_failed"
312
+ /** The resend itself was ambiguous: the reply may or may not have landed. */
313
+ | "reply_unknown"
314
+ | "none";
315
+
316
+ export interface ChannelReconcileResult {
317
+ readonly status: "resolved" | "not_found" | "conflict" | "denied" | "unavailable";
318
+ readonly outcome?: ChannelReconcileOutcome;
319
+ readonly state?: ChannelOperationState;
320
+ /** Bounded explanation, never a raw error payload. */
321
+ readonly detail?: string;
322
+ }
323
+
324
+ export interface ChannelPruneResult {
325
+ readonly scanned: number;
326
+ readonly deleted: number;
327
+ readonly retained: number;
328
+ }
329
+
330
+ /** Bounded runtime counters; no message text, external ids, tokens or key material. */
331
+ export interface ChannelDiagnostics {
332
+ readonly admitted: number;
333
+ readonly denied: number;
334
+ readonly unsupported: number;
335
+ readonly duplicates: number;
336
+ readonly queued: number;
337
+ readonly active: number;
338
+ readonly completed: number;
339
+ readonly failed: number;
340
+ readonly cancelled: number;
341
+ readonly suspended: number;
342
+ readonly deliveries: number;
343
+ readonly deliveryFailures: number;
344
+ readonly truncated: number;
345
+ /** Journal writes/reads that failed; admission fails closed and is counted here. */
346
+ readonly storageFailures: number;
347
+ /** Lease acquisition/renewal failures, including deferrals to another receiver. */
348
+ readonly leaseLosses: number;
349
+ }
350
+
351
+ /**
352
+ * Adapter intake callback. Returning the optional `ChannelAdmission` lets an adapter retain its
353
+ * transport acknowledgement on capacity/storage failure; legacy callbacks may return nothing.
354
+ */
355
+ export type ChannelReceive = (event: ChannelInboundEvent) => unknown;
356
+
357
+ /**
358
+ * Cumulative assistant text observed so far in the current answer of one running turn. This is a
359
+ * *preview* seam: it is never journaled, never counted as a reply, and never replaces the
360
+ * terminal `ChannelReply` — an adapter may render it (Telegram drafts) or ignore it.
361
+ */
362
+ export interface ChannelAssistantDelta {
363
+ readonly connectionId: string;
364
+ readonly externalConversationId: string;
365
+ /** Present when the bound conversation is a thread (e.g. a forum topic). */
366
+ readonly threadId?: string;
367
+ /** Redacted cumulative text of the assistant message being produced; may be truncated by the adapter. */
368
+ readonly text: string;
369
+ }
370
+
371
+ /** Transport implementation contract. Adapters await `admit` before acknowledging receipt. */
372
+ export interface ChannelAdapter {
373
+ readonly connectionId: string;
374
+ readonly capabilities: ChannelCapabilities;
375
+ start(receive: ChannelReceive): Promise<void>;
376
+ send(reply: ChannelReply): Promise<ChannelSendResult>;
377
+ stop(): Promise<void>;
378
+ }
379
+
380
+ export interface ChannelDrainResult {
381
+ readonly settled: boolean;
382
+ readonly pending: number;
383
+ readonly completed: number;
384
+ readonly failed: number;
385
+ readonly cancelled: number;
386
+ }
387
+
388
+ export interface ChannelRuntimeOptions {
389
+ /** Maps an observed sender + action to a verified grant, or `false` when unknown/denied. */
390
+ readonly authorize?: (
391
+ input: ChannelAuthorizeInput,
392
+ ) => ChannelAuthorization | false | undefined | Promise<ChannelAuthorization | false | undefined>;
393
+ /** Host delivery seam, normally the adapter's `send`. */
394
+ readonly deliver: (reply: ChannelReply) => ChannelSendResult | Promise<ChannelSendResult>;
395
+ /** Host-owned binding resolver; defaults to a deterministic per-binding session id. */
396
+ readonly resolveBinding?: (input: ChannelBindingInput) => ChannelBinding | Promise<ChannelBinding>;
397
+ readonly limits?: ChannelLimits;
398
+ readonly redactor?: SecretRedactor;
399
+ /** Durable journal: bindings, operation dedup/CAS claim, intake cursor and reply staging. */
400
+ readonly checkpoints?: CheckpointStore;
401
+ /** Optional fencing: one worker per binding; a lost lease fails closed. */
402
+ readonly leases?: LeaseStore;
403
+ /**
404
+ * Opt-in live preview of the answer being produced by the current turn (cumulative, already
405
+ * redacted, same text the terminal reply will carry). Called only while a turn is running and
406
+ * never journaled.
407
+ */
408
+ readonly onAssistantDelta?: (delta: ChannelAssistantDelta) => void;
409
+ /**
410
+ * Host media seam, normally an adapter's own `fetchAttachment`. Called only with refs of the event
411
+ * being run, only for models that declare image input.
412
+ */
413
+ readonly fetchAttachment?: (ref: ChannelAttachmentRef) => Promise<ChannelAttachmentBytes | undefined | null>;
414
+ }
415
+
416
+ export interface ChannelRuntime {
417
+ /** Authorize and admit one event; resolves before the adapter acknowledges transport receipt. */
418
+ admit(event: ChannelInboundEvent): Promise<ChannelAdmission>;
419
+ /** Host-initiated unicast notice to an existing binding. */
420
+ notify(input: ChannelNotifyInput): Promise<ChannelAdmission>;
421
+ /** Wait for queued/running work to settle, up to `deadlineMs` (unbounded when omitted). */
422
+ drain(options?: { readonly deadlineMs?: number }): Promise<ChannelDrainResult>;
423
+ diagnostics(): ChannelDiagnostics;
424
+ /** Reject new admissions, cancel queued work, abort active runs, wait bounded for settle. */
425
+ stop(): Promise<void>;
426
+ /** Authorized resolution of one dead-letter/unknown operation or undelivered staged reply. */
427
+ reconcile(input: ChannelReconcileInput): Promise<ChannelReconcileResult>;
428
+ /** Bounded listing of unresolved (`accepted`/`executing`) operations in one ownership scope. */
429
+ listUnresolved(input: { readonly identity: AgentIdentity; readonly limit?: number }): Promise<readonly ChannelUnresolvedOperation[]>;
430
+ /** Delete settled journal records past retention; unresolved work is never pruned. */
431
+ prune(input: { readonly identity: AgentIdentity; readonly now?: string }): Promise<ChannelPruneResult>;
432
+ }
433
+
434
+ export interface ChannelConnectionHandle {
435
+ handle(update: unknown): Promise<unknown>;
436
+ start(): Promise<void>;
437
+ close(): Promise<void>;
438
+ stop(): Promise<void>;
439
+ drain(options?: { readonly deadlineMs?: number }): Promise<ChannelDrainResult>;
440
+ }
441
+
442
+ export { ChannelTokenLiteralError, CHANNEL_TOKEN_LITERAL_CODE } from "./secret-ref.js";
@@ -0,0 +1,92 @@
1
+ # @arnilo/prism-hosts/devtools
2
+
3
+ A loopback developer inspector over one Prism `Agent`. It reads the agent's own surface, `inspect()`,
4
+ `sessions`, `session.entries()`, and `subscribe()`, and serves it as a page and a small JSON API. It
5
+ starts no run, builds no agent, and imports only the public `@arnilo/prism` surface
6
+ ([allow-list](../../../scripts/host-surface-allowlist.json)).
7
+
8
+ ## Use
9
+
10
+ ```ts
11
+ import { createAgent } from "@arnilo/prism";
12
+ import { serveDevtools } from "@arnilo/prism-hosts/devtools";
13
+
14
+ const agent = await createAgent({ model, packages });
15
+ const devtools = serveDevtools(agent, {
16
+ port: 4311,
17
+ // Optional host/origin overrides (defaults to bound loopback pairs):
18
+ // allowedHosts: ["127.0.0.1:4311", "localhost:4311", "[::1]:4311"],
19
+ // allowedOrigins: ["http://127.0.0.1:4311", "http://localhost:4311", "http://[::1]:4311"],
20
+ });
21
+ console.log(devtools.url); // http://127.0.0.1:4311
22
+ ```
23
+
24
+ `serveDevtools` is synchronous and returns `{ url, hostname, port, close() }`. `close()` ends the live
25
+ event streams and the listener.
26
+
27
+ The `prism-devtools` bin serves a manifest-built agent:
28
+
29
+ ```bash
30
+ prism-devtools --model anthropic/claude-sonnet-4-5 --root . [--trust-project] [--port 4311]
31
+ ```
32
+
33
+ `--model` is `provider/model`. The project scope loads only with `--trust-project` (roadmap §2.7). The
34
+ bin binds loopback only; a remote bind is a programmatic `serveDevtools(agent, { hostname, token })` call.
35
+
36
+ ## Routes
37
+
38
+ | Route | Answers with |
39
+ | --- | --- |
40
+ | `GET /` | the page (strict CSP; no inline script) |
41
+ | `GET /api/inspect` | `agent.inspect()`, redacted |
42
+ | `GET /api/sessions?limit&cursor` | `agent.sessions.list()`, one page (`limit` 1–200) |
43
+ | `GET /api/sessions/:id` | `agent.sessions.get(id)`, or 404 |
44
+ | `GET /api/sessions/:id/entries` | `session.entries()` for the stored session, or 404 |
45
+ | `GET /api/replay?session&cursor&limit` | one page of the session's stored entries (`limit` 1–500); starts no run |
46
+ | `GET /api/events?session=` | server-sent events: `agent` for `agent.subscribe()`, and `session` for the session's `subscribe()` |
47
+ | `POST /api/compare` | `{ left, right }` metadata compared: winners and the invariant block |
48
+
49
+ Quality compares `aggregate.macroMean`. When both sides supply the same scorer ids and every scorer has `ci95: { low, high }`, a winner requires every interval to support that direction without overlap; overlap (including touching bounds) or conflicting directions gives `tie`. Missing intervals fall back to means. A failed invariant still blocks quality winners.
50
+
51
+ Unknown sessions answer 404 with `ERR_PRISM_DEVTOOLS_NOT_FOUND`. A malformed query answers 400 with
52
+ `ERR_PRISM_DEVTOOLS_QUERY`. Errors never carry an internal message.
53
+
54
+ ## What is not here
55
+
56
+ - **No prompt, decision, or run routes.** The inspector observes; it does not drive a run or resolve an
57
+ approval. Those belong to the host that owns the session.
58
+ - **No timeline panel.** The page renders raw entries and events. The timeline projector stays in
59
+ the 0.12 family package until Phase 16 moves it to `@arnilo/prism-extensions/observability`.
60
+ - **The session feed sees its own session object.** A `Session`'s subscribers belong to the instance that
61
+ emitted the events. The `?session=` feed follows the `Session` the route opened (`acrossRuns: true`), so a
62
+ run driven through a different instance of the same id is not visible through the public API. The agent
63
+ feed still carries `session.opened` and `session.closed`. A cross-instance session feed is a kernel
64
+ change, not a host one.
65
+ - **A session with no entries is not stored**, so it has no entries to replay and no stream route for it
66
+ until it has run once.
67
+
68
+ ## Security
69
+
70
+ - **Loopback by default.** `hostname` defaults to `127.0.0.1`. Any non-loopback `hostname` throws
71
+ `ERR_PRISM_DEVTOOLS_REMOTE_BIND` unless `token` is set, before a listener exists.
72
+ - **Host and Origin gate.** Every route validates the `Host` and `Origin` headers. By default, only bound loopback addresses (`127.0.0.1:<port>`, `localhost:<port>`, `[::1]:<port>`) and loopback origins are allowed, blocking DNS-rebinding attacks from browser pages against loopback inspectors. Mismatched `Host` headers return 403 `ERR_PRISM_DEVTOOLS_FORBIDDEN_HOST`, and untrusted `Origin` headers return 403 `ERR_PRISM_DEVTOOLS_FORBIDDEN_ORIGIN`. `ServeDevtoolsOptions.allowedHosts` and `allowedOrigins` override the defaults for custom network topologies.
73
+ - **Tokens are refs.** `token` takes `env:NAME`, read from the environment at serve time. A literal token
74
+ throws `ERR_PRISM_DEVTOOLS_TOKEN_LITERAL`, and an unset ref throws `ERR_PRISM_DEVTOOLS_TOKEN_UNSET`.
75
+ - **Every route is guarded when a token is set**, the page included. The header is `Authorization: Bearer
76
+ <token>`, compared in constant time. A browser cannot send that header from the page, so a token-guarded
77
+ server is for programmatic clients; the page is for loopback use.
78
+ - **Redacted output.** Every JSON body and every SSE event passes the agent's redactor on the way out. A
79
+ secret the agent holds is not in any route's body; `devtools_entries_redacted` asserts this.
80
+
81
+ ## Bounds
82
+
83
+ - Replay pages are at most 500 entries; the page shows 100 at a time.
84
+ - The live feed keeps the newest 500 rows on screen. Each subscription uses the agent's bounded queue
85
+ (`SubscribeOptions.maxQueuedEvents`, default 1024).
86
+ - The browser module is transpiled once per process and cached. The package ships source, so there is no
87
+ build step and no `dist/`.
88
+
89
+ ## Tests
90
+
91
+ `bun test src` from this package covers the routes, the redaction, the token and loopback rules, the
92
+ replay paging, the bin serving a manifest-built agent, and the host-surface scan.
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * `prism-devtools`: serves the developer inspector over a manifest-built agent, on loopback.
4
+ *
5
+ * `--model provider/model` picks the provider the manifest packages registered. `--root` defaults to the
6
+ * current directory, and the project scope loads only with `--trust-project` (roadmap §2.7). The bin is
7
+ * loopback-only: a remote bind belongs to a programmatic `serveDevtools(agent, { hostname, token })` call.
8
+ */
9
+ import type { Agent } from "@arnilo/prism";
10
+ import { createAgent } from "@arnilo/prism";
11
+ import { loadManifest, ManifestError } from "@arnilo/prism/manifest";
12
+ import { type DevtoolsArgs, DevtoolsArgsError, parseDevtoolsArgs, serveDevtools } from "../src/index.js";
13
+
14
+ /** Assemble the served agent from the manifest. The only `createAgent` call in this package. */
15
+ export async function buildAgent(args: DevtoolsArgs): Promise<Agent> {
16
+ const packages = await loadManifest({
17
+ ...(args.root === undefined ? {} : { root: args.root }),
18
+ scopes: ["user", "project"],
19
+ ...(args.trustProject ? { trustProject: () => true } : {}),
20
+ });
21
+ return createAgent({ id: "prism-devtools", model: args.model, packages });
22
+ }
23
+
24
+ export async function main(argv: readonly string[]): Promise<number> {
25
+ let args: DevtoolsArgs;
26
+ try {
27
+ args = parseDevtoolsArgs(argv);
28
+ } catch (error) {
29
+ if (!(error instanceof DevtoolsArgsError)) throw error;
30
+ console.error(`prism-devtools: ${error.message}`);
31
+ return 1;
32
+ }
33
+
34
+ let agent: Agent;
35
+ try {
36
+ agent = await buildAgent(args);
37
+ } catch (error) {
38
+ const detail =
39
+ error instanceof ManifestError ? `${error.code}: ${error.message}` : error instanceof Error ? error.message : String(error);
40
+ console.error(`prism-devtools: ${detail}`);
41
+ return 1;
42
+ }
43
+
44
+ let devtools: ReturnType<typeof serveDevtools>;
45
+ try {
46
+ devtools = serveDevtools(agent, { port: args.port });
47
+ } catch (error) {
48
+ await agent.dispose();
49
+ console.error(`prism-devtools: ${error instanceof Error ? error.message : String(error)}`);
50
+ return 1;
51
+ }
52
+ console.log(`prism-devtools → ${devtools.url} (press Ctrl+C to stop)`);
53
+
54
+ await new Promise<void>((resolve) => {
55
+ process.once("SIGINT", resolve);
56
+ process.once("SIGTERM", resolve);
57
+ });
58
+ await devtools.close();
59
+ await agent.dispose();
60
+ return 0;
61
+ }
62
+
63
+ if (import.meta.main) process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Argument parsing for the `prism-devtools` binary. No agent construction here: `bin/prism-devtools.ts`
3
+ * owns `createAgent` and `serveDevtools`, so the host-surface gate sees the one construction site.
4
+ */
5
+ import { parseArgs } from "node:util";
6
+
7
+ export interface DevtoolsModel {
8
+ readonly provider: string;
9
+ readonly model: string;
10
+ }
11
+
12
+ export interface DevtoolsArgs {
13
+ /** Manifest root; defaults to the current directory. */
14
+ readonly root?: string;
15
+ readonly model: DevtoolsModel;
16
+ /** Without this, the project scope never loads (roadmap §2.7). */
17
+ readonly trustProject: boolean;
18
+ /** Loopback port. `0` picks a free one. */
19
+ readonly port: number;
20
+ }
21
+
22
+ export class DevtoolsArgsError extends Error {
23
+ constructor(message: string) {
24
+ super(message);
25
+ this.name = "DevtoolsArgsError";
26
+ }
27
+ }
28
+
29
+ /** `provider/model`; the model may contain slashes, the provider may not. */
30
+ function parseModel(value: string | undefined): DevtoolsModel {
31
+ if (value === undefined) throw new DevtoolsArgsError("--model is required (provider/model, e.g. anthropic/claude-sonnet-4-5)");
32
+ const slash = value.indexOf("/");
33
+ const provider = slash === -1 ? "" : value.slice(0, slash);
34
+ const model = slash === -1 ? "" : value.slice(slash + 1);
35
+ if (!provider || !model) throw new DevtoolsArgsError(`--model must be provider/model, got "${value}"`);
36
+ return { provider, model };
37
+ }
38
+
39
+ const DEFAULT_PORT = 4311;
40
+
41
+ function parsePort(value: string | undefined): number {
42
+ if (value === undefined) return DEFAULT_PORT;
43
+ const port = Number(value);
44
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
45
+ throw new DevtoolsArgsError(`--port must be an integer from 0 to 65535, got "${value}"`);
46
+ return port;
47
+ }
48
+
49
+ export function parseDevtoolsArgs(argv: readonly string[]): DevtoolsArgs {
50
+ let values: { root?: string; model?: string; "trust-project"?: boolean; port?: string };
51
+ try {
52
+ values = parseArgs({
53
+ args: [...argv],
54
+ options: {
55
+ root: { type: "string" },
56
+ model: { type: "string" },
57
+ "trust-project": { type: "boolean" },
58
+ port: { type: "string" },
59
+ },
60
+ allowPositionals: false,
61
+ }).values as typeof values;
62
+ } catch (error) {
63
+ throw new DevtoolsArgsError(error instanceof Error ? error.message : String(error));
64
+ }
65
+ return {
66
+ ...(values.root === undefined ? {} : { root: values.root }),
67
+ model: parseModel(values.model),
68
+ trustProject: values["trust-project"] === true,
69
+ port: parsePort(values.port),
70
+ };
71
+ }