@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,621 @@
1
+ import { createHash } from "node:crypto";
2
+ import { type OwnershipScope } from "@arnilo/prism";
3
+ import type { ChannelReplyKeyInput } from "./delivery.js";
4
+ import {
5
+ MAX_ATTACHMENT_META_BYTES,
6
+ MAX_ATTACHMENT_REFS,
7
+ MAX_ID_BYTES,
8
+ type RouteState,
9
+ type RuntimeContext,
10
+ TRUNCATION_MARKER,
11
+ type Turn,
12
+ } from "./runtime-types.js";
13
+ import {
14
+ CHANNEL_JOURNAL_NAMESPACES,
15
+ type ChannelBindingKeyInput,
16
+ type ChannelBindingRecord,
17
+ type ChannelOperationKeyInput,
18
+ type StoredChannelRecord,
19
+ } from "./state.js";
20
+ import type {
21
+ ChannelAction,
22
+ ChannelAdmission,
23
+ ChannelAttachmentRef,
24
+ ChannelAuthorization,
25
+ ChannelAuthorizeInput,
26
+ ChannelBinding,
27
+ ChannelBindingInput,
28
+ ChannelDenialReason,
29
+ ChannelInboundEvent,
30
+ ChannelOperationRecord,
31
+ ChannelOperationState,
32
+ ChannelUnsupportedReason,
33
+ } from "./types.js";
34
+ import { type AgentIdentity, assertIdentityActive } from "./identity.js";
35
+ export function createRuntimeCore(ctx: RuntimeContext) {
36
+ const { counters, inflight, journal, leaseOwnerId, limits, options, redactor, routes, seenEvents, slotWaiters } = ctx;
37
+ function key(parts: readonly (string | undefined)[]): string {
38
+ return parts.map((part) => part ?? "").join("\u0000");
39
+ }
40
+
41
+ function actorKey(event: ChannelInboundEvent): string {
42
+ return key([event.connectionId, event.externalConversationId, event.threadId, event.externalActorId]);
43
+ }
44
+
45
+ function nowIso(): string {
46
+ return new Date().toISOString();
47
+ }
48
+
49
+ function boundText(text: string, maxBytes: number): string {
50
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) return text;
51
+ counters.truncated += 1;
52
+ const head = Buffer.from(text, "utf8")
53
+ .subarray(0, Math.max(0, maxBytes - Buffer.byteLength(TRUNCATION_MARKER, "utf8")))
54
+ .toString("utf8")
55
+ .replace(/\uFFFD*$/, "");
56
+ return `${head}${TRUNCATION_MARKER}`;
57
+ }
58
+
59
+ function redact(text: string): string {
60
+ return redactor === undefined ? text : redactor.redact(text);
61
+ }
62
+
63
+ function denial(reason: ChannelDenialReason): ChannelAdmission {
64
+ counters.denied += 1;
65
+ return { status: "denied", reason };
66
+ }
67
+
68
+ function unsupported(reason: ChannelUnsupportedReason): ChannelAdmission {
69
+ counters.unsupported += 1;
70
+ return { status: "unsupported", reason };
71
+ }
72
+
73
+ function identityActive(identity: AgentIdentity): boolean {
74
+ try {
75
+ assertIdentityActive(identity);
76
+ return true;
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ function validEvent(event: ChannelInboundEvent): boolean {
83
+ for (const value of [event.connectionId, event.externalConversationId, event.externalActorId, event.eventId]) {
84
+ if (typeof value !== "string" || value.length === 0) return false;
85
+ }
86
+ if (typeof event.text !== "string") return false;
87
+ if (
88
+ event.approval !== undefined &&
89
+ (typeof event.approval.token !== "string" ||
90
+ !/^[A-Za-z0-9_-]{32,64}$/.test(event.approval.token) ||
91
+ (event.approval.outcome !== "allow_once" && event.approval.outcome !== "reject_once"))
92
+ ) {
93
+ return false;
94
+ }
95
+ if (event.threadId !== undefined && typeof event.threadId !== "string") return false;
96
+ if (event.attachments !== undefined && !validAttachments(event.attachments)) return false;
97
+ const ids = [event.connectionId, event.externalConversationId, event.externalActorId, event.eventId, event.threadId];
98
+ return ids.every((value) => value === undefined || Buffer.byteLength(value, "utf8") <= MAX_ID_BYTES);
99
+ }
100
+
101
+ /** Sum of transport-declared attachment sizes; the adapter still bounds the actual body it reads. */
102
+ function declaredAttachmentBytes(event: ChannelInboundEvent): number {
103
+ let total = 0;
104
+ for (const ref of event.attachments ?? []) total += ref.byteLength ?? 0;
105
+ return total;
106
+ }
107
+
108
+ /** Attachment *references* only: bounded count, bounded metadata, no bytes and no URLs. */
109
+ function validAttachments(attachments: readonly ChannelAttachmentRef[]): boolean {
110
+ if (!Array.isArray(attachments) || attachments.length > MAX_ATTACHMENT_REFS) return false;
111
+ return attachments.every((ref) => {
112
+ if (ref === null || typeof ref !== "object") return false;
113
+ if (ref.kind !== "image" && ref.kind !== "document" && ref.kind !== "voice") return false;
114
+ if (typeof ref.transportFileId !== "string" || ref.transportFileId.length === 0) return false;
115
+ if (Buffer.byteLength(ref.transportFileId, "utf8") > MAX_ID_BYTES) return false;
116
+ if (
117
+ ref.mimeType !== undefined &&
118
+ (typeof ref.mimeType !== "string" || Buffer.byteLength(ref.mimeType, "utf8") > MAX_ATTACHMENT_META_BYTES)
119
+ ) {
120
+ return false;
121
+ }
122
+ if (
123
+ ref.fileName !== undefined &&
124
+ (typeof ref.fileName !== "string" || Buffer.byteLength(ref.fileName, "utf8") > MAX_ATTACHMENT_META_BYTES)
125
+ ) {
126
+ return false;
127
+ }
128
+ return ref.byteLength === undefined || (Number.isSafeInteger(ref.byteLength) && ref.byteLength >= 0);
129
+ });
130
+ }
131
+
132
+ async function authorizeEvent(event: ChannelInboundEvent, action: ChannelAction): Promise<ChannelAuthorization | ChannelAdmission> {
133
+ const input: ChannelAuthorizeInput = {
134
+ connectionId: event.connectionId,
135
+ externalConversationId: event.externalConversationId,
136
+ externalActorId: event.externalActorId,
137
+ eventId: event.eventId,
138
+ text: event.text,
139
+ action,
140
+ ...(event.threadId === undefined ? {} : { threadId: event.threadId }),
141
+ receivedAt: event.receivedAt ?? new Date().toISOString(),
142
+ ...(event.claims === undefined ? {} : { claims: event.claims }),
143
+ };
144
+ let result: ChannelAuthorization | false | undefined;
145
+ if (options.authorize) {
146
+ try {
147
+ result = await options.authorize(input);
148
+ } catch {
149
+ return denial("authorization_failed");
150
+ }
151
+ if (!result || result.identity === undefined) return denial("rejected");
152
+ if (!identityActive(result.identity)) return denial("revoked");
153
+ if (typeof result.grantRevision !== "string" || result.grantRevision.length === 0) return denial("rejected");
154
+ return result;
155
+ }
156
+ const tenantId = ctx.agent.config?.ownership?.tenantId ?? "default";
157
+ const userId = ctx.agent.config?.ownership?.userId ?? event.externalActorId;
158
+ const accountId = ctx.agent.config?.ownership?.accountId;
159
+ return {
160
+ identity: {
161
+ tenantId,
162
+ ...(accountId ? { accountId } : {}),
163
+ userId,
164
+ principal: { kind: "user", id: event.externalActorId },
165
+ scopes: ["chat"],
166
+ issuedAt: new Date(0).toISOString(),
167
+ verified: true,
168
+ },
169
+ grantRevision: "1",
170
+ };
171
+ }
172
+
173
+ function recentEvents(connectionId: string): { ids: Set<string>; order: string[] } {
174
+ let entry = seenEvents.get(connectionId);
175
+ if (!entry) {
176
+ if (seenEvents.size >= limits.maxRoutes) return { ids: new Set(), order: [] };
177
+ entry = { ids: new Set(), order: [] };
178
+ seenEvents.set(connectionId, entry);
179
+ }
180
+ return entry;
181
+ }
182
+
183
+ function alreadySeen(event: ChannelInboundEvent): boolean {
184
+ const entry = recentEvents(event.connectionId);
185
+ if (entry.ids.has(event.eventId)) return true;
186
+ entry.ids.add(event.eventId);
187
+ entry.order.push(event.eventId);
188
+ while (entry.order.length > limits.maxSeenEventsPerConnection) {
189
+ const oldest = entry.order.shift();
190
+ if (oldest !== undefined) entry.ids.delete(oldest);
191
+ }
192
+ return false;
193
+ }
194
+
195
+ function pendingCount(): number {
196
+ let pending = 0;
197
+ for (const route of routes.values()) pending += route.queue.length;
198
+ return pending;
199
+ }
200
+
201
+ function resolveAlias(_event: ChannelInboundEvent, _authorization: ChannelAuthorization): string | undefined {
202
+ return "default";
203
+ }
204
+
205
+ function ensureRoute(event: ChannelInboundEvent, alias: string = "default"): RouteState | undefined {
206
+ const routeKey = actorKey(event);
207
+ const existing = routes.get(routeKey);
208
+ if (existing) return existing;
209
+ if (routes.size >= limits.maxRoutes) return undefined;
210
+ const created: RouteState = {
211
+ connectionId: event.connectionId,
212
+ externalConversationId: event.externalConversationId,
213
+ externalActorId: event.externalActorId,
214
+ ...(event.threadId === undefined ? {} : { threadId: event.threadId }),
215
+ alias,
216
+ generation: 0,
217
+ suspended: false,
218
+ resuming: false,
219
+ pumping: false,
220
+ hydrated: false,
221
+ queue: [],
222
+ };
223
+ routes.set(routeKey, created);
224
+ return created;
225
+ }
226
+
227
+ /** Lookup only: `/status` and `/cancel` from a fresh actor must not allocate a route. */
228
+ function findRoute(event: ChannelInboundEvent, _alias?: string): RouteState | undefined {
229
+ return routes.get(actorKey(event));
230
+ }
231
+
232
+ function bindingInputFor(route: RouteState, turn: Turn, generation: number = route.generation): ChannelBindingInput {
233
+ return {
234
+ connectionId: route.connectionId,
235
+ externalConversationId: route.externalConversationId,
236
+ externalActorId: route.externalActorId,
237
+ ...(route.threadId === undefined ? {} : { threadId: route.threadId }),
238
+ identity: turn.authorization.identity,
239
+ ownership: turn.ownership,
240
+ agentAlias: route.alias,
241
+ generation,
242
+ };
243
+ }
244
+
245
+ function bindingKeyFor(route: RouteState, ownership: OwnershipScope): ChannelBindingKeyInput {
246
+ return {
247
+ ownership,
248
+ connectionId: route.connectionId,
249
+ externalConversationId: route.externalConversationId,
250
+ externalActorId: route.externalActorId,
251
+ ...(route.threadId === undefined ? {} : { threadId: route.threadId }),
252
+ agentAlias: route.alias,
253
+ };
254
+ }
255
+
256
+ function operationKeyFor(ownership: OwnershipScope, event: ChannelInboundEvent, operationId: string): ChannelOperationKeyInput {
257
+ return { ownership, connectionId: event.connectionId, operationId };
258
+ }
259
+
260
+ function operationKeyForTurn(turn: Turn): ChannelOperationKeyInput {
261
+ return operationKeyFor(turn.ownership, turn.event, turn.operationId);
262
+ }
263
+
264
+ function replyKeyFor(turn: Turn): ChannelReplyKeyInput {
265
+ return { ownership: turn.ownership, connectionId: turn.event.connectionId, operationId: turn.operationId };
266
+ }
267
+
268
+ function deriveSessionId(input: ChannelBindingInput): string {
269
+ const digest = createHash("sha256")
270
+ .update(
271
+ key([
272
+ input.connectionId,
273
+ input.externalConversationId,
274
+ input.threadId,
275
+ input.externalActorId,
276
+ input.ownership.tenantId,
277
+ input.ownership.accountId,
278
+ input.ownership.userId,
279
+ input.agentAlias,
280
+ String(input.generation),
281
+ ]),
282
+ )
283
+ .digest("hex");
284
+ return `chan-${digest.slice(0, 40)}`;
285
+ }
286
+
287
+ async function resolveNewSessionId(turn: Turn, route: RouteState, generation: number = route.generation): Promise<string> {
288
+ const input = bindingInputFor(route, turn, generation);
289
+ const binding = options.resolveBinding === undefined ? { sessionId: deriveSessionId(input) } : await options.resolveBinding(input);
290
+ if (
291
+ typeof binding?.sessionId !== "string" ||
292
+ binding.sessionId.length === 0 ||
293
+ Buffer.byteLength(binding.sessionId, "utf8") > MAX_ID_BYTES
294
+ ) {
295
+ throw new TypeError("Channel binding must provide a non-empty sessionId of at most 256 bytes");
296
+ }
297
+ return binding.sessionId;
298
+ }
299
+
300
+ async function resolveBinding(turn: Turn, route: RouteState): Promise<ChannelBinding> {
301
+ if (route.sessionId !== undefined)
302
+ return { sessionId: route.sessionId, ...(route.leafId === undefined ? {} : { leafId: route.leafId }) };
303
+ const binding = await options.resolveBinding?.(bindingInputFor(route, turn));
304
+ const sessionId = binding?.sessionId ?? deriveSessionId(bindingInputFor(route, turn));
305
+ if (typeof sessionId !== "string" || sessionId.length === 0 || Buffer.byteLength(sessionId, "utf8") > MAX_ID_BYTES) {
306
+ throw new TypeError("Channel binding must provide a non-empty sessionId of at most 256 bytes");
307
+ }
308
+ route.sessionId = sessionId;
309
+ if (binding?.leafId !== undefined) route.leafId = binding.leafId;
310
+ return { sessionId: route.sessionId, ...(route.leafId === undefined ? {} : { leafId: route.leafId }) };
311
+ }
312
+
313
+ function track(task: Promise<void>): void {
314
+ inflight.add(task);
315
+ const remove = (): void => {
316
+ inflight.delete(task);
317
+ };
318
+ task.then(remove, remove);
319
+ }
320
+
321
+ // ── durable journal helpers ────────────────────────────────────────────────
322
+
323
+ /** Load (or create once) the durable binding for a route; survives restarts and `/new`. */
324
+ async function hydrateRoute(route: RouteState, turn: Turn, create = true): Promise<"ok" | "missing" | "unavailable"> {
325
+ if (journal === undefined || route.hydrated) return "ok";
326
+ try {
327
+ const keyInput = bindingKeyFor(route, turn.ownership);
328
+ let stored = await journal.loadBinding(keyInput);
329
+ if (stored === null) {
330
+ if (!create) return "missing";
331
+ const record: ChannelBindingRecord = {
332
+ sessionId: await resolveNewSessionId(turn, route),
333
+ agentAlias: route.alias,
334
+ generation: route.generation,
335
+ suspended: false,
336
+ updatedAt: nowIso(),
337
+ };
338
+ stored = await journal.createBinding(keyInput, record);
339
+ if (stored === null) stored = await journal.loadBinding(keyInput);
340
+ if (stored === null) {
341
+ counters.storageFailures += 1;
342
+ return "unavailable";
343
+ }
344
+ }
345
+ route.sessionId = stored.record.sessionId;
346
+ route.leafId = stored.record.leafId;
347
+ route.generation = stored.record.generation;
348
+ route.suspended = stored.record.suspended;
349
+ route.suspendedRun = stored.record.suspendedRun;
350
+ route.bindingVersion = stored.version;
351
+ route.hydrated = true;
352
+ return "ok";
353
+ } catch {
354
+ counters.storageFailures += 1;
355
+ return "unavailable";
356
+ }
357
+ }
358
+
359
+ async function persistBinding(route: RouteState, ownership: OwnershipScope): Promise<void> {
360
+ if (journal === undefined || route.sessionId === undefined) return;
361
+ const record: ChannelBindingRecord = {
362
+ sessionId: route.sessionId,
363
+ ...(route.leafId === undefined ? {} : { leafId: route.leafId }),
364
+ agentAlias: route.alias,
365
+ generation: route.generation,
366
+ suspended: route.suspended,
367
+ ...(route.suspendedRun === undefined ? {} : { suspendedRun: route.suspendedRun }),
368
+ updatedAt: nowIso(),
369
+ };
370
+ try {
371
+ const saved = await journal.saveBinding(
372
+ bindingKeyFor(route, ownership),
373
+ record,
374
+ route.bindingVersion ?? 0,
375
+ route.lease?.fencingToken,
376
+ );
377
+ if (saved === null) counters.storageFailures += 1;
378
+ else route.bindingVersion = saved.version;
379
+ } catch {
380
+ counters.storageFailures += 1;
381
+ }
382
+ }
383
+
384
+ /** Durable dedup + admission: the operation record exists before any effect or transport ack. */
385
+ async function beginOperation(
386
+ turn: Turn,
387
+ kind: ChannelAction,
388
+ options_: { readonly advanceCursor?: boolean } = {},
389
+ ): Promise<"unavailable" | "duplicate" | StoredChannelRecord<ChannelOperationRecord>> {
390
+ const store = journal;
391
+ if (store === undefined) return "duplicate";
392
+ const record: ChannelOperationRecord = {
393
+ operationId: turn.operationId,
394
+ eventId: turn.event.eventId,
395
+ kind,
396
+ connectionId: turn.event.connectionId,
397
+ externalConversationId: turn.event.externalConversationId,
398
+ externalActorId: turn.event.externalActorId,
399
+ ...(turn.event.threadId === undefined ? {} : { threadId: turn.event.threadId }),
400
+ agentAlias: turn.alias,
401
+ state: "accepted",
402
+ replyStaged: false,
403
+ attempts: 0,
404
+ createdAt: nowIso(),
405
+ updatedAt: nowIso(),
406
+ };
407
+ try {
408
+ const created = await store.createOperation(operationKeyForTurn(turn), record);
409
+ if (created === null) return "duplicate";
410
+ turn.opVersion = created.version;
411
+ turn.opRecord = created.record;
412
+ if (options_.advanceCursor === false) return created;
413
+ try {
414
+ await store.advanceCursor({ ownership: turn.ownership, connectionId: turn.event.connectionId }, turn.event.eventId);
415
+ } catch {
416
+ counters.storageFailures += 1; // ordering evidence only; the operation is already durable
417
+ }
418
+ return created;
419
+ } catch {
420
+ counters.storageFailures += 1;
421
+ return "unavailable";
422
+ }
423
+ }
424
+
425
+ async function settleOperation(
426
+ turn: Turn,
427
+ state: ChannelOperationState,
428
+ extra: {
429
+ readonly runId?: string;
430
+ readonly sessionId?: string;
431
+ readonly errorCode?: string;
432
+ readonly replyStaged?: boolean;
433
+ readonly attempt?: boolean;
434
+ } = {},
435
+ ): Promise<void> {
436
+ const store = journal;
437
+ if (store === undefined || turn.opRecord === undefined) return;
438
+ const previous = turn.opRecord;
439
+ const record: ChannelOperationRecord = {
440
+ ...previous,
441
+ state,
442
+ updatedAt: nowIso(),
443
+ ...(extra.runId === undefined ? {} : { runId: extra.runId }),
444
+ ...(extra.sessionId === undefined ? {} : { sessionId: extra.sessionId }),
445
+ ...(extra.errorCode === undefined ? {} : { errorCode: extra.errorCode }),
446
+ ...(extra.replyStaged === undefined ? {} : { replyStaged: extra.replyStaged }),
447
+ attempts: previous.attempts + (extra.attempt === true ? 1 : 0),
448
+ };
449
+ try {
450
+ const saved = await store.saveOperation(operationKeyForTurn(turn), record, turn.opVersion ?? 0, turn.lease?.fencingToken);
451
+ if (saved === null) counters.storageFailures += 1;
452
+ else {
453
+ turn.opVersion = saved.version;
454
+ turn.opRecord = saved.record;
455
+ }
456
+ } catch {
457
+ counters.storageFailures += 1;
458
+ }
459
+ }
460
+
461
+ /** A denial or a command that applied nothing must stay retryable: drop its record. */
462
+ async function dropOperation(turn: Turn): Promise<void> {
463
+ if (journal === undefined || turn.opRecord === undefined) return;
464
+ try {
465
+ await journal.removeOperation(operationKeyForTurn(turn));
466
+ turn.opRecord = undefined;
467
+ turn.opVersion = undefined;
468
+ } catch {
469
+ counters.storageFailures += 1;
470
+ }
471
+ }
472
+
473
+ async function ensureLease(route: RouteState, ownership: OwnershipScope): Promise<"ok" | "lost"> {
474
+ if (options.leases === undefined) return "ok";
475
+ const keyInput = bindingKeyFor(route, ownership);
476
+ const key = `${CHANNEL_JOURNAL_NAMESPACES.binding}:${keyInput.connectionId}:${keyInput.externalConversationId}:${keyInput.externalActorId}:${keyInput.agentAlias}`;
477
+ const now = Date.now();
478
+ const current = route.lease;
479
+ if (current !== undefined && current.expiresAt - now > limits.leaseTtlMs / 3) return "ok";
480
+ try {
481
+ if (current !== undefined) {
482
+ const renewed = await options.leases.renewLease({
483
+ namespace: CHANNEL_JOURNAL_NAMESPACES.binding,
484
+ key,
485
+ ...keyInput.ownership,
486
+ ownerId: leaseOwnerId,
487
+ token: current.token,
488
+ ttlMs: limits.leaseTtlMs,
489
+ });
490
+ if (renewed !== null) {
491
+ route.lease = {
492
+ key,
493
+ token: renewed.token,
494
+ fencingToken: renewed.fencingToken,
495
+ expiresAt: Date.parse(renewed.expiresAt),
496
+ };
497
+ return "ok";
498
+ }
499
+ route.lease = undefined;
500
+ counters.leaseLosses += 1;
501
+ return "lost";
502
+ }
503
+ const acquired = await options.leases.tryAcquireLease({
504
+ namespace: CHANNEL_JOURNAL_NAMESPACES.binding,
505
+ key,
506
+ ...keyInput.ownership,
507
+ ownerId: leaseOwnerId,
508
+ ttlMs: limits.leaseTtlMs,
509
+ });
510
+ if (acquired === null) {
511
+ counters.leaseLosses += 1;
512
+ return "lost"; // another worker owns this binding; never a second receiver
513
+ }
514
+ route.lease = { key, token: acquired.token, fencingToken: acquired.fencingToken, expiresAt: Date.parse(acquired.expiresAt) };
515
+ return "ok";
516
+ } catch {
517
+ counters.storageFailures += 1;
518
+ return "lost";
519
+ }
520
+ }
521
+
522
+ async function releaseLease(route: RouteState, ownership: OwnershipScope): Promise<void> {
523
+ if (options.leases === undefined || route.lease === undefined) return;
524
+ const lease = route.lease;
525
+ try {
526
+ await options.leases.releaseLease({
527
+ namespace: CHANNEL_JOURNAL_NAMESPACES.binding,
528
+ key: lease.key,
529
+ ...ownership,
530
+ ownerId: leaseOwnerId,
531
+ token: lease.token,
532
+ });
533
+ route.lease = undefined;
534
+ } catch {
535
+ counters.storageFailures += 1;
536
+ }
537
+ }
538
+
539
+ /** CAS claim before provider work: exactly one worker moves `accepted` → `executing`. */
540
+ async function claimTurn(turn: Turn, route: RouteState): Promise<"ok" | "deferred" | "unavailable"> {
541
+ const store = journal;
542
+ if (store === undefined || turn.opRecord === undefined) return "ok";
543
+ if ((await ensureLease(route, turn.ownership)) === "lost") return "deferred";
544
+ try {
545
+ const saved = await store.saveOperation(
546
+ operationKeyForTurn(turn),
547
+ { ...turn.opRecord, state: "executing", updatedAt: nowIso() },
548
+ turn.opVersion ?? 0,
549
+ route.lease?.fencingToken,
550
+ );
551
+ if (saved === null) {
552
+ counters.storageFailures += 1;
553
+ return "deferred";
554
+ }
555
+ turn.opVersion = saved.version;
556
+ turn.opRecord = saved.record;
557
+ turn.lease = route.lease;
558
+ return "ok";
559
+ } catch {
560
+ counters.storageFailures += 1;
561
+ return "unavailable"; // fail closed: never run unclaimed work
562
+ }
563
+ }
564
+
565
+ async function acquireSlot(): Promise<() => void> {
566
+ if (ctx.activeRuns < limits.maxActiveSessions) {
567
+ ctx.activeRuns += 1;
568
+ return releaseSlot;
569
+ }
570
+ await new Promise<void>((resolve) => {
571
+ slotWaiters.push(resolve);
572
+ });
573
+ return releaseSlot;
574
+ }
575
+
576
+ function releaseSlot(): void {
577
+ const next = slotWaiters.shift();
578
+ if (next !== undefined) {
579
+ next();
580
+ return;
581
+ }
582
+ ctx.activeRuns -= 1;
583
+ }
584
+
585
+ return {
586
+ key,
587
+ actorKey,
588
+ nowIso,
589
+ boundText,
590
+ redact,
591
+ denial,
592
+ unsupported,
593
+ identityActive,
594
+ validEvent,
595
+ declaredAttachmentBytes,
596
+ authorizeEvent,
597
+ alreadySeen,
598
+ pendingCount,
599
+ resolveAlias,
600
+ ensureRoute,
601
+ findRoute,
602
+ bindingKeyFor,
603
+ operationKeyFor,
604
+ operationKeyForTurn,
605
+ replyKeyFor,
606
+ resolveNewSessionId,
607
+ resolveBinding,
608
+ track,
609
+ hydrateRoute,
610
+ persistBinding,
611
+ beginOperation,
612
+ settleOperation,
613
+ dropOperation,
614
+ ensureLease,
615
+ releaseLease,
616
+ claimTurn,
617
+ acquireSlot,
618
+ };
619
+ }
620
+
621
+ export type RuntimeCore = ReturnType<typeof createRuntimeCore>;