@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,108 @@
1
+ /**
2
+ * Static UI assets for the devtools page.
3
+ *
4
+ * One page and one browser module, served from this origin with no external fetches. The module is
5
+ * `inspector.ts`, transpiled by Bun on first request and cached: the package ships source, so there is
6
+ * no build step and no `dist/`. Every response carries a strict CSP (scripts, styles, and connections
7
+ * to this origin only).
8
+ */
9
+ import { readFileSync } from "node:fs";
10
+
11
+ /** Strict CSP for the served page: scripts, styles, and connections to this origin only. */
12
+ export const UI_CSP = [
13
+ "default-src 'none'",
14
+ "script-src 'self'",
15
+ "style-src 'self' 'unsafe-inline'",
16
+ "connect-src 'self'",
17
+ "img-src 'self' data:",
18
+ "base-uri 'none'",
19
+ "frame-ancestors 'none'",
20
+ ].join("; ");
21
+
22
+ const CSP_HEADERS: Readonly<Record<string, string>> = {
23
+ "content-security-policy": UI_CSP,
24
+ "x-content-type-options": "nosniff",
25
+ "cache-control": "no-store",
26
+ };
27
+
28
+ let cachedScript: string | undefined;
29
+
30
+ /** The browser module, transpiled from `inspector.ts` and cached for the process. */
31
+ export function getInspectorScript(): string {
32
+ if (cachedScript === undefined) {
33
+ const source = readFileSync(new URL("./inspector.ts", import.meta.url), "utf8");
34
+ cachedScript = new Bun.Transpiler({ loader: "ts", target: "browser" }).transformSync(source);
35
+ }
36
+ return cachedScript;
37
+ }
38
+
39
+ /** The served page: one static document with the layout and the stylesheet inline. */
40
+ export function inspectorPageResponse(): Response {
41
+ const html = `<!doctype html>
42
+ <html lang="en">
43
+ <head>
44
+ <meta charset="utf-8" />
45
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
46
+ <title>prism devtools</title>
47
+ <style>
48
+ :root { color-scheme: light dark; font: 14px/1.45 ui-monospace, monospace; }
49
+ body { margin: 0 auto; max-width: 1200px; padding: 1rem; }
50
+ h1 { font-size: 1.1rem; margin: 0 0 .25rem; } h2 { font-size: .95rem; margin: 1rem 0 .35rem; }
51
+ .hint { color: gray; margin: .1rem 0 .75rem; font-size: .85rem; }
52
+ .layout { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; }
53
+ pre { margin: .2rem 0 0; padding: .4rem; background: color-mix(in srgb, currentColor 7%, transparent); overflow: auto; max-height: 18rem; white-space: pre-wrap; word-break: break-word; }
54
+ button { font: inherit; cursor: pointer; margin: .3rem .3rem 0 0; }
55
+ button:disabled { opacity: .5; cursor: default; }
56
+ textarea { width: 100%; box-sizing: border-box; font: inherit; min-height: 6rem; }
57
+ ul { list-style: none; margin: 0; padding: 0; max-height: 14rem; overflow-y: auto; }
58
+ li { padding: .2rem .4rem; border-radius: 4px; cursor: pointer; }
59
+ li.selected { background: color-mix(in srgb, highlight 30%, transparent); }
60
+ .feed { border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 6px; padding: .35rem; max-height: 22rem; overflow-y: auto; }
61
+ .feed div { padding: .15rem .4rem; margin: .1rem 0; border-left: 3px solid gray; white-space: pre-wrap; word-break: break-word; }
62
+ .status { color: gray; font-size: .85rem; min-height: 1.2rem; }
63
+ .error { color: crimson; }
64
+ @media (max-width: 800px) { .layout { grid-template-columns: 1fr; } }
65
+ </style>
66
+ <script type="module" src="/assets/inspector.js"></script>
67
+ </head>
68
+ <body>
69
+ <h1>prism devtools</h1>
70
+ <p class="hint">read-only over this agent; payloads are host-redacted</p>
71
+ <div class="layout">
72
+ <section>
73
+ <h2>Inspection</h2>
74
+ <div id="inspect-summary" class="status"></div>
75
+ <pre id="inspect"></pre>
76
+ <h2>Sessions</h2>
77
+ <button id="sessions-refresh">Refresh</button>
78
+ <button id="sessions-more" disabled>More</button>
79
+ <div id="sessions-status" class="status"></div>
80
+ <ul id="sessions"></ul>
81
+ <h2>Compare</h2>
82
+ <textarea id="compare-input" spellcheck="false">{"left":{"summary":{"durationMs":120,"errorCount":0,"toolCallCount":1,"status":"completed"}},"right":{"summary":{"durationMs":90,"errorCount":0,"toolCallCount":1,"status":"completed"}}}</textarea>
83
+ <button id="compare-run">Compare</button>
84
+ <pre id="compare-out"></pre>
85
+ </section>
86
+ <section>
87
+ <h2>Entries <span id="replay-title" class="status"></span></h2>
88
+ <button id="replay-more" disabled>Next page</button>
89
+ <div id="replay-status" class="status"></div>
90
+ <div id="replay" class="feed"></div>
91
+ <h2>Live events</h2>
92
+ <div id="live-status" class="status">select a session to follow its events</div>
93
+ <div id="live" class="feed"></div>
94
+ </section>
95
+ </div>
96
+ </body>
97
+ </html>
98
+ `;
99
+ return new Response(html, { status: 200, headers: { "content-type": "text/html; charset=utf-8", ...CSP_HEADERS } });
100
+ }
101
+
102
+ /** The browser module. */
103
+ export function inspectorScriptResponse(): Response {
104
+ return new Response(getInspectorScript(), {
105
+ status: 200,
106
+ headers: { "content-type": "text/javascript; charset=utf-8", ...CSP_HEADERS },
107
+ });
108
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Browser module for the devtools page. It has no imports: it reads the JSON routes on this origin and
3
+ * renders with text nodes only, so no session or event payload becomes markup.
4
+ */
5
+
6
+ /** Newest live events kept on screen; older rows drop off the top. */
7
+ export const LIVE_FEED_LIMIT = 500;
8
+ /** Entries per replay page. */
9
+ export const REPLAY_PAGE_SIZE = 100;
10
+ const SESSIONS_PAGE_SIZE = 20;
11
+
12
+ /** A one-line label for a session entry or event: its `type`, and its `id` when it has one. */
13
+ export function describeRecord(value: unknown): string {
14
+ if (!value || typeof value !== "object") return String(value);
15
+ const record = value as { type?: unknown; id?: unknown };
16
+ const kind = typeof record.type === "string" ? record.type : "record";
17
+ return typeof record.id === "string" ? `${kind} ${record.id}` : kind;
18
+ }
19
+
20
+ export function formatJson(value: unknown): string {
21
+ return JSON.stringify(value, null, 2) ?? "undefined";
22
+ }
23
+
24
+ function errorMessage(body: unknown): string {
25
+ const message = (body as { error?: { message?: unknown } } | undefined)?.error?.message;
26
+ return typeof message === "string" ? message : "request failed";
27
+ }
28
+
29
+ /** Mounts the page into `doc`. Every request is same-origin and relative. */
30
+ export function mount(doc: Document): void {
31
+ const byId = <T extends HTMLElement>(id: string): T => {
32
+ const node = doc.getElementById(id);
33
+ if (!node) throw new Error(`missing #${id}`);
34
+ return node as T;
35
+ };
36
+ const inspect = byId<HTMLPreElement>("inspect");
37
+ const inspectSummary = byId<HTMLDivElement>("inspect-summary");
38
+ const sessions = byId<HTMLUListElement>("sessions");
39
+ const sessionsMore = byId<HTMLButtonElement>("sessions-more");
40
+ const sessionsStatus = byId<HTMLDivElement>("sessions-status");
41
+ const replay = byId<HTMLDivElement>("replay");
42
+ const replayMore = byId<HTMLButtonElement>("replay-more");
43
+ const replayStatus = byId<HTMLDivElement>("replay-status");
44
+ const replayTitle = byId<HTMLSpanElement>("replay-title");
45
+ const live = byId<HTMLDivElement>("live");
46
+ const liveStatus = byId<HTMLDivElement>("live-status");
47
+ const compareInput = byId<HTMLTextAreaElement>("compare-input");
48
+ const compareOut = byId<HTMLPreElement>("compare-out");
49
+
50
+ let selected: string | undefined;
51
+ let replayCursor: string | undefined;
52
+ let sessionsCursor: string | undefined;
53
+ let source: EventSource | undefined;
54
+
55
+ async function getJson(path: string, init?: RequestInit): Promise<unknown> {
56
+ const response = await fetch(path, init);
57
+ const body: unknown = await response.json().catch(() => undefined);
58
+ if (!response.ok) throw new Error(`${response.status}: ${errorMessage(body)}`);
59
+ return body;
60
+ }
61
+
62
+ async function loadInspect(): Promise<void> {
63
+ const info = (await getJson("/api/inspect")) as Record<string, unknown[] | undefined>;
64
+ const count = (key: string): number => info[key]?.length ?? 0;
65
+ inspectSummary.textContent = `${count("packages")} packages · ${count("tools")} tools · ${count("skills")} skills · ${count("commands")} commands`;
66
+ inspect.textContent = formatJson(info);
67
+ }
68
+
69
+ async function loadSessions(reset: boolean): Promise<void> {
70
+ if (reset) {
71
+ sessionsCursor = undefined;
72
+ sessions.replaceChildren();
73
+ }
74
+ const params = new URLSearchParams({ limit: String(SESSIONS_PAGE_SIZE) });
75
+ if (sessionsCursor !== undefined) params.set("cursor", sessionsCursor);
76
+ const page = (await getJson(`/api/sessions?${params}`)) as { items: Array<{ sessionId: string }>; nextCursor?: string };
77
+ for (const item of page.items) {
78
+ const row = doc.createElement("li");
79
+ row.textContent = item.sessionId;
80
+ row.dataset.session = item.sessionId;
81
+ if (item.sessionId === selected) row.classList.add("selected");
82
+ row.addEventListener("click", () => selectSession(item.sessionId));
83
+ sessions.append(row);
84
+ }
85
+ sessionsCursor = page.nextCursor;
86
+ sessionsMore.disabled = sessionsCursor === undefined;
87
+ sessionsStatus.textContent = page.items.length === 0 && reset ? "no sessions yet" : "";
88
+ }
89
+
90
+ function selectSession(id: string): void {
91
+ selected = id;
92
+ for (const row of sessions.querySelectorAll("li")) row.classList.toggle("selected", row.dataset.session === id);
93
+ replay.replaceChildren();
94
+ replayCursor = undefined;
95
+ replayTitle.textContent = id;
96
+ void loadReplay();
97
+ follow(id);
98
+ }
99
+
100
+ async function loadReplay(): Promise<void> {
101
+ if (selected === undefined) return;
102
+ const params = new URLSearchParams({ session: selected, limit: String(REPLAY_PAGE_SIZE) });
103
+ if (replayCursor !== undefined) params.set("cursor", replayCursor);
104
+ try {
105
+ const page = (await getJson(`/api/replay?${params}`)) as { items: unknown[]; nextCursor?: string };
106
+ for (const item of page.items) {
107
+ const details = doc.createElement("details");
108
+ const summary = doc.createElement("summary");
109
+ summary.textContent = describeRecord(item);
110
+ const body = doc.createElement("pre");
111
+ body.textContent = formatJson(item);
112
+ details.append(summary, body);
113
+ replay.append(details);
114
+ }
115
+ replayCursor = page.nextCursor;
116
+ replayMore.disabled = replayCursor === undefined;
117
+ replayStatus.textContent = page.items.length === 0 && replay.childElementCount === 0 ? "no entries" : "";
118
+ replayStatus.className = "status";
119
+ } catch (error) {
120
+ replayStatus.textContent = error instanceof Error ? error.message : "replay failed";
121
+ replayStatus.className = "status error";
122
+ }
123
+ }
124
+
125
+ function follow(id: string): void {
126
+ source?.close();
127
+ live.replaceChildren();
128
+ const next = new EventSource(`/api/events?session=${encodeURIComponent(id)}`);
129
+ source = next;
130
+ liveStatus.textContent = `following ${id}`;
131
+ for (const name of ["agent", "session"]) {
132
+ next.addEventListener(name, (message) => {
133
+ let label: string;
134
+ try {
135
+ label = describeRecord(JSON.parse((message as MessageEvent<string>).data));
136
+ } catch {
137
+ label = "unreadable event";
138
+ }
139
+ const row = doc.createElement("div");
140
+ row.textContent = `${name}: ${label}`;
141
+ live.append(row);
142
+ // Bounded: the oldest rows drop off so a long run never grows the page without limit.
143
+ while (live.childElementCount > LIVE_FEED_LIMIT) live.firstElementChild?.remove();
144
+ live.scrollTop = live.scrollHeight;
145
+ });
146
+ }
147
+ next.onerror = () => {
148
+ liveStatus.textContent = "stream disconnected; the browser retries";
149
+ };
150
+ }
151
+
152
+ async function runCompare(): Promise<void> {
153
+ try {
154
+ const result = await getJson("/api/compare", {
155
+ method: "POST",
156
+ headers: { "content-type": "application/json" },
157
+ body: compareInput.value,
158
+ });
159
+ compareOut.textContent = formatJson(result);
160
+ } catch (error) {
161
+ compareOut.textContent = error instanceof Error ? error.message : "compare failed";
162
+ }
163
+ }
164
+
165
+ byId<HTMLButtonElement>("sessions-refresh").addEventListener("click", () => void loadSessions(true).catch(reportSessions));
166
+ sessionsMore.addEventListener("click", () => void loadSessions(false).catch(reportSessions));
167
+ replayMore.addEventListener("click", () => void loadReplay());
168
+ byId<HTMLButtonElement>("compare-run").addEventListener("click", () => void runCompare());
169
+
170
+ function reportSessions(error: unknown): void {
171
+ sessionsStatus.textContent = error instanceof Error ? error.message : "sessions failed";
172
+ sessionsStatus.className = "status error";
173
+ }
174
+
175
+ void loadInspect().catch((error: unknown) => {
176
+ inspectSummary.textContent = error instanceof Error ? error.message : "inspect failed";
177
+ inspectSummary.className = "status error";
178
+ });
179
+ void loadSessions(true).catch(reportSessions);
180
+ }
181
+
182
+ if (typeof document !== "undefined" && document.getElementById("inspect") !== null) mount(document);
@@ -0,0 +1,197 @@
1
+ # @arnilo/prism-hosts/driver-process
2
+
3
+ A generic process driver for host-written external-agent adapters. It claims `slot:loop` and runs without a Prism model. No adapter or external binary is bundled.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @arnilo/prism @arnilo/prism-hosts
9
+ ```
10
+
11
+ ## Configuration
12
+
13
+ Create the profile first through `createProfiles({ driver: adapterDriver(adapter) })` from `@arnilo/prism/driver-kit`. Profile sign-in and deployment policy follow the descriptor's auth modes. The driver uses the agent's effective tools and skills registries.
14
+
15
+ | Configuration | Default | Meaning |
16
+ | --- | --- | --- |
17
+ | `name`, `profile` | required | Agent name and existing profile |
18
+ | `binary` | adapter command | Executable path override; command prefix arguments remain |
19
+ | `args` | `[]` | Arguments before the adapter's configured arguments |
20
+ | `cwd` | current directory | Working directory when no workspace is bound |
21
+ | `capture` | `mapped` | Mapped accounting or raw frame events |
22
+ | `graceMs` | `5000` | Cleanup signal grace budget |
23
+ | `vendor` | `{}` | Adapter-specific JSON Schema options; unknown keys fail closed |
24
+ | `isolation` | `strict` | Workspace-file adapters require a bound worktree |
25
+ | `prismTools`, `skills` | none | Selected tool and skill names (`skills` also accepts `all`) |
26
+ | `deployment` | `local` | Auth deployment policy |
27
+ | `profilesRoot`, `principal`, `acknowledgements`, `requires` | driver-kit defaults | Profile, identity, terms, and capability checks |
28
+
29
+ The remaining `ExternalAgentSpec` fields (system prompt, model, effort, built-in tools, subagents, limits) are passed to `configure`. Adapters own their mapping into flags and files.
30
+
31
+ ## What it changes
32
+
33
+ Installing this package claims `slot:loop` with a loop that has `usesModel: false`, so `createAgent` needs no model. It provides a `driver-process:<adapter name>` service whose `inspect()` reports the adapter identity, binary, transport, capture, deployment, isolation, and auth policy. It registers no tools, skills, providers, or events of its own; the vendor agent's activity reaches the shared event stream as `agent.*` events. The adapter owns the mapping from the agent definition to the binary.
34
+
35
+ ## The adapter contract
36
+
37
+ Export a plain `AgentAdapter` object with:
38
+
39
+ - `name`, `revision`, `descriptor`, optional `vendor` schema.
40
+ - `binary: { command, versionArgs?, version(stdout) }` and `profile: { parseStatus }`.
41
+ - `configure(spec, ctx)` returning `LaunchPlan { args?, env?, files?, overlays? }`. Context includes the private `runDir`, profile `home`, `cwd`, selected materialized `skills`, optional MCP `endpoint`, and `hook: { argv, command }`. The command is POSIX quoted. Wrap the neutral skill layout by returning additional files or overlays.
42
+ - `open?(ctx)` for initialization frames, and `encode.prompt(input, ctx)`, optional `encode.steer` and `encode.continue`. Encoding contexts carry optional session and turn IDs; opening also receives selected tool definitions and resume entries.
43
+ - `decode(frame)` returning `Decoded { activity, turnEnd?, sessionId?, turnId?, stop?, unmapped? }`. Activities are observed sequentially. A session-ID signal is recorded in external state.
44
+ - Optional `hooks: { codec, failClosed, timeoutMs? }` for relay callbacks, optional `permissionTool` for MCP permission prompts, and optional JSON-RPC `requests` handlers.
45
+ - `session: { strategy, archive?, restore? }`, `abort` steps (RPC, stdin close, signals), and optional `notices(activity)` limit classification.
46
+
47
+ `adapterDriver(adapter)` exposes the driver-kit definition. `processDriver(adapter)` builds its native package and adds a `driver-process:<adapter.name>` service with `inspect()`. Setup status notes include adapter revision, binary version, transport, capture, deployment, isolation, and auth policy.
48
+
49
+ The driver supports both `jsonl-stream` and `json-rpc`.
50
+
51
+ ## Process lifetime and resume
52
+
53
+ One process is probed at package setup and one process is spawned for each run. Each run also starts a local callback broker. MCP is loaded dynamically only when tools or a permission tool are selected. Skill files are copied each run. This startup and filesystem cost applies even to short turns. Persistent processes are outside this package's current scope. The adapter selects one resume strategy:
54
+
55
+ - `store` requires `archive` and `restore`. The driver archives once per completed turn, including continuations; the final archive runs after graceful process shutdown so transcript writes can flush. Entries use bounded, redacted `vendor-session` external state. A new run restores them into its private run directory. Restore plans accept only `files` and `args`; the driver appends those arguments automatically, and also exposes them as `configure`'s `ctx.resume.args`.
56
+ - `vendor` records decoded session IDs and passes the latest as `ctx.resume.sessionId` and the encoding context's `sessionId`.
57
+ - `none` starts fresh and writes no resume state. Adapters choose this strategy to avoid per-turn archive writes; there is no implicit strategy default.
58
+
59
+ `archive` and `restore` receive `{ runDir, home, cwd, sessionId? }`. Non-empty resume state requires matching binary major and adapter revision; a mismatch fails with `driver_revision_mismatch`. Provenance is stored separately under `driver-revision` before launch, including for runs interrupted after receiving a vendor ID.
60
+
61
+ Archived strings and object keys are checked against all declared protected credential paths, and restored files pass run-directory containment. Adapters are trusted host code: opaque transcript content carries no source provenance, so adapters must select conversation data without reading credential files. Configured secrets are redacted before persistence, and the kernel's external-state byte cap still applies.
62
+
63
+ ## Abort
64
+
65
+ A run abort executes the adapter's declared steps in order. RPC steps send JSON-RPC notifications, stdin steps close the input, and signal steps signal the child. Each step receives a slice of `graceMs`, with two slices reserved for the fallback signal ladder; a hard SIGKILL deadline covers the whole abort budget. Failed interrupt writes do not prevent escalation. RPC steps require `json-rpc`.
66
+
67
+ Normal completion closes stdin and waits up to `graceMs` for flushing before using the fallback signal ladder. It can therefore take roughly twice the grace budget if escalation is needed. An abort during this final flush still executes the abort steps. Classified vendor limits also use the abort ladder, without retry.
68
+
69
+ ## Capabilities
70
+
71
+ The package claims `slot:loop` with `usesModel: false`, and declares `host-ui` when the adapter has JSON-RPC request handlers that route to `host.ui`. It depends on the kernel and on `@arnilo/prism-hosts/mcp-server`, which is imported dynamically only when the spec selects tools or a permission tool.
72
+
73
+ ## Cost, security, and failure behavior
74
+
75
+ One process is probed at package setup and one is spawned per run, even for a short turn. `capture: "all"` emits one `agent.raw` event per unmapped frame; the default `capture: "mapped"` counts them and emits one notice. A `store` adapter writes an archive per completed turn; `none` avoids that write.
76
+
77
+ The kit checks profiles, deployment policy, and required controls before spawn. Child environments use the kit's allow list and strip protected variables. The broker token reaches the child only in the MCP endpoint's named environment variable; neither the endpoint nor inspection contains it. Activity and errors mask the token and configured environment values.
78
+
79
+ Files must be relative to the private run directory. Overlays go through `RunDirectory.overlay`, including Git exclude blocks, and must target disposable workspace paths. All handles close in reverse order. Process cleanup closes stdin and applies the kit's signal ladder before removing materialized files.
80
+
81
+ Malformed adapters throw `ProcessDriverError` `adapter_invalid`, naming the member. Missing or unparsable binaries produce a status note and `driver_unavailable` on run. An exit before the decoded `turnEnd` fails with `vendor_process_exited` and a bounded redacted stderr tail. Stdout JSONL lines are capped at 1 MiB. Invalid JSON is treated as unmapped.
82
+
83
+ ## Gating and fail-closed responses
84
+
85
+ `configure` receives the relay hook command. Its codec maps callbacks to `pre-tool`, `stop`, or `observe`. Only `pre-tool` calls `run.ask`; observed activity never grants permission. Rewrites require `descriptor.controls.rewrite`. Empty effect lists receive all tool effects; adapters should use `effectsTable` for vendor tool names. Response substitution remains unsupported because the current descriptor has no `respond` control. Codec failures and an unreachable broker use the adapter's declared `failClosed`, including protocols that print a deny with exit code zero.
86
+
87
+ Stop callbacks and decoded `stop` signals call `run.end`. Continuations require `continueOnStop`, and decoded stops also require `encode.continue`. The kernel caps them with `limits.maxContinuations`.
88
+
89
+ ## Steering
90
+
91
+ `mid-turn` delivers messages using `encode.steer`; `next-turn` collects messages and sends them as the next prompt after `turnEnd`. `none` emits `steer_unsupported`. Frames, relay callbacks, and steering share an ordered queue. JSON-RPC request handlers run concurrently within the bound described below.
92
+
93
+ ## Capture and unmapped frames
94
+
95
+ The default `capture: "mapped"` counts unmapped frames and emits one `unmapped_frames` notice per run. `capture: "all"` emits one `agent.raw` event per unmapped frame, increasing event and storage costs. Invalid JSON uses the kit's redacted, 256-character preview. Valid raw frames and mapped activity are redacted before observation.
96
+
97
+ ## Rate limits and quotas
98
+
99
+ `notices` classifies decoded notice activity. Rate-limit, quota, billing, and auth signals reach the profile guard and fail with `vendor_limit`; `ProcessDriverError.deferUntil` carries a deferral date when supplied. The process is stopped without retry. The declared abort steps precede the fallback signal ladder within the abort deadline. A throwing classifier also fails the run and reaps the process.
100
+
101
+
102
+ ## Transports
103
+
104
+ `jsonl-stream` writes encoded JSON to stdin and decodes stdout lines. `json-rpc` uses a JSON-RPC 2.0 peer over the same stdio pipes. Its encoders return `{ method, params?, notify?, onResult? }`. `notify: true` sends a notification; otherwise the driver sends a request. Results go through `onResult(result)` when supplied, or directly through `decode(result)` otherwise. An `onResult` returning `undefined` ignores an acknowledgement. Notification envelopes reach `decode` in wire order, including their `method` and `params`.
105
+
106
+ `open(ctx)` frames run sequentially before the first prompt. Each request waits for its reply and applies decoded session/turn IDs before the next opening frame or prompt. Prompt, steer, and continuation requests keep the reader running while replies are outstanding, so approval callbacks and turn-completion notifications cannot deadlock a pending request. A decoded result can also end a turn without a completion notification.
107
+
108
+ Both transports share capture, steering, stop/continue, redaction, and process cleanup. JSON-RPC lines retain the 1 MiB cap. At most 256 notification/result frames may wait for consumption; exceeding this bound fails the run rather than dropping frames.
109
+
110
+ ## Server-to-client requests
111
+
112
+ Every JSON-RPC request needs an own entry in `adapter.requests`. Each handler receives `{ params, run, host, bridge, ask, tools, sessionId?, turnId? }`; it receives neither the peer nor the broker token. These types are exported as `RequestContext` and `RequestHandler`.
113
+
114
+ Use `ask(request)` for approvals: it calls `run.ask` with the adapter's rewrite support, preserving `tool.call` hooks and external origin. Without a UI, the kernel denies or suspends according to whether the loop is resumable. Use `host.ui.request` for questions and elicitation; the process package declares `host-ui` when request handlers are present. Use `bridge.invoke(call)` for client tools; only `spec.prismTools` are bridged, and execution goes through `run.executeTools`.
115
+
116
+ Up to 8 handlers run concurrently. Excess concurrent requests receive a JSON-RPC error and fail the run. Unknown methods receive `-32601` before the run fails with `vendor_request_unhandled`, naming the method. A throwing handler receives `-32603` before the run fails with `vendor_request_failed`; error text is redacted. These failures are never retried. Adapters that use `adapterDriver` inside their own package must declare that package's `host-ui` capability before calling `host.ui`.
117
+
118
+ ## Extending an adapter
119
+
120
+ `extendAdapter(base, overrides)` creates a new adapter at definition time without changing the base. Every extension requires its own `name` and `revision`.
121
+
122
+ ```ts
123
+ import { extendAdapter } from "@arnilo/prism-hosts/driver-process";
124
+
125
+ const custom = extendAdapter(adapter, {
126
+ name: "my-extended-adapter",
127
+ revision: "1",
128
+ configure: (baseConfigure) => async (spec, ctx) => {
129
+ const plan = await baseConfigure(spec, ctx);
130
+ return { ...plan, args: [...(plan.args ?? []), "--quiet"] };
131
+ },
132
+ decode: { replace: (frame) => decodeCustomFrame(frame) },
133
+ descriptor: {
134
+ auth: {
135
+ modes: adapter.descriptor.auth.modes.map((mode) => ({ ...mode, deployments: ["local"] })),
136
+ },
137
+ },
138
+ });
139
+ ```
140
+
141
+ For `configure`, `decode`, `open`, and `notices`, a bare function is a `(baseFunction) => newFunction` factory, called once. Use `{ replace: fn }` to replace a function directly or introduce an absent optional function. Wrapping an absent function fails with `adapter_invalid`; a wrapper must return a function. The explicit replacement form avoids guessing from function arity or executing a decoder during definition.
142
+
143
+ Object members (`binary`, `profile`, `encode`, `hooks`, `session`, `requests`) merge one level; functions inside those objects replace directly. The descriptor merges its `controls`, `capture`, and `auth` fields one level. Arrays, including `abort` and auth `modes`, replace as a whole; they never concatenate or merge by index. Other members replace directly.
144
+
145
+ Auth overrides may remove modes or deployments, add hosted acknowledgements, or add protected paths and variables. They cannot introduce modes, change a mode's kind or home variable, remove acknowledgements or protections, or enable another deployment (`adapter_invalid: policy_widened`). The merged adapter is validated, and setup checks `requires` against its descriptor. Adapters remain trusted host code: keep their policy data unchanged after definition.
146
+
147
+ The result records `extends: { name, revision, extends? }`. Inspection status notes and the `driver-process:<name>` service include the full chain beside the extension's identity.
148
+
149
+ ## Testing your adapter
150
+
151
+ Import the offline suite separately so production imports do not load testing code:
152
+
153
+ ```ts
154
+ import { adapterConformance } from "@arnilo/prism-hosts/driver-process/testing";
155
+
156
+ const result = await adapterConformance(myAdapter, {
157
+ dialect: myDialect,
158
+ fixtures: {
159
+ config: (cli) => ({ binary: cli.command[0], args: cli.command.slice(1) }),
160
+ recorded: "fixtures/my-agent.json",
161
+ },
162
+ });
163
+ ```
164
+
165
+ Run this in the host's CI against fixtures from `recordFixtures.finish` in
166
+ `@arnilo/prism/testing`. The result lists the kernel driver legs plus fixture
167
+ replay, unmapped capture, declared fail-closed response, unknown RPC request,
168
+ abort, resume, hosted acknowledgements, and rate-limit checks. Failures throw
169
+ `AdapterConformanceError` with the failing `leg`; unavailable legs include a
170
+ skip reason. The credential canary retains the kernel suite's filesystem atime
171
+ limitation.
172
+
173
+ The dialect describes the binary's wire. `fixtures.scriptFor(activity)` can
174
+ return raw steps when the dialect's `frames` cannot map a neutral activity.
175
+ `fixtures.home` supplies the actual hook, skill, and MCP paths planted by the
176
+ strict isolation check. Command-hook dialects that print deny with exit zero
177
+ must supply `hook.allowed({ exitCode, stdout })` so the fake binary honors that
178
+ response. Without it, the binary uses the exit code.
179
+
180
+ ## Example
181
+
182
+ ```ts
183
+ import { createAgent } from "@arnilo/prism";
184
+ import { processDriver } from "@arnilo/prism-hosts/driver-process";
185
+ import { adapter } from "./my-adapter.ts";
186
+
187
+ const agent = await createAgent({
188
+ packages: [processDriver(adapter)({ name: "worker", profile: "me" })],
189
+ });
190
+ ```
191
+
192
+ ## Related
193
+
194
+ - Writing an adapter: the contract, the mappings, and the dated worked mappings for the three researched binaries.
195
+ - drivers: the kernel driver kit this package builds on.
196
+ - Reference adapters: `stream-cli.ts` (shape A), `rpc-server.ts` (shape B), `workspace-config.ts` (shape C).
197
+ - Extending an adapter: a host derives a new adapter from the rpc-server reference with `extendAdapter` and runs it through `processDriver`.
@@ -0,0 +1,74 @@
1
+ import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { signalLadder } from "@arnilo/prism/driver-kit";
3
+ import type { AgentAdapter, EncodeContext } from "./adapter.js";
4
+ import type { Transport } from "./transports/types.js";
5
+
6
+ /** Exit-aware waits clear their timers as soon as the child is reaped. */
7
+ function wait(exited: Promise<void>, ms: number): Promise<void> {
8
+ return new Promise((resolve) => {
9
+ const timer = setTimeout(resolve, Math.max(0, ms));
10
+ void exited.then(() => {
11
+ clearTimeout(timer);
12
+ resolve();
13
+ });
14
+ });
15
+ }
16
+
17
+ export function processShutdown(
18
+ child: ChildProcessWithoutNullStreams,
19
+ exited: Promise<void>,
20
+ adapter: AgentAdapter,
21
+ transport: Transport,
22
+ encoding: EncodeContext,
23
+ graceMs: number,
24
+ ) {
25
+ let stopped = false;
26
+ void exited.then(() => {
27
+ stopped = true;
28
+ });
29
+ let stopping: Promise<void> | undefined;
30
+ let aborting: Promise<void> | undefined;
31
+ const abort = () =>
32
+ (aborting ??= (async () => {
33
+ if (stopped || child.pid === undefined) {
34
+ await exited;
35
+ return;
36
+ }
37
+ const deadline = Date.now() + graceMs;
38
+ const hardKill = setTimeout(() => child.kill("SIGKILL"), graceMs);
39
+ try {
40
+ const slice = graceMs / (adapter.abort.length + 2);
41
+ for (const step of adapter.abort) {
42
+ if (stopped || Date.now() >= deadline) break;
43
+ const action = async () => {
44
+ if ("rpc" in step) await transport.send({ method: step.rpc, params: step.params?.(encoding), notify: true });
45
+ else if ("closeStdin" in step) child.stdin.end();
46
+ else child.kill(step.signal);
47
+ };
48
+ const pause = wait(exited, Math.min(slice, Math.max(0, deadline - Date.now())));
49
+ // A broken interrupt channel must not prevent later signals or the hard kill.
50
+ await Promise.race([action().catch(() => undefined), pause]);
51
+ await pause;
52
+ }
53
+ if (!stopped && Date.now() < deadline) await signalLadder(child, { graceMs: Math.max(1, Math.floor((deadline - Date.now()) / 2)) });
54
+ await exited;
55
+ } finally {
56
+ clearTimeout(hardKill);
57
+ }
58
+ })());
59
+ const shutdown = (graceful: boolean) =>
60
+ (stopping ??= (async () => {
61
+ if (stopped || child.pid === undefined) {
62
+ await exited;
63
+ return;
64
+ }
65
+ if (graceful) {
66
+ child.stdin.end();
67
+ await wait(exited, graceMs);
68
+ }
69
+ if (aborting) await aborting;
70
+ else if (!stopped) await signalLadder(child, { graceMs: Math.max(1, Math.floor(graceMs / 2)) });
71
+ await exited;
72
+ })());
73
+ return { abort, graceful: () => shutdown(true), failure: () => shutdown(false) };
74
+ }