@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,178 @@
1
+ // Plan 079 Task 3: restart-safe pairing. A pairing token is returned once, stored only as a
2
+ // SHA-256 hash, bound to exact ownership + external ids + grant revision, and consumed by CAS
3
+ // so a replay or a concurrent double consume can never bind twice. Confirmation stays in the
4
+ // trusted host interface; this store never sends the token anywhere.
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import type { OwnershipScope } from "@arnilo/prism";
7
+ import type { CheckpointStore } from "./checkpoint-contract.js";
8
+ import { CHANNEL_JOURNAL_NAMESPACES } from "./state.js";
9
+
10
+ /** Review section 6: 5 minutes, host-tightenable, never longer. */
11
+ export const DEFAULT_PAIRING_TTL_MS = 5 * 60_000;
12
+ export const HARD_PAIRING_TTL_MS = 5 * 60_000;
13
+ const TOKEN_BYTES = 32;
14
+
15
+ export interface ChannelPairingRecord {
16
+ readonly connectionId: string;
17
+ readonly externalConversationId: string;
18
+ readonly externalActorId: string;
19
+ readonly threadId?: string;
20
+ readonly agentAlias?: string;
21
+ readonly grantRevision: string;
22
+ readonly state: "pending" | "consumed";
23
+ readonly createdAt: string;
24
+ readonly expiresAt: string;
25
+ readonly consumedAt?: string;
26
+ }
27
+
28
+ export interface CreateChannelPairingInput extends OwnershipScope {
29
+ readonly connectionId: string;
30
+ readonly externalConversationId: string;
31
+ readonly externalActorId: string;
32
+ readonly threadId?: string;
33
+ readonly agentAlias?: string;
34
+ readonly grantRevision: string;
35
+ readonly ttlMs?: number;
36
+ readonly now?: string;
37
+ }
38
+
39
+ export interface ChannelPairingGrant {
40
+ /** Returned exactly once; the store keeps only its hash. */
41
+ readonly token: string;
42
+ readonly expiresAt: string;
43
+ /** The binding target the host applies after an authorized confirmation. */
44
+ readonly target: ChannelPairingRecord;
45
+ }
46
+
47
+ export interface ConsumeChannelPairingInput extends OwnershipScope {
48
+ readonly connectionId: string;
49
+ readonly token: string;
50
+ readonly now?: string;
51
+ }
52
+
53
+ export type ChannelPairingConsumption =
54
+ | { readonly status: "consumed"; readonly target: ChannelPairingRecord }
55
+ | { readonly status: "invalid" | "expired" | "already_consumed" };
56
+
57
+ export interface ChannelPairingStore {
58
+ /** Resolve a previously consumed pairing in the exact ownership scope. */
59
+ resolve(input: ConsumeChannelPairingInput): Promise<ChannelPairingRecord | null>;
60
+ create(input: CreateChannelPairingInput): Promise<ChannelPairingGrant>;
61
+ /** One-use: exactly one caller observes `consumed`; replay observes `already_consumed`. */
62
+ consume(input: ConsumeChannelPairingInput): Promise<ChannelPairingConsumption>;
63
+ }
64
+
65
+ export interface ChannelPairingStoreOptions {
66
+ readonly checkpoints: CheckpointStore;
67
+ }
68
+
69
+ function scopeTag(ownership: OwnershipScope): string {
70
+ return `${ownership.tenantId ?? "-"}:${ownership.accountId ?? "-"}:${ownership.userId ?? "-"}`;
71
+ }
72
+
73
+ function scopeOf(ownership: OwnershipScope): OwnershipScope {
74
+ return {
75
+ ...(ownership.tenantId === undefined ? {} : { tenantId: ownership.tenantId }),
76
+ ...(ownership.accountId === undefined ? {} : { accountId: ownership.accountId }),
77
+ ...(ownership.userId === undefined ? {} : { userId: ownership.userId }),
78
+ };
79
+ }
80
+
81
+ function hashToken(token: string): string {
82
+ return createHash("sha256").update(token).digest("hex");
83
+ }
84
+
85
+ function pairingKey(ownership: OwnershipScope, connectionId: string, tokenHash: string): string {
86
+ return ["p1", connectionId || "-", scopeTag(ownership), tokenHash.slice(0, 40)].join(":");
87
+ }
88
+
89
+ export function createChannelPairingStore(options: ChannelPairingStoreOptions): ChannelPairingStore {
90
+ const { checkpoints } = options;
91
+
92
+ async function load(ownership: OwnershipScope, connectionId: string, token: string) {
93
+ const tokenHash = hashToken(token);
94
+ const stored = await checkpoints.loadCheckpoint({
95
+ namespace: CHANNEL_JOURNAL_NAMESPACES.control,
96
+ key: pairingKey(ownership, connectionId, tokenHash),
97
+ ...scopeOf(ownership),
98
+ });
99
+ if (stored === null) return null;
100
+ const record = stored.value as ChannelPairingRecord;
101
+ if (record.connectionId !== connectionId) return null;
102
+ return { version: stored.version, record, tokenHash };
103
+ }
104
+
105
+ return {
106
+ async resolve(input) {
107
+ const found = await load(input, input.connectionId, input.token);
108
+ if (found === null) return null;
109
+ const r = found.record;
110
+ if (
111
+ r.state !== "consumed" ||
112
+ typeof r.externalConversationId !== "string" ||
113
+ !r.externalConversationId ||
114
+ typeof r.externalActorId !== "string" ||
115
+ !r.externalActorId ||
116
+ typeof r.grantRevision !== "string" ||
117
+ !r.grantRevision ||
118
+ (r.threadId !== undefined && typeof r.threadId !== "string")
119
+ )
120
+ return null;
121
+ return r;
122
+ },
123
+ async create(input) {
124
+ const ttl = Math.min(Math.max(1_000, input.ttlMs ?? DEFAULT_PAIRING_TTL_MS), HARD_PAIRING_TTL_MS);
125
+ const now = input.now ?? new Date().toISOString();
126
+ const token = randomBytes(TOKEN_BYTES).toString("base64url");
127
+ const record: ChannelPairingRecord = {
128
+ connectionId: input.connectionId,
129
+ externalConversationId: input.externalConversationId,
130
+ externalActorId: input.externalActorId,
131
+ ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
132
+ agentAlias: input.agentAlias ?? "default",
133
+ grantRevision: input.grantRevision,
134
+ state: "pending",
135
+ createdAt: now,
136
+ expiresAt: new Date(Date.parse(now) + ttl).toISOString(),
137
+ };
138
+ await checkpoints.saveCheckpoint({
139
+ namespace: CHANNEL_JOURNAL_NAMESPACES.control,
140
+ key: pairingKey(input, input.connectionId, hashToken(token)),
141
+ ...scopeOf(input),
142
+ category: "channel-control",
143
+ expectedVersion: 0,
144
+ version: 1,
145
+ value: record,
146
+ });
147
+ return { token, expiresAt: record.expiresAt, target: record };
148
+ },
149
+
150
+ async consume(input) {
151
+ const found = await load(input, input.connectionId, input.token);
152
+ if (found === null) return { status: "invalid" };
153
+ if (found.record.state === "consumed") return { status: "already_consumed" };
154
+ const now = input.now ?? new Date().toISOString();
155
+ if (Date.parse(found.record.expiresAt) <= Date.parse(now)) return { status: "expired" };
156
+ const consumed: ChannelPairingRecord = {
157
+ ...found.record,
158
+ state: "consumed",
159
+ consumedAt: now,
160
+ };
161
+ try {
162
+ const saved = await checkpoints.saveCheckpoint({
163
+ namespace: CHANNEL_JOURNAL_NAMESPACES.control,
164
+ key: pairingKey(input, input.connectionId, found.tokenHash),
165
+ ...scopeOf(input),
166
+ category: "channel-control",
167
+ expectedVersion: found.version,
168
+ version: found.version + 1,
169
+ value: consumed,
170
+ });
171
+ return { status: "consumed", target: saved.value as ChannelPairingRecord };
172
+ } catch (error) {
173
+ if (error instanceof Error && error.name === "CheckpointConflictError") return { status: "already_consumed" };
174
+ throw error;
175
+ }
176
+ },
177
+ };
178
+ }
@@ -0,0 +1,389 @@
1
+ import { createHash } from "node:crypto";
2
+ import { type OwnershipScope } from "@arnilo/prism";
3
+ import type { RuntimeCore } from "./runtime-core.js";
4
+ import type { RuntimeTurn } from "./runtime-turn.js";
5
+ import { COMMAND_NAMES, HELP_TEXT, MAX_ID_BYTES, type RouteState, type RuntimeContext, type Turn } from "./runtime-types.js";
6
+ import type { ChannelBindingRecord } from "./state.js";
7
+ import type { ChannelAction, ChannelAdmission, ChannelAuthorization, ChannelInboundEvent, ChannelNotifyInput } from "./types.js";
8
+ import { type AgentIdentity, ownershipFromIdentity } from "./identity.js";
9
+ export function createRuntimeAdmit(ctx: RuntimeContext, core: RuntimeCore, turnRuntime: RuntimeTurn) {
10
+ const { approvals, counters, journal, limits, routes } = ctx;
11
+ const {
12
+ alreadySeen,
13
+ authorizeEvent,
14
+ beginOperation,
15
+ bindingKeyFor,
16
+ declaredAttachmentBytes,
17
+ denial,
18
+ dropOperation,
19
+ ensureRoute,
20
+ hydrateRoute,
21
+ identityActive,
22
+ key,
23
+ nowIso,
24
+ pendingCount,
25
+ redact,
26
+ resolveAlias,
27
+ resolveNewSessionId,
28
+ settleOperation,
29
+ track,
30
+ unsupported,
31
+ validEvent,
32
+ } = core;
33
+ const { approvalFromEvent, commandNotice, enqueue, notify, sameOwnership, startResume } = turnRuntime;
34
+ async function handleApproval(event: ChannelInboundEvent, authorization: ChannelAuthorization, turn: Turn): Promise<ChannelAdmission> {
35
+ const control = approvalFromEvent(event);
36
+ if (control === undefined || approvals === undefined) return denial(control === undefined ? "rejected" : "unavailable");
37
+ let stored: Awaited<ReturnType<typeof approvals.load>>;
38
+ try {
39
+ stored = await approvals.load({ ownership: turn.ownership, connectionId: event.connectionId, token: control.token });
40
+ } catch {
41
+ counters.storageFailures += 1;
42
+ return denial("unavailable");
43
+ }
44
+ if (stored === null) return denial("rejected");
45
+ const record = stored.record;
46
+ if (
47
+ record.state !== "pending" ||
48
+ Date.parse(record.expiresAt) <= Date.now() ||
49
+ record.outcome !== control.outcome ||
50
+ record.connectionId !== event.connectionId ||
51
+ record.externalConversationId !== event.externalConversationId ||
52
+ record.externalActorId !== event.externalActorId ||
53
+ record.threadId !== event.threadId ||
54
+ record.principalKind !== authorization.identity.principal.kind ||
55
+ record.principalId !== authorization.identity.principal.id ||
56
+ record.grantRevision !== authorization.grantRevision
57
+ ) {
58
+ return denial("rejected");
59
+ }
60
+ const route = ensureRoute(event, record.agentAlias ?? "default");
61
+ if (route === undefined) return denial("capacity");
62
+ if ((await hydrateRoute(route, turn)) === "unavailable") return denial("unavailable");
63
+ const suspended = route.suspendedRun;
64
+ if (
65
+ route.resuming ||
66
+ (!route.suspended && suspended === undefined) ||
67
+ (suspended !== undefined && (suspended.runId !== record.runId || suspended.sessionId !== record.sessionId)) ||
68
+ !sameOwnership(turn.ownership, ownershipFromIdentity(authorization.identity))
69
+ ) {
70
+ return denial("rejected");
71
+ }
72
+ try {
73
+ const consumed = await approvals.consume({
74
+ ownership: turn.ownership,
75
+ connectionId: event.connectionId,
76
+ token: control.token,
77
+ expectedVersion: stored.version,
78
+ });
79
+ if (consumed !== "consumed") return denial("rejected");
80
+ await settleOperation(turn, "succeeded");
81
+ startResume(route, turn, [{ approvalId: record.approvalId, outcome: record.outcome }], "approval", record);
82
+ counters.admitted += 1;
83
+ return { status: "accepted" };
84
+ } catch {
85
+ counters.storageFailures += 1;
86
+ return denial("unavailable");
87
+ }
88
+ }
89
+
90
+ async function handleCommand(event: ChannelInboundEvent, _authorization: ChannelAuthorization, turn: Turn): Promise<ChannelAdmission> {
91
+ const match = /^\/([A-Za-z0-9_]+)(?:\s+([\s\S]*))?$/.exec(event.text.trim());
92
+ if (match === null || !COMMAND_NAMES.has(match[1].toLowerCase())) return unsupported("unknown_command");
93
+ const name = match[1].toLowerCase();
94
+
95
+ if (name === "help") {
96
+ commandNotice(turn, HELP_TEXT);
97
+ counters.admitted += 1;
98
+ return { status: "accepted" };
99
+ }
100
+
101
+ const route = ensureRoute(event, turn.alias);
102
+ if (route === undefined) return denial("capacity");
103
+ if (route !== undefined && (await hydrateRoute(route, turn)) === "unavailable") return denial("unavailable");
104
+ if (name === "status") {
105
+ const state =
106
+ route === undefined
107
+ ? "idle"
108
+ : route.resuming
109
+ ? "resuming"
110
+ : route.active !== undefined
111
+ ? "running"
112
+ : route.suspended
113
+ ? "awaiting decision"
114
+ : route.queue.length > 0
115
+ ? `queued (${route.queue.length})`
116
+ : "idle";
117
+ commandNotice(turn, `Agent: ${route?.alias ?? turn.alias}; state: ${state}.`);
118
+ counters.admitted += 1;
119
+ return { status: "accepted" };
120
+ }
121
+ if (name === "new") {
122
+ if (route === undefined) return denial("capacity");
123
+ if (route.suspended) {
124
+ commandNotice(turn, "Resolve or cancel the suspended request before starting a new conversation.");
125
+ counters.admitted += 1;
126
+ return { status: "accepted" };
127
+ }
128
+ if (route.active !== undefined || route.queue.length > 0) {
129
+ commandNotice(turn, "Finish or cancel the current request before starting a new conversation.");
130
+ counters.admitted += 1;
131
+ return { status: "accepted" };
132
+ }
133
+ if (journal !== undefined && route.sessionId !== undefined) {
134
+ const nextGeneration = route.generation + 1;
135
+ const record: ChannelBindingRecord = {
136
+ sessionId: await resolveNewSessionId(turn, route, route.generation + 1),
137
+ agentAlias: route.alias,
138
+ generation: nextGeneration,
139
+ suspended: false,
140
+ updatedAt: nowIso(),
141
+ };
142
+ let saved = await journal
143
+ .saveBinding(bindingKeyFor(route, turn.ownership), record, route.bindingVersion ?? 0, route.lease?.fencingToken)
144
+ .catch(() => null);
145
+ if (saved === null) {
146
+ const current = await journal.loadBinding(bindingKeyFor(route, turn.ownership)).catch(() => null);
147
+ saved =
148
+ current === null
149
+ ? null
150
+ : await journal
151
+ .saveBinding(bindingKeyFor(route, turn.ownership), record, current.version, route.lease?.fencingToken)
152
+ .catch(() => null);
153
+ }
154
+ if (saved === null) {
155
+ counters.storageFailures += 1;
156
+ commandNotice(turn, "Could not start a new conversation. Try again.");
157
+ return denial("unavailable");
158
+ }
159
+ route.bindingVersion = saved.version;
160
+ }
161
+ route.generation += 1;
162
+ route.sessionId = undefined;
163
+ route.leafId = undefined;
164
+ route.suspended = false;
165
+ commandNotice(turn, "Started a new conversation.");
166
+ counters.admitted += 1;
167
+ return { status: "accepted" };
168
+ }
169
+ // cancel
170
+ if (route?.suspended && !route.resuming && route.suspendedRun !== undefined) {
171
+ try {
172
+ await settleOperation(turn, "succeeded");
173
+ const approvalId = (route.suspendedRun as { approvalId?: string }).approvalId ?? "cancel";
174
+ startResume(route, turn, [{ approvalId, outcome: "reject_once" }], "command");
175
+ counters.admitted += 1;
176
+ return { status: "accepted" };
177
+ } catch {
178
+ return denial("unavailable");
179
+ }
180
+ }
181
+ const active = route?.active;
182
+ const queued = (route?.queue ?? []).filter((turn_) => !turn_.cancelled);
183
+ if (active?.controller !== undefined) active.controller.abort(new Error("Channel user cancelled the request"));
184
+ for (const queuedTurn of queued) {
185
+ queuedTurn.cancelled = true;
186
+ track(settleOperation(queuedTurn, "cancelled", { errorCode: "cancelled_while_queued" }));
187
+ }
188
+ const suffix = queued.length === 1 ? "" : "s";
189
+ if (active?.controller !== undefined && queued.length > 0) {
190
+ commandNotice(turn, `Cancelling the current request and ${queued.length} queued request${suffix}.`);
191
+ } else if (active?.controller !== undefined) {
192
+ commandNotice(turn, "Cancelling the current request.");
193
+ } else if (queued.length > 0) {
194
+ commandNotice(turn, `Cancelled ${queued.length} queued request${suffix}.`);
195
+ } else {
196
+ commandNotice(turn, "Nothing to cancel.");
197
+ }
198
+ counters.admitted += 1;
199
+ return { status: "accepted" };
200
+ }
201
+
202
+ /**
203
+ * Validate host-supplied notify input. Ids only: nothing here is used as a destination, and
204
+ * `text` reaches the bound conversation alone (redacted, bounded by the reply cap).
205
+ */
206
+ function validNotifyInput(input: ChannelNotifyInput): boolean {
207
+ if (input === null || typeof input !== "object") return false;
208
+ if (typeof input.text !== "string" || input.text.trim().length === 0) return false;
209
+ if (input.threadId !== undefined && !boundedId(input.threadId)) return false;
210
+ return boundedId(input.connectionId) && boundedId(input.externalConversationId) && boundedId(input.notifyId, 8);
211
+ }
212
+
213
+ function boundedId(value: string, reserved = 0): boolean {
214
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= MAX_ID_BYTES - reserved;
215
+ }
216
+
217
+ /**
218
+ * The one already-bound route this notice may address: exact destination, same ownership (when
219
+ * the route recorded it), and never a guess. Several bindings for one owned pair (the host moved
220
+ * the conversation to another alias) resolve to the current selection or fail closed — notify is
221
+ * unicast to a bound pair and has no fan-out.
222
+ */
223
+ function notifyRoute(input: ChannelNotifyInput, ownership: OwnershipScope): RouteState | undefined {
224
+ const candidates: RouteState[] = [];
225
+ for (const route of routes.values()) {
226
+ if (route.connectionId !== input.connectionId) continue;
227
+ if (route.externalConversationId !== input.externalConversationId) continue;
228
+ if (route.threadId !== input.threadId) continue;
229
+ if (route.ownershipHint !== undefined && !sameOwnership(route.ownershipHint, ownership)) continue;
230
+ candidates.push(route);
231
+ }
232
+ return candidates[0];
233
+ }
234
+
235
+ function samePrincipal(left: AgentIdentity, right: AgentIdentity): boolean {
236
+ return left.principal.kind === right.principal.kind && left.principal.id === right.principal.id;
237
+ }
238
+
239
+ /**
240
+ * Host-initiated unicast notice: authorize the notification action for the bound actor, confirm
241
+ * the caller's identity is the one that grant names, and reuse the notice reply path (staged
242
+ * reply → `deliver`) without ever starting an agent run or touching the turn queue.
243
+ */
244
+ async function notifyBinding(input: ChannelNotifyInput): Promise<ChannelAdmission> {
245
+ if (ctx.stopped) return denial("stopped");
246
+ if (!validNotifyInput(input)) return denial("malformed");
247
+ if (!identityActive(input.identity)) return denial("revoked");
248
+ let ownership: OwnershipScope;
249
+ try {
250
+ ownership = ownershipFromIdentity(input.identity);
251
+ } catch {
252
+ return denial("malformed");
253
+ }
254
+ const route = notifyRoute(input, ownership);
255
+ if (route === undefined) return denial("rejected");
256
+ const event: ChannelInboundEvent = {
257
+ connectionId: route.connectionId,
258
+ externalConversationId: route.externalConversationId,
259
+ externalActorId: route.externalActorId,
260
+ ...(route.threadId === undefined ? {} : { threadId: route.threadId }),
261
+ eventId: `notify-${input.notifyId}`,
262
+ text: "",
263
+ };
264
+ const authorization = await authorizeEvent(event, "notify");
265
+ if ("status" in authorization) return authorization;
266
+ if (authorization.notifications !== true) return denial("rejected");
267
+ if (!samePrincipal(authorization.identity, input.identity)) return denial("rejected");
268
+ if (!sameOwnership(ownershipFromIdentity(authorization.identity), ownership)) return denial("rejected");
269
+ const operationId = `chan-op-${createHash("sha256")
270
+ .update(
271
+ key([
272
+ "notify",
273
+ route.connectionId,
274
+ ownership.tenantId,
275
+ ownership.accountId,
276
+ ownership.userId,
277
+ route.externalActorId,
278
+ route.alias,
279
+ input.notifyId,
280
+ ]),
281
+ )
282
+ .digest("hex")
283
+ .slice(0, 32)}`;
284
+ const turn: Turn = { event, authorization, ownership, alias: route.alias, operationId, cancelled: false };
285
+ const hydrated = await hydrateRoute(route, turn, false);
286
+ if (hydrated === "unavailable") return denial("unavailable");
287
+ if (hydrated === "missing") return denial("rejected");
288
+ if (pendingCount() >= limits.maxPendingPerProcess) return denial("capacity");
289
+ if (journal !== undefined) {
290
+ const begun = await beginOperation(turn, "notify", { advanceCursor: false });
291
+ if (begun === "unavailable") return denial("unavailable");
292
+ if (begun === "duplicate") {
293
+ counters.duplicates += 1;
294
+ counters.admitted += 1;
295
+ return { status: "accepted", operationId, duplicate: true };
296
+ }
297
+ } else if (alreadySeen(event)) {
298
+ counters.duplicates += 1;
299
+ counters.admitted += 1;
300
+ return { status: "accepted", operationId, duplicate: true };
301
+ }
302
+ await notify(turn, redact(input.text));
303
+ await settleOperation(turn, "succeeded");
304
+ counters.admitted += 1;
305
+ return { status: "accepted", operationId };
306
+ }
307
+
308
+ async function admit(event: ChannelInboundEvent): Promise<ChannelAdmission> {
309
+ if (ctx.stopped) return denial("stopped");
310
+ if (!validEvent(event)) return denial("malformed");
311
+ if (Buffer.byteLength(event.text, "utf8") > limits.maxInputBytes) return denial("oversized");
312
+ if (declaredAttachmentBytes(event) > limits.maxAttachmentBytes) return denial("oversized");
313
+ const control = approvalFromEvent(event);
314
+ const isCommand = control === undefined && event.text.trimStart().startsWith("/");
315
+ const action: ChannelAction = control === undefined ? (isCommand ? "command" : "message") : "approval";
316
+ const authorization = await authorizeEvent(event, action);
317
+ if ("status" in authorization) return authorization;
318
+
319
+ const alias = resolveAlias(event, authorization);
320
+ if (alias === undefined) return denial("rejected");
321
+ const ownership = ownershipFromIdentity(authorization.identity);
322
+ const operationId = `chan-op-${createHash("sha256")
323
+ .update(key([event.connectionId, event.eventId]))
324
+ .digest("hex")
325
+ .slice(0, 32)}`;
326
+ const turn: Turn = { event, authorization, ownership, alias, operationId, cancelled: false };
327
+
328
+ if (journal !== undefined) {
329
+ const begun = await beginOperation(turn, action);
330
+ if (begun === "unavailable") return denial("unavailable");
331
+ if (begun === "duplicate") {
332
+ counters.duplicates += 1;
333
+ counters.admitted += 1;
334
+ return { status: "accepted", operationId, duplicate: true };
335
+ }
336
+ } else if (isCommand === false && alreadySeen(event)) {
337
+ counters.duplicates += 1;
338
+ counters.admitted += 1;
339
+ return { status: "accepted", operationId, duplicate: true };
340
+ }
341
+
342
+ try {
343
+ if (action === "approval") {
344
+ const outcome = await handleApproval(event, authorization, turn);
345
+ if (outcome.status === "accepted") await settleOperation(turn, "succeeded");
346
+ else await dropOperation(turn);
347
+ return outcome;
348
+ }
349
+ if (isCommand) {
350
+ const outcome = await handleCommand(event, authorization, turn);
351
+ if (outcome.status === "accepted") {
352
+ await settleOperation(turn, "succeeded");
353
+ if (turn.opRecord !== undefined && turn.opRecord.state === "accepted") counters.storageFailures += 1;
354
+ } else {
355
+ await dropOperation(turn); // denied or unsupported commands stay retryable
356
+ }
357
+ return outcome;
358
+ }
359
+
360
+ const route = ensureRoute(event, alias);
361
+ if (route === undefined) {
362
+ await dropOperation(turn);
363
+ return denial("capacity");
364
+ }
365
+ if ((await hydrateRoute(route, turn)) === "unavailable") {
366
+ await dropOperation(turn);
367
+ return denial("unavailable");
368
+ }
369
+ if (route.suspended) {
370
+ track(notify(turn, "A previous request is awaiting an operator decision."));
371
+ await dropOperation(turn);
372
+ return denial("awaiting_decision");
373
+ }
374
+ if (route.queue.length >= limits.maxPendingPerBinding || pendingCount() >= limits.maxPendingPerProcess) {
375
+ await dropOperation(turn);
376
+ return denial("capacity");
377
+ }
378
+ enqueue(route, turn, ownership);
379
+ counters.admitted += 1;
380
+ return { status: "accepted", operationId };
381
+ } catch (error) {
382
+ await dropOperation(turn).catch(() => undefined);
383
+ counters.failed += 1;
384
+ return denial(error instanceof TypeError ? "malformed" : "unavailable");
385
+ }
386
+ }
387
+
388
+ return { admit, notifyBinding };
389
+ }