@arnilo/prism-hosts 0.0.0-stage → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +6167 -0
  136. package/host-builder/data/errors.json +546 -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 +252 -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 +317 -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 +64 -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,124 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ type Agent,
7
+ createAgent,
8
+ createSessionIndex,
9
+ definePackage,
10
+ type HostUi,
11
+ providerDone,
12
+ providerTextDelta,
13
+ type SessionStore,
14
+ } from "@arnilo/prism";
15
+ import { createScriptedHostUi, mockProvider } from "@arnilo/prism/testing";
16
+
17
+ import sqliteStore, { createSqlitePersistence } from "@arnilo/prism-extensions/store-sqlite";
18
+ import workflows, { agentNode, defineWorkflow, startWorkflow, type WorkflowRun } from "@arnilo/prism-extensions/workflows";
19
+
20
+ // Keep Bun transport declarations out of the examples compiler (see the conformance fixture).
21
+ const remoteModule = "@arnilo/prism-hosts/remote";
22
+ const connectAgent: (
23
+ endpoint: { kind: "stdio"; command: string[] },
24
+ options: { host: { ui: HostUi }; mirror: SessionStore },
25
+ ) => Promise<Agent> = (await import(remoteModule)).connectAgent;
26
+
27
+ // Run offline: bun examples/remote-agent.ts (also works as emitted JavaScript).
28
+ function assert(condition: boolean, message: string): asserts condition {
29
+ if (!condition) throw new Error(`remote_agent_example_output: ${message}`);
30
+ }
31
+
32
+ export async function demo() {
33
+ const root = mkdtempSync(join(tmpdir(), "prism-remote-"));
34
+ const path = join(root, "sessions.db");
35
+ const store = createSqlitePersistence({ filename: path });
36
+ const agents: Agent[] = [];
37
+ try {
38
+ const scripted = createScriptedHostUi({ confirm: true, select: "once" });
39
+ const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
40
+ const remote = await connectAgent(
41
+ {
42
+ kind: "stdio",
43
+ command: [process.execPath, fileURLToPath(new URL(`./remote-agent-server.${extension}`, import.meta.url))],
44
+ },
45
+ { host: { ui: scripted.ui }, mirror: store },
46
+ );
47
+ agents.push(remote);
48
+ const local = await createAgent({
49
+ id: "local-reviewer",
50
+ model: { provider: "mock", model: "demo" },
51
+ packages: [sqliteStore({ path }), mockProvider([[providerTextDelta("Local reviewed report"), providerDone()]])],
52
+ });
53
+ agents.push(local);
54
+ const flow = defineWorkflow({
55
+ id: "remote-review",
56
+ revision: "1",
57
+ nodes: {
58
+ plan: agentNode({ agent: remote, input: () => "Save the report" }),
59
+ review: agentNode({ agent: local, input: (ctx) => `Review: ${String(ctx.upstream.plan)}` }),
60
+ },
61
+ edges: [["plan", "review"]],
62
+ });
63
+ const host = await createAgent({
64
+ model: { provider: "mock", model: "demo" },
65
+ packages: [
66
+ sqliteStore({ path }),
67
+ mockProvider([[providerDone()]]),
68
+ workflows,
69
+ definePackage({
70
+ name: "@example/remote-workflow",
71
+ version: "1.0.0",
72
+ requires: { api: 1 },
73
+ setup(prism) {
74
+ prism.commands.register({
75
+ name: "review",
76
+ description: "Run the remote and local agents",
77
+ run: (_args, ctx) => startWorkflow(flow, "report", { prism, session: ctx.session! }),
78
+ });
79
+ },
80
+ }),
81
+ ],
82
+ });
83
+ agents.push(host);
84
+ const parent = await host.session();
85
+ const run = (await host.commands.run("review", undefined, { session: parent })) as WorkflowRun;
86
+ let remoteEvents = 0;
87
+ let externalTools = 0;
88
+ for await (const event of run.stream()) {
89
+ console.log(JSON.stringify(event));
90
+ if ("origin" in event && event.origin?.remote === "example-remote") {
91
+ remoteEvents++;
92
+ if (event.type.startsWith("tool.")) {
93
+ assert(event.origin.executedBy === "external", "remote tool attribution");
94
+ externalTools++;
95
+ }
96
+ }
97
+ }
98
+ const result = await run.result();
99
+ const hits = await createSessionIndex(store).search({ query: "report", workflowRunId: run.id });
100
+ assert(result.status === "succeeded", `workflow ${result.status}`);
101
+ assert(scripted.requestsOf("confirm").length === 1, "approval did not reach local HostUi");
102
+ assert(remoteEvents > 0 && externalTools > 0, "origin.remote missing");
103
+ assert(hits.items.length === 2, `expected two search hits, got ${hits.items.length}`);
104
+ assert(
105
+ hits.items.some((hit) => (hit.snippet ?? "").includes("Remote approved")),
106
+ "remote reply missing",
107
+ );
108
+ assert(
109
+ hits.items.some((hit) => (hit.snippet ?? "").includes("Local reviewed")),
110
+ "local reply missing",
111
+ );
112
+ await parent.close();
113
+ return { status: result.status, approved: true, remoteEvents, searchHits: hits.items };
114
+ } finally {
115
+ try {
116
+ for (const agent of agents.reverse()) await agent.dispose();
117
+ } finally {
118
+ store.close();
119
+ rmSync(root, { recursive: true, force: true });
120
+ }
121
+ }
122
+ }
123
+
124
+ if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Offline: bun examples/research-ledger.ts
3
+ * A mock fetch records two sources. One citation passes. An unknown id fails the check.
4
+ */
5
+ import { createAgent, type ToolDefinition } from "@arnilo/prism";
6
+ import { mockProvider, providerDone, providerTextDelta, providerToolCall, toolCallContent } from "@arnilo/prism/testing";
7
+ import toolsResearch from "@arnilo/prism-tools/research";
8
+
9
+ function assert(condition: unknown, message: string): asserts condition {
10
+ if (!condition) throw new Error(`research_ledger_example: ${message}`);
11
+ }
12
+
13
+ const fetchTool: ToolDefinition = {
14
+ name: "web_fetch",
15
+ description: "Fixture fetch.",
16
+ effects: ["network"],
17
+ parameters: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
18
+ async execute(args, context) {
19
+ return {
20
+ toolCallId: context.toolCallId,
21
+ name: "web_fetch",
22
+ value: { url: args.url, title: "T" },
23
+ content: [{ type: "text", text: "fetched" }],
24
+ };
25
+ },
26
+ };
27
+
28
+ export async function demo() {
29
+ const passed = await createAgent({
30
+ model: { provider: "mock", model: "m" },
31
+ tools: { add: [fetchTool] },
32
+ packages: [
33
+ mockProvider([
34
+ [
35
+ providerToolCall(toolCallContent("c1", "web_fetch", { url: "https://a.test/one" })),
36
+ providerToolCall(toolCallContent("c2", "web_fetch", { url: "https://b.test/two" })),
37
+ providerDone(),
38
+ ],
39
+ [providerTextDelta("Kept [[cite:S1]]."), providerDone()],
40
+ ]),
41
+ toolsResearch({ sourceTools: ["web_fetch"] }),
42
+ ],
43
+ });
44
+ try {
45
+ const session = await passed.session({ id: "ok", create: true });
46
+ await session.run("research");
47
+ const verdict = await passed.commands.run("research.verify", {}, { session });
48
+ assert(verdict !== undefined && typeof verdict === "object", "verify returned nothing");
49
+ const report = verdict as { verdict: string; unresolved: string[]; ledgerSize: number };
50
+ assert(report.verdict === "passed", `expected passed, got ${report.verdict}`);
51
+ assert(report.ledgerSize === 2, `expected 2 sources, got ${report.ledgerSize}`);
52
+ assert(report.unresolved.length === 0, "passed run has unresolved ids");
53
+ } finally {
54
+ await passed.dispose();
55
+ }
56
+
57
+ const failed = await createAgent({
58
+ model: { provider: "mock", model: "m" },
59
+ packages: [
60
+ mockProvider([[providerTextDelta("Invented [[cite:S9]]."), providerDone()]]),
61
+ toolsResearch({ sourceTools: ["web_fetch"], maxRepairs: 0 }),
62
+ ],
63
+ });
64
+ try {
65
+ const session = await failed.session({ id: "bad", create: true });
66
+ await session.run("research");
67
+ const report = (await failed.commands.run("research.verify", {}, { session })) as {
68
+ verdict: string;
69
+ unresolved: string[];
70
+ };
71
+ assert(report.verdict === "failed", `expected failed, got ${report.verdict}`);
72
+ assert(report.unresolved.includes("S9"), "failed run did not name S9");
73
+ console.log(JSON.stringify({ passed: { verdict: "passed", ledgerSize: 2 }, failed: report }));
74
+ } finally {
75
+ await failed.dispose();
76
+ }
77
+ }
78
+
79
+ if (import.meta.url === `file://${process.argv[1]}`) await demo();
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Cross-layer revocation composition (plan 122 Task 7).
3
+ *
4
+ * One host, one in-memory vector store, three scenarios that a Synapta-shaped
5
+ * host needs proven end to end:
6
+ *
7
+ * 1. access loss — a principal loses a grant; the source stays for others.
8
+ * 2. deletion — `createDeletionPropagator` tombstones the source (and its
9
+ * lineage-closed derived ids) and the registered handlers
10
+ * delete chunk rows.
11
+ * 3. mid-flight — a grant revoked *while a reranker runs* still cannot leak:
12
+ * the post-rerank gate re-reads and withholds the source.
13
+ *
14
+ * Revocation reaches derived context through the build-time `invalidatedIds`
15
+ * filter fed by `listInvalidatedIds`: the observational-memory projection is
16
+ * built with the same tombstone set, so a revoked source stops rendering
17
+ * without an observational-memory write path. (0.12's `om.observations.dropped`
18
+ * drop leg lived in the attach surface, deleted by plan 157 Task 5.) Nothing
19
+ * here grants or commits: retrieval, grants, and commit authority stay with the host.
20
+ *
21
+ * Offline: hash embedder, in-memory vector/session stores, no network.
22
+ */
23
+ import { type Session, type ContextBlock, createAgent, createMemorySessionStore, createSessionEntry } from "@arnilo/prism";
24
+ import {
25
+ createDeletionPropagator,
26
+ createHashEmbedder,
27
+ createMemoryVectorStore,
28
+ listInvalidatedIds,
29
+ type MemoryScope,
30
+ type VectorStore,
31
+ } from "@arnilo/prism-memory-system/core";
32
+ import {
33
+ activeObservations,
34
+ buildObservationalMemoryContextBlocks,
35
+ createMemoryId,
36
+ foldObservationalMemoryLedger,
37
+ OBSERVATIONS_RECORDED,
38
+ } from "@arnilo/prism-memory-system";
39
+ import { chunkMarkdown, createRagDeletionHandler, indexChunks, retrieveContext } from "@arnilo/prism-knowledge/rag";
40
+ import { mockProvider } from "@arnilo/prism/testing";
41
+
42
+ const TENANT = "t1";
43
+ const RESOURCE = "docs";
44
+ const CORPUS = "handbook";
45
+ const vectorScope: Required<MemoryScope> = { tenantId: TENANT, resourceId: RESOURCE, threadId: CORPUS };
46
+ const ragScope = { tenantId: TENANT, resourceId: RESOURCE, corpusId: CORPUS };
47
+ const analyst = { tenantId: TENANT, principalId: "analyst" };
48
+ const auditor = { tenantId: TENANT, principalId: "auditor" };
49
+ const DENIAL_SECRET = "sk-live-never-persist-this";
50
+
51
+ const PAYROLL = "payroll-export";
52
+ const SECURITY = "security-guide";
53
+ const PLAN_NOTES = "plan-notes";
54
+ const VENDOR = "vendor-contract";
55
+ const OBSERVATION_TEXT = "Payroll export moved to the new bucket";
56
+
57
+ const embedder = createHashEmbedder();
58
+ const store = createMemoryVectorStore();
59
+
60
+ await store.setSourceAccess(vectorScope, [
61
+ { sourceId: PAYROLL, principalIds: ["analyst", "auditor"], accessVersion: 1 },
62
+ { sourceId: SECURITY, principalIds: ["analyst", "auditor"], accessVersion: 1 },
63
+ { sourceId: PLAN_NOTES, principalIds: ["analyst", "auditor"], accessVersion: 1 },
64
+ { sourceId: VENDOR, principalIds: ["analyst", "auditor"], accessVersion: 1 },
65
+ ]);
66
+
67
+ await indexChunks({
68
+ chunks: chunkMarkdown("# Payroll export\n\nPayroll figures move to the new bucket in March.", { sourceId: PAYROLL }),
69
+ embedder,
70
+ store,
71
+ scope: ragScope,
72
+ });
73
+ await indexChunks({
74
+ chunks: chunkMarkdown("# Approval policy\n\nApprovers recheck current execution policy before side effects.", { sourceId: SECURITY }),
75
+ embedder,
76
+ store,
77
+ scope: ragScope,
78
+ });
79
+ await indexChunks({
80
+ chunks: chunkMarkdown("# Delivery plan\n\nThe rollout plan notes the staging window and rollback owner.", { sourceId: PLAN_NOTES }),
81
+ embedder,
82
+ store,
83
+ scope: ragScope,
84
+ });
85
+ await indexChunks({
86
+ chunks: chunkMarkdown("# Vendor contract\n\nVendor contract renewal terms expire next quarter.", { sourceId: VENDOR }),
87
+ embedder,
88
+ store,
89
+ scope: ragScope,
90
+ });
91
+
92
+ function sourcesOf(result: Awaited<ReturnType<typeof retrieveContext>>): readonly string[] {
93
+ return [...new Set(result.hits.map((hit) => hit.sourceId))];
94
+ }
95
+
96
+ function legsOf(result: Awaited<ReturnType<typeof retrieveContext>>, sourceId: string): readonly string[] {
97
+ return result.hits.filter((hit) => hit.sourceId === sourceId).map((hit) => hit.provenance.retrieval);
98
+ }
99
+
100
+ /** Scenario 1: baseline retrieval sees both readable sources through the vector + lexical legs. */
101
+ const baseline = await retrieveContext("payroll export approval policy", {
102
+ embedder,
103
+ store,
104
+ scope: ragScope,
105
+ authorization: analyst,
106
+ lexical: "fts",
107
+ topK: 5,
108
+ });
109
+ const report = baseline.text; // host report generated from the authorized baseline
110
+
111
+ /** Scenario 2: access loss for the analyst only; the auditor still reads the retained rows. */
112
+ await store.setSourceAccess(vectorScope, [{ sourceId: PAYROLL, principalIds: ["auditor"], accessVersion: 2 }]);
113
+ const accessLossDenials: unknown[] = [];
114
+ const analystAfterAccessLoss = await retrieveContext("payroll export approval policy", {
115
+ embedder,
116
+ store,
117
+ scope: ragScope,
118
+ authorization: analyst,
119
+ lexical: "fts",
120
+ topK: 5,
121
+ onAccessDenied: (denial) => accessLossDenials.push({ sourceId: denial.sourceId, reason: denial.reason, hits: denial.hits }),
122
+ });
123
+ const auditorAfterAccessLoss = await retrieveContext("payroll export approval policy", {
124
+ embedder,
125
+ store,
126
+ scope: ragScope,
127
+ authorization: auditor,
128
+ lexical: "fts",
129
+ topK: 5,
130
+ });
131
+ const tombstonesAfterAccessLoss = await listInvalidatedIds(store, vectorScope);
132
+ const rowsRetainedAfterAccessLoss = (await store.getBySource(vectorScope, PAYROLL)).length;
133
+
134
+ /** Scenario 3: observational memory holds one observation that rests on the payroll source. */
135
+ const sessionStore = createMemorySessionStore();
136
+ const session: Session = await (
137
+ await createAgent({
138
+ model: { provider: "mock", model: "revocation-demo" },
139
+ packages: [mockProvider([[]])],
140
+ slots: { store: sessionStore },
141
+ })
142
+ ).session({ id: "s-revocation", create: true });
143
+ const observation = {
144
+ id: createMemoryId("x"),
145
+ kind: "statement" as const,
146
+ description: OBSERVATION_TEXT,
147
+ timestamp: "2026-01-01T00:00:00.000Z",
148
+ relevance: "high" as const,
149
+ sourceEntryIds: [PAYROLL],
150
+ tokenCount: 8,
151
+ };
152
+ const observationEntry = createSessionEntry({
153
+ id: "e-om-1",
154
+ sessionId: session.id,
155
+ parentId: session.leafId,
156
+ kind: "custom",
157
+ data: { type: OBSERVATIONS_RECORDED, observations: [observation] },
158
+ });
159
+ await sessionStore.append(observationEntry);
160
+ await session.checkout(observationEntry.id);
161
+
162
+ const memoryContent = (blocks: readonly ContextBlock[]): string => {
163
+ const content = blocks.find((block) => block.title === "session-memory")?.content;
164
+ return typeof content === "string" ? content : "";
165
+ };
166
+ const entriesBeforeRevocation = await session.entries();
167
+ const contextBeforeRevocation = memoryContent(buildObservationalMemoryContextBlocks(entriesBeforeRevocation));
168
+
169
+ /** Deletion pass one: tombstone the lineage-closed id set and delete the chunk rows. */
170
+ const propagator = createDeletionPropagator({
171
+ scope: vectorScope,
172
+ vectorStore: store,
173
+ authorization: auditor,
174
+ handlers: [createRagDeletionHandler({ store, scope: ragScope })],
175
+ });
176
+ const deletion = await propagator.propagate(PAYROLL);
177
+
178
+ /** Read path: build-time `invalidatedIds` withholds what the drop entry has not retired yet. */
179
+ const invalidatedIds = await listInvalidatedIds(store, vectorScope);
180
+ const contextReadPath = memoryContent(buildObservationalMemoryContextBlocks(entriesBeforeRevocation, { invalidatedIds }));
181
+
182
+ const analystAfterDeletion = await retrieveContext("payroll export approval policy", {
183
+ embedder,
184
+ store,
185
+ scope: ragScope,
186
+ authorization: analyst,
187
+ lexical: "fts",
188
+ topK: 5,
189
+ });
190
+ const auditorAfterDeletion = await retrieveContext("payroll export approval policy", {
191
+ embedder,
192
+ store,
193
+ scope: ragScope,
194
+ authorization: auditor,
195
+ lexical: "fts",
196
+ topK: 5,
197
+ });
198
+
199
+ /** The same projection, with the tombstones applied: the revoked source stops rendering. */
200
+ const entriesAfterDeletion = await session.entries();
201
+ const activeObservationIdsAfterDeletion = activeObservations(foldObservationalMemoryLedger(entriesAfterDeletion)).map(
202
+ (active) => active.id,
203
+ );
204
+
205
+ /** Scenario 4: revoke landing while the reranker runs — the post-rerank gate re-reads and withholds. */
206
+ const midFlightDenials: unknown[] = [];
207
+ let preRerankSources: readonly string[] = [];
208
+ const midFlight = await retrieveContext("delivery plan staging window", {
209
+ embedder,
210
+ store,
211
+ scope: ragScope,
212
+ authorization: analyst,
213
+ lexical: "fts",
214
+ topK: 5,
215
+ onAccessDenied: (denial) => midFlightDenials.push({ sourceId: denial.sourceId, reason: denial.reason, hits: denial.hits }),
216
+ reranker: {
217
+ async rerank({ hits }) {
218
+ preRerankSources = [...new Set(hits.map((hit) => hit.sourceId))];
219
+ // A revoke during rerank must not leak into the prompt.
220
+ await store.setSourceAccess(vectorScope, [{ sourceId: PLAN_NOTES, principalIds: ["auditor"], accessVersion: 2 }]);
221
+ return hits;
222
+ },
223
+ },
224
+ });
225
+
226
+ /** Scenario 5: a throwing grant check fails closed and the error is redacted and capped, never a payload. */
227
+ const flakyStore: VectorStore = {
228
+ ...store,
229
+ checkSourceAccess: async (scope, sourceId, authorization, accessOptions) => {
230
+ if (sourceId === VENDOR) {
231
+ throw new Error(`grant check failed for ${sourceId}: ${DENIAL_SECRET} ${"detail ".repeat(60)}`);
232
+ }
233
+ return store.checkSourceAccess(scope, sourceId, authorization, accessOptions);
234
+ },
235
+ };
236
+ const denialPath: { sourceId: string; reason: string; error?: string }[] = [];
237
+ const deniedQuery = await retrieveContext("vendor contract approval policy", {
238
+ embedder,
239
+ store: flakyStore,
240
+ scope: ragScope,
241
+ authorization: analyst,
242
+ lexical: "fts",
243
+ topK: 5,
244
+ secrets: [DENIAL_SECRET],
245
+ onAccessDenied: (denial) => denialPath.push({ sourceId: denial.sourceId, reason: denial.reason, error: denial.error }),
246
+ });
247
+
248
+ const payload = {
249
+ scenario: "cross-layer-revocation",
250
+ baseline: { sources: sourcesOf(baseline), payrollLegs: legsOf(baseline, PAYROLL), hasRevokedText: report.includes("Payroll figures") },
251
+ accessLoss: {
252
+ analystSources: sourcesOf(analystAfterAccessLoss),
253
+ analystDenials: accessLossDenials,
254
+ auditorSources: sourcesOf(auditorAfterAccessLoss),
255
+ tombstones: tombstonesAfterAccessLoss,
256
+ retainedRows: rowsRetainedAfterAccessLoss,
257
+ },
258
+ deletion: {
259
+ tombstonedIds: deletion.ids,
260
+ layers: deletion.layers,
261
+ analystSources: sourcesOf(analystAfterDeletion),
262
+ auditorSources: sourcesOf(auditorAfterDeletion),
263
+ invalidatedIds,
264
+ },
265
+ context: {
266
+ beforeHasRevoked: contextBeforeRevocation.includes(OBSERVATION_TEXT),
267
+ readPathHasRevoked: contextReadPath.includes(OBSERVATION_TEXT),
268
+ activeObservationIds: activeObservationIdsAfterDeletion,
269
+ },
270
+ exposure: {
271
+ reportHadRevokedText: report.includes("Payroll figures"),
272
+ postDeletionRetrievedRevoked: [...sourcesOf(analystAfterDeletion), ...sourcesOf(auditorAfterDeletion)].includes(PAYROLL),
273
+ },
274
+ midFlight: { preRerankSources, sources: sourcesOf(midFlight), denials: midFlightDenials },
275
+ denialPath: {
276
+ denials: denialPath,
277
+ remainingSources: sourcesOf(deniedQuery),
278
+ errorCapped: denialPath.every((denial) => (denial.error?.length ?? 0) <= 256),
279
+ },
280
+ policy: {
281
+ attentionThresholdsTouched: false,
282
+ executionAuthority: "host",
283
+ priorDisclosure: "not erased by revocation",
284
+ },
285
+ };
286
+
287
+ console.log(JSON.stringify(payload));
@@ -0,0 +1,93 @@
1
+ import { createAgent, providerDone, providerTextDelta, type EvaluationRecord } from "@arnilo/prism";
2
+ import { mockProvider } from "@arnilo/prism/testing";
3
+ import { createMemoryEvaluationStore, createMemoryRunFeedbackStore } from "@arnilo/prism-extensions/store-codecs";
4
+ import { appendEvaluationFeedback, calibrateJudge, createRubricJudge } from "@arnilo/prism-hosts/evals";
5
+ import { createInMemoryTelemetry, createOpenTelemetryInstrumentation } from "@arnilo/prism-extensions/observability";
6
+
7
+ const ownership = { tenantId: "example-tenant", userId: "example-user" } as const;
8
+ const run = { runId: "run-1", sessionId: "session-1", traceId: "trace-1", ...ownership };
9
+ const feedback = createMemoryRunFeedbackStore({
10
+ resolveRun: ({ runId }) => (runId === run.runId ? run : false),
11
+ });
12
+ const evaluation: EvaluationRecord = {
13
+ id: "eval-1",
14
+ scorerId: "citation-quality",
15
+ status: "scored",
16
+ sampled: true,
17
+ score: 1,
18
+ runId: run.runId,
19
+ sessionId: run.sessionId,
20
+ traceId: run.traceId,
21
+ createdAt: new Date().toISOString(),
22
+ ...ownership,
23
+ };
24
+ const record = await appendEvaluationFeedback({
25
+ feedbackStore: feedback,
26
+ evaluationStore: createMemoryEvaluationStore([evaluation]),
27
+ evaluationIds: [evaluation.id],
28
+ feedback: {
29
+ id: "feedback-1",
30
+ runId: run.runId,
31
+ traceId: run.traceId,
32
+ rating: 1,
33
+ comment: "Useful and cited",
34
+ tags: ["reviewed"],
35
+ ...ownership,
36
+ },
37
+ });
38
+
39
+ const memory = createInMemoryTelemetry();
40
+ const telemetry = createOpenTelemetryInstrumentation({ tracer: memory.tracer, meter: memory.meter });
41
+ telemetry.handleRunFeedback({
42
+ runId: record.runId,
43
+ rating: record.rating,
44
+ hasComment: record.comment !== undefined,
45
+ tagCount: record.tags.length,
46
+ scorerCount: record.scorerIds.length,
47
+ evaluationCount: record.evaluationIds.length,
48
+ });
49
+ telemetry.handleEvaluation({ runId: run.runId, status: evaluation.status, score: evaluation.score, hasReason: false });
50
+
51
+ console.log(
52
+ JSON.stringify({
53
+ feedback: (await feedback.query({ ...ownership, runId: run.runId })).items,
54
+ metricLabels: memory.metrics.map((metric) => metric.attributes),
55
+ }),
56
+ );
57
+
58
+ // One mock label demonstrates the API; a CI gate needs a representative human-labeled sample.
59
+ const candidate = await createAgent({
60
+ model: { provider: "mock", model: "candidate" },
61
+ packages: [mockProvider([[providerTextDelta("A useful answer [1]."), providerDone()]])],
62
+ });
63
+ const judgeAgent = await createAgent({
64
+ model: { provider: "mock", model: "judge" },
65
+ packages: [mockProvider([[providerTextDelta(JSON.stringify({ reasoning: "Useful and cited", label: "yes" })), providerDone()]])],
66
+ });
67
+ const session = await candidate.session();
68
+ try {
69
+ const result = await session.run("Give a useful answer with a citation");
70
+ const judge = createRubricJudge({
71
+ agent: judgeAgent,
72
+ judgedModel: candidate.config.model,
73
+ rubric: {
74
+ id: "citation-quality",
75
+ version: "1",
76
+ criteria: "The answer is useful and cited",
77
+ scale: [
78
+ { label: "no", score: 0, description: "Missing useful citations" },
79
+ { label: "yes", score: 1, description: "Useful and cited" },
80
+ ],
81
+ },
82
+ });
83
+ const calibration = await calibrateJudge({
84
+ judge,
85
+ items: [{ item: { id: record.id, input: "Give a useful answer with a citation" }, result, humanScore: (record.rating! + 1) / 2 }],
86
+ seed: 1,
87
+ });
88
+ console.log(JSON.stringify({ calibration }));
89
+ } finally {
90
+ await session.close();
91
+ await candidate.dispose();
92
+ await judgeAgent.dispose();
93
+ }
@@ -0,0 +1,48 @@
1
+ import { createHashEmbedder, createMemoryVectorStore } from "@arnilo/prism-memory-system/core";
2
+ import { replaceDocument, retrieveContext } from "@arnilo/prism-knowledge/rag";
3
+ import { createMistralOcrParser } from "@arnilo/prism-tools/work/document-reader";
4
+
5
+ const pdf = Buffer.from("%PDF-1.7\n%", "latin1");
6
+ let pagesProcessed = 0;
7
+ const ocr = createMistralOcrParser({
8
+ apiKey: "demo",
9
+ fetch: async () =>
10
+ new Response(
11
+ JSON.stringify({
12
+ pages: [{ index: 1, markdown: "Recheck policy before side effects." }],
13
+ model: "mistral-ocr-latest",
14
+ usage_info: { pages_processed: 1 },
15
+ }),
16
+ { status: 200 },
17
+ ),
18
+ recordUsage: (usage) => {
19
+ pagesProcessed = usage.pagesProcessed;
20
+ },
21
+ });
22
+
23
+ const scope = { tenantId: "demo", resourceId: "docs", corpusId: "scans" };
24
+ const store = createMemoryVectorStore();
25
+ const embedder = createHashEmbedder();
26
+ const replaced = await replaceDocument({
27
+ uri: "ocr:demo",
28
+ sourceId: "scan",
29
+ loader: {
30
+ load: async () => ({ uri: "ocr:demo", sourceId: "scan", mediaType: "application/pdf", data: pdf }),
31
+ },
32
+ parser: {
33
+ async parse(document, options) {
34
+ const buffer = Buffer.from(document.data ?? new Uint8Array());
35
+ const extracted = await ocr.extract(buffer, {
36
+ maxPages: options?.maxPages ?? 4,
37
+ maxTextBytes: 64 * 1024,
38
+ signal: options?.signal,
39
+ });
40
+ return { text: extracted.text, metadata: { pages: extracted.pages } };
41
+ },
42
+ },
43
+ embedder,
44
+ store,
45
+ scope,
46
+ });
47
+ const found = await retrieveContext("policy", { embedder, store, scope, lexical: "off" });
48
+ console.log(JSON.stringify({ indexed: replaced.indexed, pagesProcessed, citation: found.citations[0]?.id }));
@@ -0,0 +1,21 @@
1
+ import { createAgent, providerDone, providerTextDelta } from "@arnilo/prism";
2
+ import { mockProvider } from "@arnilo/prism/testing";
3
+
4
+ // SDK basics: create an agent + session, subscribe to events, run a prompt.
5
+ // Uses the mock provider — network-free, no credentials.
6
+ export async function demo(): Promise<readonly string[]> {
7
+ const agent = await createAgent({
8
+ model: { provider: "mock", model: "demo" },
9
+ packages: [mockProvider([[providerTextDelta("Hello"), providerDone()]])],
10
+ });
11
+
12
+ const session = await agent.session();
13
+
14
+ const types: string[] = [];
15
+ for await (const event of session.subscribe()) {
16
+ types.push(event.type);
17
+ }
18
+
19
+ await session.run("Hi");
20
+ return types;
21
+ }