@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,29 @@
1
+ import { createAgent, type ContextBlock, providerDone, providerTextDelta, withContextBlocks, type ContextDraft } from "@arnilo/prism";
2
+ import { mockProvider } from "@arnilo/prism/testing";
3
+
4
+ // Ordered context blocks as a `context.build` handler (roadmap §2.4). The draft is the provider
5
+ // view for this turn only, so a host-owned handler adds context without touching the session
6
+ // store. Blocks are appended in registration order, and a handler can never grant tools.
7
+ export async function demo() {
8
+ let seen: readonly ContextBlock[] = [];
9
+ const agent = await createAgent({
10
+ model: { provider: "mock", model: "context-demo" },
11
+ packages: [
12
+ mockProvider([[providerTextDelta("ok"), providerDone()]], {
13
+ onRequest: (request) => {
14
+ seen = request.context ?? [];
15
+ },
16
+ }),
17
+ ],
18
+ hooks: (hooks) =>
19
+ hooks.on(
20
+ "context.build",
21
+ (draft: ContextDraft) =>
22
+ withContextBlocks(draft, [{ content: `UTC: ${new Date(0).toISOString()}` }, { content: "Project notes placeholder." }]),
23
+ { id: "clock-and-notes" },
24
+ ),
25
+ });
26
+
27
+ await (await agent.session()).run("Hi");
28
+ return { count: seen.length, contents: seen.map((b) => b.content) };
29
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Phase 15 Part B: a host extends a reference adapter instead of writing one from scratch.
3
+ *
4
+ * `extendAdapter` derives a new adapter from `examples/adapters/rpc-server.ts` at definition time:
5
+ * - `configure` wraps the base plan, appending one extra flag and one bound-worktree overlay;
6
+ * - `decode` turns the base's `agent.raw` frame for a `custom-file` notification into `agent.file`;
7
+ * - `descriptor.auth.modes` narrows the policy to the base's api-key modes, dropping the account mode.
8
+ * The derived adapter runs through `processDriver` with `@arnilo/prism-tools/coding` (which owns the
9
+ * `workspace` service and routes `edit` into the session's worktree) and `@arnilo/prism-extensions/approval` in
10
+ * `ask` mode. The scripted binary is the rpc-server dialect: it calls the served `edit` twice, once
11
+ * allowed and once declined by a scripted `HostUi`, then emits a `custom-file` frame the extension
12
+ * decodes. The example prints the captured activity with its `origin`, both decisions, the worktree
13
+ * diff with the overlay excluded, the materialized skill, the extra flag, and `agent.inspect()` notes
14
+ * naming the base and the extension.
15
+ * Imports only `@arnilo/prism`, `/driver-kit`, `/testing`, `@arnilo/prism-hosts/driver-process`,
16
+ * `@arnilo/prism-tools/coding`, `@arnilo/prism-extensions/approval`, the reference adapter and its dialect, and
17
+ * Node built-ins. No vendor name. Run: npm run build:core && bun examples/custom-adapter.ts
18
+ */
19
+ import { spawnSync } from "node:child_process";
20
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
21
+ import { tmpdir } from "node:os";
22
+ import { join, resolve } from "node:path";
23
+ import { pathToFileURL } from "node:url";
24
+ import { type AgentEvent, createAgent, createMemorySessionStore, definePackage, type PackageInstance, type Skill } from "@arnilo/prism";
25
+ import { createProfiles } from "@arnilo/prism/driver-kit";
26
+ import { createScriptedCli, createScriptedHostUi, type ScriptedRecordEntry, type ScriptStep } from "@arnilo/prism/testing";
27
+ import { type AgentAdapter, adapterDriver, extendAdapter, processDriver } from "@arnilo/prism-hosts/driver-process";
28
+ import approval from "@arnilo/prism-extensions/approval";
29
+ import toolsCoding, { type WorkspaceService } from "@arnilo/prism-tools/coding";
30
+ import { rpcServerDialect } from "./adapters/rpc-server.dialect.js";
31
+ import { rpcServer } from "./adapters/rpc-server.js";
32
+
33
+ type Agent = Awaited<ReturnType<typeof createAgent>>;
34
+
35
+ /** The overlay the extension writes into the bound worktree; it is excluded from the diff. */
36
+ const OVERLAY = ".rpc-server/extended.json";
37
+ /** A stable identity for git in the fixture, so no user-level configuration is read. */
38
+ const GIT_ENV = { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" };
39
+
40
+ /** What the extension reports back to the example. */
41
+ interface Evidence {
42
+ readonly materializedSkills: string[];
43
+ }
44
+
45
+ /** The extension: an extra flag, an overlay, a decoder for the base's raw frame, and a narrowed policy. */
46
+ function extendRpcServer(evidence: Evidence): AgentAdapter {
47
+ return extendAdapter(rpcServer, {
48
+ name: "custom-adapter",
49
+ revision: "2",
50
+ configure: (base) => async (spec, ctx) => {
51
+ const plan = await base(spec, ctx);
52
+ if (ctx.skills) evidence.materializedSkills.push(...ctx.skills.pathToSkill.keys());
53
+ return {
54
+ ...plan,
55
+ args: [...(plan.args ?? []), "--custom-flag"],
56
+ overlays: [{ path: OVERLAY, content: JSON.stringify({ extended: true }) }],
57
+ };
58
+ },
59
+ decode: (base) => (frame) => {
60
+ const f = frame as { method?: unknown; params?: { type?: unknown; data?: unknown } };
61
+ if (f?.method === "item/raw" && f.params?.type === "custom-file") {
62
+ const data = (f.params.data ?? {}) as { path?: unknown; change?: unknown };
63
+ return {
64
+ ...base(frame),
65
+ activity: [
66
+ {
67
+ kind: "file",
68
+ path: String(data.path ?? ""),
69
+ change: data.change === "created" || data.change === "deleted" || data.change === "moved" ? data.change : "modified",
70
+ source: "agent",
71
+ },
72
+ ],
73
+ };
74
+ }
75
+ return base(frame);
76
+ },
77
+ descriptor: { auth: { modes: rpcServer.descriptor.auth.modes.filter((mode) => mode.kind === "api-key") } },
78
+ });
79
+ }
80
+
81
+ /** What the vendor's own loop asks the served tools to do, in order. */
82
+ const VENDOR_SCRIPT: readonly ScriptStep[] = [
83
+ { mcp: { method: "tools/call", params: { name: "edit", arguments: { path: "a.txt", edits: [{ oldText: "one", newText: "edited" }] } } } },
84
+ {
85
+ mcp: { method: "tools/call", params: { name: "edit", arguments: { path: "a.txt", edits: [{ oldText: "edited", newText: "again" }] } } },
86
+ },
87
+ { out: { kind: "raw", vendor: "rpc-server", type: "custom-file", data: { path: "b.txt", change: "created" } } },
88
+ { out: { kind: "message.delta", content: { type: "text", text: "Edited a.txt." } } },
89
+ ];
90
+
91
+ const reviewNotes: Skill = { name: "review-notes", description: "Review before editing.", instructions: "Read the notes first." };
92
+
93
+ /** Reads the package's `workspace` service once the packages are set up, so the example can bind a worktree. */
94
+ function workspaceProbe(): { readonly package: PackageInstance; readonly service: () => WorkspaceService | undefined } {
95
+ let service: WorkspaceService | undefined;
96
+ const instance = definePackage({
97
+ name: "custom-adapter-workspace-probe",
98
+ version: "1.0.0",
99
+ requires: { api: 1 },
100
+ setup: ({ services }) => {
101
+ service = services.consume<WorkspaceService>("workspace");
102
+ },
103
+ })();
104
+ return { package: instance, service: () => service };
105
+ }
106
+
107
+ const eventName = (event: AgentEvent): string => (event.type === "package.event" ? event.name : event.type);
108
+
109
+ /** One MCP `tools/call` result the vendor recorded: the error flag and its text. */
110
+ type McpEntry = Extract<ScriptedRecordEntry, { readonly event: "mcp" }>;
111
+ function decisionOf(entry: McpEntry | undefined): { readonly isError: boolean; readonly text: string } {
112
+ if (entry === undefined) return { isError: false, text: "" };
113
+ if ("error" in entry) return { isError: true, text: JSON.stringify(entry.error) };
114
+ const result = entry.result as { readonly isError?: boolean; readonly content?: readonly { readonly text?: string }[] } | undefined;
115
+ return { isError: result?.isError === true, text: (result?.content ?? []).map((block) => block.text ?? "").join("") };
116
+ }
117
+
118
+ /** Runs one git command in the fixture repository, failing loudly. */
119
+ function git(cwd: string, args: readonly string[]): void {
120
+ const result = spawnSync("git", [...args], { cwd, encoding: "utf8", env: GIT_ENV });
121
+ if (result.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${result.stderr}`);
122
+ }
123
+
124
+ export async function demo(): Promise<Record<string, unknown>> {
125
+ const base = mkdtempSync(join(tmpdir(), "ex-ca-"));
126
+ const repo = join(base, "repo");
127
+ mkdirSync(repo, { recursive: true });
128
+ git(repo, ["init", "-q", "-b", "main", "."]);
129
+ git(repo, ["config", "user.name", "Prism Example"]);
130
+ git(repo, ["config", "user.email", "example@prism.local"]);
131
+ writeFileSync(join(repo, "a.txt"), "one\n");
132
+ git(repo, ["add", "-A"]);
133
+ git(repo, ["commit", "-qm", "seed"]);
134
+
135
+ const evidence: Evidence = { materializedSkills: [] };
136
+ const extended = extendRpcServer(evidence);
137
+ const cli = createScriptedCli({ dialect: rpcServerDialect, script: VENDOR_SCRIPT });
138
+ const probe = workspaceProbe();
139
+ const profilesRoot = join(base, "p");
140
+
141
+ // The scripted terminal allows the first edit (confirm, then select `once`) and declines the second.
142
+ let confirms = 0;
143
+ const ui = createScriptedHostUi((request) => {
144
+ if (request.kind === "select") return "once";
145
+ if (request.kind === "confirm") {
146
+ confirms += 1;
147
+ return confirms === 1;
148
+ }
149
+ return { status: "unavailable" };
150
+ });
151
+
152
+ try {
153
+ const profiles = createProfiles({ root: profilesRoot, driver: adapterDriver(extended), host: { ui: ui.ui }, binary: process.execPath });
154
+ await profiles.create("custom", { mode: "key", principal: "u1" });
155
+
156
+ const agent: Agent = await createAgent({
157
+ id: "custom-adapter-demo",
158
+ ownership: { tenantId: "example" },
159
+ principal: { kind: "user", id: "u1" },
160
+ packages: [
161
+ processDriver(extended)({
162
+ binary: cli.command[0] as string,
163
+ args: cli.command.slice(1),
164
+ name: "custom-agent",
165
+ profile: "custom",
166
+ profilesRoot,
167
+ principal: "u1",
168
+ systemPrompt: { replace: "You are the custom agent." },
169
+ prismTools: ["edit"],
170
+ skills: ["review-notes"],
171
+ }),
172
+ toolsCoding({ root: repo, workspace: { worktreeRoot: join(base, "w") } }),
173
+ approval({ mode: "ask" }),
174
+ probe.package,
175
+ ],
176
+ host: { ui: ui.ui },
177
+ slots: { store: createMemorySessionStore() },
178
+ skills: { add: [reviewNotes] },
179
+ });
180
+
181
+ const session = await agent.session();
182
+ const workspace = probe.service();
183
+ if (workspace === undefined) throw new Error("no workspace service: the coding package must provide one");
184
+ const worktree = await workspace.worktree.create({ sessionId: session.id });
185
+
186
+ const events: AgentEvent[] = [];
187
+ // The driver writes the adapter's overlays into the worktree and removes them when the run ends, so
188
+ // presence has to be sampled while the vendor runs.
189
+ let overlayDuringRun = false;
190
+ const pump = (async () => {
191
+ for await (const event of session.subscribe()) {
192
+ events.push(event);
193
+ if (!overlayDuringRun) overlayDuringRun = existsSync(join(worktree.path, OVERLAY));
194
+ }
195
+ })();
196
+ const result = await session.run("Edit a.txt, then report.");
197
+ await session.close();
198
+ await pump.catch(() => undefined);
199
+
200
+ const { changes, truncated } = await workspace.diff(worktree.path);
201
+ const worktreeFile = readFileSync(join(worktree.path, "a.txt"), "utf8").trim();
202
+ const view = agent.inspect();
203
+ const note = view.statusNotes.find((entry) => entry.package === extended.name);
204
+ const inspection = (note === undefined ? {} : JSON.parse(note.message)) as {
205
+ readonly adapter?: {
206
+ readonly name: string;
207
+ readonly revision: string;
208
+ readonly extends?: { readonly name: string; readonly revision: string };
209
+ };
210
+ };
211
+ await worktree.dispose({ force: true });
212
+ await agent.dispose();
213
+
214
+ const argv = cli.record().find((entry) => entry.event === "argv");
215
+ const calls = cli.record().filter((entry): entry is McpEntry => entry.event === "mcp" && entry.method === "tools/call");
216
+ const captured = [
217
+ ...new Map(
218
+ events
219
+ .filter((event) => event.origin !== undefined)
220
+ .map((event) => [
221
+ `${eventName(event)}|${event.origin?.kind}|${event.origin?.depth}`,
222
+ { name: eventName(event), kind: event.origin?.kind, depth: event.origin?.depth },
223
+ ]),
224
+ ).values(),
225
+ ].sort((a, b) => a.name.localeCompare(b.name));
226
+
227
+ return {
228
+ status: result.status,
229
+ adapter: {
230
+ name: inspection.adapter?.name,
231
+ revision: inspection.adapter?.revision,
232
+ base: inspection.adapter?.extends?.name,
233
+ baseRevision: inspection.adapter?.extends?.revision,
234
+ },
235
+ extraFlag: argv !== undefined && "argv" in argv ? argv.argv.includes("--custom-flag") : false,
236
+ activity: captured,
237
+ decisions: {
238
+ allowed: decisionOf(calls[0]),
239
+ declined: decisionOf(calls[1]),
240
+ confirmRequests: ui.requestsOf("confirm").length,
241
+ selectRequests: ui.requestsOf("select").length,
242
+ },
243
+ worktreeFile,
244
+ diff: { changes: changes.map((change) => `${change.change} ${change.path}`), truncated },
245
+ overlay: { path: OVERLAY, presentDuringRun: overlayDuringRun, excluded: !changes.some((change) => change.path === OVERLAY) },
246
+ materializedSkills: [...new Set(evidence.materializedSkills)],
247
+ };
248
+ } finally {
249
+ cli.dispose();
250
+ rmSync(base, { recursive: true, force: true });
251
+ }
252
+ }
253
+
254
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
255
+ console.log(JSON.stringify(await demo()));
256
+ }
@@ -0,0 +1,66 @@
1
+ import { type ContextDraft, createAgent, type Message, providerDone, providerTextDelta, withContextBlocks } from "@arnilo/prism";
2
+ import { mockProvider } from "@arnilo/prism/testing";
3
+
4
+ // A host-owned prompt composition plus a `run.input` hook: both interception
5
+ // points a 0.12 `PromptBuilder` / `ContextProvider` pair used to occupy, now both
6
+ // on the hook bus (roadmap §2.4).
7
+ //
8
+ // - The `run.input` handler wraps raw user text in a tagged user message and
9
+ // prepends a host-owned preamble.
10
+ // - The `context.build` handler places the host's context blocks and a tool
11
+ // summary ahead of the transcript — a different order than the kernel's own.
12
+ //
13
+ // Uses the mock provider — no network, no credentials.
14
+ const preambleMessage: Message = {
15
+ role: "system",
16
+ content: [{ type: "text", text: "Host preamble: answer in one short sentence." }],
17
+ };
18
+
19
+ export async function demo(): Promise<readonly string[]> {
20
+ const agent = await createAgent({
21
+ model: { provider: "mock", model: "demo" },
22
+ packages: [mockProvider([[providerTextDelta("ok"), providerDone()]])],
23
+ hooks: (hooks) => {
24
+ hooks.on("run.input", (messages) => [
25
+ preambleMessage,
26
+ {
27
+ role: "user",
28
+ content: [
29
+ {
30
+ type: "text",
31
+ text: messages
32
+ .flatMap((m) => m.content)
33
+ .map((b) => (b.type === "text" ? b.text : ""))
34
+ .join(" "),
35
+ },
36
+ ],
37
+ },
38
+ ]);
39
+ hooks.on(
40
+ "context.build",
41
+ (draft: ContextDraft) =>
42
+ withContextBlocks(draft, [
43
+ { title: "Workspace", content: "demo repo" },
44
+ { title: "Tools", content: (draft.tools ?? []).map((entry) => entry.name).join(", ") || "none" },
45
+ ]),
46
+ { id: "host-context" },
47
+ );
48
+ },
49
+ });
50
+
51
+ const session = await agent.session();
52
+ const types: string[] = [];
53
+ async function drain(): Promise<void> {
54
+ for await (const event of session.subscribe()) types.push(event.type);
55
+ }
56
+ await Promise.all([drain(), session.run("Summarize the workspace.")]);
57
+ return types;
58
+ }
59
+
60
+ export async function main() {
61
+ console.log(JSON.stringify(await demo()));
62
+ }
63
+
64
+ if (import.meta.url === `file://${process.argv[1]}`) {
65
+ await main();
66
+ }
@@ -0,0 +1,89 @@
1
+ import { createAgent, createMemorySessionStore, type LoopStrategy, providerDone, providerTextDelta, toolCallContent } from "@arnilo/prism";
2
+ import { providerPackage } from "@arnilo/prism/provider-kit";
3
+
4
+ /**
5
+ * Plan-then-act custom loop (roadmap §2.5): a host `LoopStrategy` supplied through `slots.loop` and a
6
+ * host `tool.call` gate that denies a `network` tool. The loop can only reach tools through
7
+ * `executeTools`, so the gate cannot be bypassed by replacing the loop. Network-free.
8
+ * Run: npm run build:core && node examples/custom-loop.ts
9
+ */
10
+
11
+ const planThenAct: LoopStrategy = {
12
+ name: "plan-then-act",
13
+ revision: "1",
14
+ async run(run) {
15
+ for (;;) {
16
+ for (;;) {
17
+ const turn = await run.turn();
18
+ if (turn.stopped) return;
19
+ if (turn.toolCalls.length === 0) {
20
+ if (turn.steered) continue;
21
+ break;
22
+ }
23
+ await run.executeTools(turn.toolCalls);
24
+ }
25
+ const end = await run.end();
26
+ if (!end.continue) return;
27
+ }
28
+ },
29
+ };
30
+
31
+ export async function demo(): Promise<Record<string, unknown>> {
32
+ const executed: string[] = [];
33
+ let turn = 0;
34
+ let sawDenial = false;
35
+ const agent = await createAgent({
36
+ id: "custom-loop",
37
+ model: { provider: "mock", model: "demo" },
38
+ slots: { store: createMemorySessionStore(), loop: planThenAct },
39
+ packages: [
40
+ providerPackage("test-provider", [
41
+ {
42
+ id: "mock",
43
+ async *generate(request) {
44
+ turn += 1;
45
+ if (turn === 1) {
46
+ yield { type: "tool_call" as const, call: toolCallContent("n1", "fetch_url", { url: "https://example.com" }) };
47
+ yield { type: "tool_call" as const, call: toolCallContent("r1", "read_file", { path: "README.md" }) };
48
+ yield providerDone();
49
+ return;
50
+ }
51
+ // The denied call reached the model as an ordinary tool result on the next turn.
52
+ sawDenial = request.messages.some((message) =>
53
+ message.content.some((block) => block.type === "tool_result" && block.error?.code === "hook_denied"),
54
+ );
55
+ yield providerTextDelta(sawDenial ? "network denied; used the local file" : "no denial seen");
56
+ yield providerDone();
57
+ },
58
+ },
59
+ ]),
60
+ ],
61
+ hooks: (hooks) => {
62
+ hooks.on("tool.call", (call) => (call.name === "fetch_url" ? { deny: "network access is disabled" } : "allow"));
63
+ },
64
+ tools: {
65
+ add: [
66
+ {
67
+ name: "fetch_url",
68
+ parameters: {},
69
+ execute: () => {
70
+ throw new Error("the network tool must never run");
71
+ },
72
+ },
73
+ {
74
+ name: "read_file",
75
+ parameters: {},
76
+ execute: (_args, context) => {
77
+ executed.push("read_file");
78
+ return { toolCallId: context.toolCallId, name: "read_file", value: "contents" };
79
+ },
80
+ },
81
+ ],
82
+ },
83
+ });
84
+
85
+ const result = await (await agent.session()).run("plan then act");
86
+ return { status: result.status, executed, sawDenial, text: result.text };
87
+ }
88
+
89
+ if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
@@ -0,0 +1,70 @@
1
+ import { createAgent } from "@arnilo/prism";
2
+ import { createRoutedProvider, providerPackage, replayFetch, type RecordedExchange, type SecretSource } from "@arnilo/prism/provider-kit";
3
+
4
+ /**
5
+ * Custom provider implementation using the routed provider builder.
6
+ * Dispatches between OpenAI-compatible and Anthropic Messages routes.
7
+ */
8
+ export function createAcmeProvider(options: { apiKey?: SecretSource; baseUrl?: string; fetch?: typeof fetch }) {
9
+ return createRoutedProvider({
10
+ id: "acme",
11
+ baseUrl: options.baseUrl ?? "https://api.acme.example/v1",
12
+ apiKey: options.apiKey,
13
+ fetch: options.fetch,
14
+ routes: {
15
+ openai: {
16
+ format: "openai-chat",
17
+ path: "/chat/completions",
18
+ auth: "bearer",
19
+ codec: { reasoningReplay: "reasoning_content" },
20
+ },
21
+ anthropic: {
22
+ format: "anthropic-messages",
23
+ path: "/messages",
24
+ auth: "x-api-key+bearer",
25
+ },
26
+ },
27
+ });
28
+ }
29
+
30
+ export async function demo(): Promise<Record<string, unknown>> {
31
+ const recording: RecordedExchange = {
32
+ method: "POST",
33
+ path: "/v1/chat/completions",
34
+ status: 200,
35
+ contentType: "text/event-stream",
36
+ responseBody: [
37
+ `data: ${JSON.stringify({ choices: [{ delta: { content: "Hello from Acme routed provider!" } }] })}\n\n`,
38
+ `data: ${JSON.stringify({ choices: [{ delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 8, completion_tokens: 7, total_tokens: 15 } })}\n\n`,
39
+ "data: [DONE]\n\n",
40
+ ].join(""),
41
+ };
42
+
43
+ const acmeProvider = createAcmeProvider({
44
+ apiKey: async () => "acme-test-key-demo",
45
+ fetch: replayFetch(recording),
46
+ });
47
+
48
+ const agent = await createAgent({
49
+ id: "custom-provider-agent",
50
+ model: { provider: "acme", model: "acme-chat-v1" },
51
+ packages: [providerPackage("acme-pkg", [acmeProvider])],
52
+ });
53
+
54
+ const session = await agent.session();
55
+ const result = await session.run("Hello Acme");
56
+ await agent.dispose();
57
+
58
+ return {
59
+ status: result.status,
60
+ text: result.text,
61
+ };
62
+ }
63
+
64
+ export async function main() {
65
+ console.log(JSON.stringify(await demo()));
66
+ }
67
+
68
+ if (import.meta.url === `file://${process.argv[1]}`) {
69
+ await main();
70
+ }
@@ -0,0 +1,72 @@
1
+ import { createAgent, createSessionEntry, providerDone, providerTextDelta, type SessionEntry, type SessionStore } from "@arnilo/prism";
2
+ import { mockProvider } from "@arnilo/prism/testing";
3
+
4
+ // Custom session store: a host implements the `SessionStore` contract
5
+ // (append + list) and passes it as the `store` slot. The runtime appends
6
+ // redacted session entries and reads them back to rebuild context across
7
+ // turns. This is the lightest custom-store seam — for a DB-backed reference
8
+ // with idempotency, conflict errors, and branch reads, see
9
+ // `external-app-db-backed.ts`.
10
+ //
11
+ // The store here is a simple in-memory map that records the kinds of entries
12
+ // the runtime appends, proving the host owns persistence. No network, no
13
+ // credentials.
14
+ function customStore(): SessionStore & { appendedKinds: () => readonly string[] } {
15
+ const byId = new Map<string, SessionEntry>();
16
+ const bySession = new Map<string, SessionEntry[]>();
17
+ const kinds: string[] = [];
18
+ return {
19
+ async append(entry: SessionEntry): Promise<void> {
20
+ byId.set(entry.id, entry);
21
+ (bySession.get(entry.sessionId) ?? bySession.set(entry.sessionId, []).get(entry.sessionId)!).push(entry);
22
+ kinds.push(entry.kind);
23
+ },
24
+ async list(sessionId: string): Promise<readonly SessionEntry[]> {
25
+ return [...(bySession.get(sessionId) ?? [])];
26
+ },
27
+ async get(id: string): Promise<SessionEntry | undefined> {
28
+ return byId.get(id);
29
+ },
30
+ appendedKinds: () => [...kinds],
31
+ };
32
+ }
33
+
34
+ export async function demo(): Promise<{ appendedKinds: readonly string[]; entryCount: number; hostNoteId: string }> {
35
+ const store = customStore();
36
+
37
+ const agent = await createAgent({
38
+ model: { provider: "mock", model: "demo" },
39
+ packages: [mockProvider([[providerTextDelta("stored"), providerDone()]])],
40
+ });
41
+
42
+ const session = await agent.session();
43
+ async function drain(): Promise<void> {
44
+ for await (const _event of session.subscribe()) {
45
+ /* consume */
46
+ }
47
+ }
48
+ await Promise.all([drain(), session.run("Hi")]);
49
+
50
+ // The host can read its own store back to display a transcript, and use
51
+ // createSessionEntry to build host-side entries outside the runtime.
52
+ const entries = await store.list(session.id);
53
+ const hostNote = createSessionEntry({
54
+ sessionId: session.id,
55
+ kind: "custom",
56
+ message: { role: "user", content: [{ type: "text", text: "host-side note" }] },
57
+ });
58
+
59
+ return {
60
+ appendedKinds: store.appendedKinds(),
61
+ entryCount: entries.length + 1, // runtime entries + the host-side note
62
+ hostNoteId: hostNote.id,
63
+ };
64
+ }
65
+
66
+ export async function main() {
67
+ console.log(JSON.stringify(await demo()));
68
+ }
69
+
70
+ if (import.meta.url === `file://${process.argv[1]}`) {
71
+ await main();
72
+ }
@@ -0,0 +1,97 @@
1
+ import {
2
+ type AgentEvent,
3
+ createAgent,
4
+ providerDone,
5
+ providerTextDelta,
6
+ providerToolCall,
7
+ providerUsage,
8
+ registerContextSources,
9
+ type Skill,
10
+ type ToolDefinition,
11
+ type ToolResult,
12
+ } from "@arnilo/prism";
13
+ import { mockProvider } from "@arnilo/prism/testing";
14
+
15
+ // Custom tools + skills + context in one host app: register a host-owned
16
+ // tool, a skill that activates it, and a context provider that pins
17
+ // workspace text — then run a prompt that triggers the tool-call loop.
18
+ //
19
+ // Distinct from `tools.ts` / `skills.ts` / `context.ts` (which illustrate
20
+ // each seam alone) and from `external-app-db-backed.ts` (which adds a
21
+ // DB-backed store + ledger): this is the focused "all three capabilities in
22
+ // one agent" SDK adoption path. No filesystem/shell/browser coding tools —
23
+ // only a host-domain `notes/save` tool. No network, no credentials.
24
+
25
+ const saveNoteTool: ToolDefinition = {
26
+ name: "notes/save",
27
+ description: "Persist a short note string.",
28
+ parameters: {
29
+ type: "object",
30
+ properties: { text: { type: "string" } },
31
+ required: ["text"],
32
+ },
33
+ execute(args, ctx): ToolResult {
34
+ return { toolCallId: ctx.toolCallId, name: "notes/save", value: { saved: true, text: args.text } };
35
+ },
36
+ };
37
+
38
+ const summarizeSkill: Skill = {
39
+ name: "summarize-skill",
40
+ description: "Summarize the pinned workspace note and save it.",
41
+ instructions: "Summarize the workspace context, then call notes/save with the summary.",
42
+ toolNames: ["notes/save"],
43
+ };
44
+
45
+ // Host context as a `context.build` source (roadmap §2.4).
46
+ const workspaceContext = {
47
+ name: "workspace",
48
+ contextBlocks: [{ title: "Workspace note", content: "Prism ships an extensible agent SDK." }],
49
+ };
50
+
51
+ export async function demo(): Promise<{
52
+ toolCallNames: readonly string[];
53
+ textDeltas: readonly string[];
54
+ eventTypes: readonly string[];
55
+ }> {
56
+ const agent = await createAgent({
57
+ model: { provider: "mock", model: "demo" },
58
+ packages: [
59
+ mockProvider([
60
+ [
61
+ providerToolCall({ type: "tool_call", id: "tc1", name: "notes/save", arguments: { text: "extensible SDK" } }),
62
+ providerTextDelta("Saved the summary."),
63
+ providerUsage({ inputTokens: 10, outputTokens: 6, totalTokens: 16 }),
64
+ providerDone(),
65
+ ],
66
+ ]),
67
+ ],
68
+ instructions: "You are a concise assistant.",
69
+ tools: { add: [saveNoteTool] },
70
+ skills: { add: [summarizeSkill] },
71
+ hooks: (hooks) => registerContextSources(hooks, [workspaceContext]),
72
+ });
73
+
74
+ const session = await agent.session();
75
+
76
+ const toolCallNames: string[] = [];
77
+ const textDeltas: string[] = [];
78
+ const eventTypes: string[] = [];
79
+ async function drain(): Promise<void> {
80
+ for await (const event of session.subscribe() as AsyncIterable<AgentEvent>) {
81
+ eventTypes.push(event.type);
82
+ if (event.type === "tool.started") toolCallNames.push(event.call.name);
83
+ if (event.type === "message.delta" && event.content.type === "text") textDeltas.push(event.content.text);
84
+ }
85
+ }
86
+ await Promise.all([drain(), session.run("Summarize and save.")]);
87
+
88
+ return { toolCallNames, textDeltas, eventTypes };
89
+ }
90
+
91
+ export async function main() {
92
+ console.log(JSON.stringify(await demo()));
93
+ }
94
+
95
+ if (import.meta.url === `file://${process.argv[1]}`) {
96
+ await main();
97
+ }