@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,238 @@
1
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { join, sep } from "node:path";
3
+ import { tokens } from "./text.js";
4
+
5
+ /** Kernel pages that describe retired contracts or are templates; the generator leaves the same ones out. */
6
+ const EXCLUDED_DOCS = [/^api-page-template\.md$/, /^release-.*-evidence\.md$/, /^migrate-to-0\.(5|6|7|8|9|11)\.md$/, /^migration\.md$/];
7
+ const KERNEL = "@arnilo/prism";
8
+ const MAX_PAGE_BYTES = 1024 * 1024;
9
+ const MAX_HITS = 5;
10
+ const EXCERPT_CHARS = 1200;
11
+
12
+ /** One readable page: `package` is `@arnilo/prism`, `path` is relative to that package (`docs/agent.md`, `README.md`). */
13
+ export interface DocPage {
14
+ readonly package: string;
15
+ readonly path: string;
16
+ /** Project-relative, as the indexes write it: `node_modules/@arnilo/prism/docs/agent.md`. */
17
+ readonly display: string;
18
+ /** The resource URI: `prism-docs://prism/docs/agent.md`. */
19
+ readonly uri: string;
20
+ readonly file: string;
21
+ }
22
+
23
+ export interface DocHit {
24
+ readonly page: string;
25
+ readonly heading: string;
26
+ /** `prism-docs://prism/docs/agent.md#heading-slug` */
27
+ readonly uri: string;
28
+ readonly excerpt: string;
29
+ readonly score: number;
30
+ }
31
+
32
+ export interface DocsResult {
33
+ readonly found: boolean;
34
+ readonly hits: readonly DocHit[];
35
+ readonly note?: string;
36
+ }
37
+
38
+ export function docUri(pkg: string, path: string): string {
39
+ return `prism-docs://${pkg.replace(/^@arnilo\//, "")}/${path}`;
40
+ }
41
+
42
+ /** The real path of `<root>/node_modules/@arnilo`'s parent: nothing outside `node_modules` may be read. */
43
+ function nodeModulesReal(root: string): string | undefined {
44
+ try {
45
+ return realpathSync(join(root, "node_modules"));
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Reads `file` only when its real path (symlinks resolved) is a regular file inside both the project's
53
+ * `node_modules` and the real directory of the package it claims to belong to. A link that leaves either is refused.
54
+ */
55
+ export function readInside(root: string, packageDir: string, file: string): string | undefined {
56
+ const modules = nodeModulesReal(root);
57
+ if (modules === undefined) return undefined;
58
+ try {
59
+ const realPackage = realpathSync(packageDir);
60
+ const realFile = realpathSync(file);
61
+ if (!realFile.startsWith(modules + sep) || !realPackage.startsWith(modules + sep)) return undefined;
62
+ if (!realFile.startsWith(realPackage + sep)) return undefined;
63
+ const stat = statSync(realFile);
64
+ if (!stat.isFile() || stat.size > MAX_PAGE_BYTES) return undefined;
65
+ return readFileSync(realFile, "utf8");
66
+ } catch {
67
+ return undefined;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * The pages installed under `<root>/node_modules/@arnilo/`: each package's `README.md` and, for the kernel, the
73
+ * top-level `docs/*.md` pages that describe the current contract. Lists names only; it reads no file.
74
+ */
75
+ export function listDocPages(root: string): DocPage[] {
76
+ const scope = join(root, "node_modules", "@arnilo");
77
+ if (!existsSync(scope)) return [];
78
+ const pages: DocPage[] = [];
79
+ const names = readdirSync(scope).sort();
80
+ for (const name of names) {
81
+ const pkg = `@arnilo/${name}`;
82
+ const dir = join(scope, name);
83
+ const add = (path: string) => {
84
+ const file = join(dir, ...path.split("/"));
85
+ if (existsSync(file)) pages.push({ package: pkg, path, display: `node_modules/${pkg}/${path}`, uri: docUri(pkg, path), file });
86
+ };
87
+ add("README.md");
88
+ try {
89
+ const manifest = JSON.parse(readInside(root, dir, join(dir, "package.json")) ?? "{}");
90
+ for (const path of manifest.files ?? []) {
91
+ if (typeof path === "string" && /^[a-zA-Z0-9_-]+\/README\.md$/.test(path)) add(path);
92
+ }
93
+ } catch {
94
+ // An unreadable or malformed manifest contributes no bundle pages.
95
+ }
96
+ if (pkg === KERNEL) {
97
+ const docsDir = join(dir, "docs");
98
+ if (!existsSync(docsDir)) continue;
99
+ for (const entry of readdirSync(docsDir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
100
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
101
+ if (!entry.name.endsWith(".md") || EXCLUDED_DOCS.some((pattern) => pattern.test(entry.name))) continue;
102
+ add(`docs/${entry.name}`);
103
+ }
104
+ }
105
+ }
106
+ return pages;
107
+ }
108
+
109
+ /** The text of a listed page by resource URI, or `undefined` for a page that is not listed or leaves `node_modules`. */
110
+ export function readDocPage(
111
+ root: string,
112
+ pages: readonly DocPage[],
113
+ uri: string,
114
+ ): { readonly page: DocPage; readonly text: string } | undefined {
115
+ const page = pages.find((candidate) => candidate.uri === uri);
116
+ if (page === undefined) return undefined;
117
+ const text = readInside(root, join(root, "node_modules", page.package), page.file);
118
+ return text === undefined ? undefined : { page, text };
119
+ }
120
+
121
+ interface Section {
122
+ readonly page: DocPage;
123
+ readonly heading: string;
124
+ readonly anchor: string;
125
+ readonly body: string;
126
+ readonly headingTokens: ReadonlySet<string>;
127
+ readonly lower: string;
128
+ }
129
+
130
+ /** GitHub-style anchor for a heading. */
131
+ export function slug(heading: string): string {
132
+ return heading
133
+ .toLowerCase()
134
+ .replace(/`/g, "")
135
+ .replace(/[^a-z0-9 _-]/g, "")
136
+ .trim()
137
+ .replace(/ /g, "-");
138
+ }
139
+
140
+ function sectionsOf(page: DocPage, markdown: string): Section[] {
141
+ const sections: Section[] = [];
142
+ let heading = page.path;
143
+ let lines: string[] = [];
144
+ let fence = false;
145
+ const flush = () => {
146
+ const body = lines.join("\n").trim();
147
+ if (body !== "") {
148
+ sections.push({
149
+ page,
150
+ heading,
151
+ anchor: slug(heading),
152
+ body,
153
+ headingTokens: new Set(tokens(heading)),
154
+ lower: `${heading}\n${body}`.toLowerCase(),
155
+ });
156
+ }
157
+ lines = [];
158
+ };
159
+ for (const line of markdown.split("\n")) {
160
+ if (/^\s*(```|~~~)/.test(line)) fence = !fence;
161
+ const match = fence ? null : /^(#{1,4})\s+(.+?)\s*#*$/.exec(line);
162
+ if (match) {
163
+ flush();
164
+ heading = (match[2] ?? "").trim();
165
+ } else lines.push(line);
166
+ }
167
+ flush();
168
+ return sections;
169
+ }
170
+
171
+ /** The excerpt window of a section: from the first matching line, capped. */
172
+ function excerptOf(section: Section, words: readonly string[]): string {
173
+ const lines = section.body.split("\n");
174
+ const first = Math.max(
175
+ 0,
176
+ lines.findIndex((line) => words.some((word) => line.toLowerCase().includes(word))),
177
+ );
178
+ const text = lines.slice(first).join("\n");
179
+ return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS)} …` : text;
180
+ }
181
+
182
+ /** A lexical docs search over the pages under one project root. The index builds on the first `search` and is kept. */
183
+ export class DocsIndex {
184
+ private sections: Section[] | undefined;
185
+ private pages: DocPage[] | undefined;
186
+
187
+ constructor(private readonly root: string) {}
188
+
189
+ listPages(): readonly DocPage[] {
190
+ this.pages ??= listDocPages(this.root);
191
+ return this.pages;
192
+ }
193
+
194
+ read(uri: string): { readonly page: DocPage; readonly text: string } | undefined {
195
+ return readDocPage(this.root, this.listPages(), uri);
196
+ }
197
+
198
+ private build(): Section[] {
199
+ if (this.sections) return this.sections;
200
+ const built: Section[] = [];
201
+ for (const page of this.listPages()) {
202
+ const text = readInside(this.root, join(this.root, "node_modules", page.package), page.file);
203
+ if (text !== undefined) built.push(...sectionsOf(page, text));
204
+ }
205
+ this.sections = built;
206
+ return built;
207
+ }
208
+
209
+ /** Ranked, heading-anchored excerpts. A heading hit outranks a body hit; every query word must appear somewhere in the section. */
210
+ search(query: string): DocsResult {
211
+ const words = [...new Set(tokens(query))];
212
+ if (words.length === 0) return { found: false, hits: [], note: "pass a query of at least one word" };
213
+ const sections = this.build();
214
+ if (sections.length === 0) {
215
+ return { found: false, hits: [], note: `no @arnilo packages are installed under ${this.root}/node_modules` };
216
+ }
217
+ const hits: Array<DocHit & { order: number }> = [];
218
+ sections.forEach((section, order) => {
219
+ let score = 0;
220
+ for (const word of words) {
221
+ if (!section.lower.includes(word)) return;
222
+ score += section.headingTokens.has(word) ? 8 : 0;
223
+ score += Math.min(5, section.lower.split(word).length - 1);
224
+ }
225
+ hits.push({
226
+ page: section.page.display,
227
+ heading: section.heading,
228
+ uri: `${section.page.uri}#${section.anchor}`,
229
+ excerpt: excerptOf(section, words),
230
+ score,
231
+ order,
232
+ });
233
+ });
234
+ hits.sort((a, b) => b.score - a.score || a.order - b.order);
235
+ if (hits.length === 0) return { found: false, hits: [], note: "no section contains every word of the query" };
236
+ return { found: true, hits: hits.slice(0, MAX_HITS).map(({ order: _order, ...hit }) => hit) };
237
+ }
238
+ }
@@ -0,0 +1,92 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import type { ErrorCodeRecord, ErrorsIndex } from "../indexes.js";
4
+ import { nearest } from "./text.js";
5
+
6
+ export interface PitfallRow {
7
+ readonly code: string;
8
+ readonly whatHappened: string;
9
+ readonly fix: string;
10
+ }
11
+
12
+ export interface ErrorsResult {
13
+ readonly found: boolean;
14
+ readonly matches: readonly ErrorMatch[];
15
+ readonly nearest: readonly string[];
16
+ readonly note?: string;
17
+ }
18
+
19
+ export interface ErrorMatch {
20
+ readonly code: string;
21
+ readonly package: string;
22
+ /** The declaring file and line: `src/driver-kit/errors.ts:26`. */
23
+ readonly declared: string;
24
+ readonly errorClass: string | null;
25
+ readonly meaning: string | null;
26
+ readonly sampleMessage: string | null;
27
+ readonly docs: readonly string[];
28
+ /** From `references/pitfalls.md`, when the skill lists the code. */
29
+ readonly pitfall?: { readonly whatHappened: string; readonly fix: string };
30
+ }
31
+
32
+ const PITFALLS_FILE = new URL("../../skills/prism-host-builder/references/pitfalls.md", import.meta.url);
33
+
34
+ let pitfallsCache: ReadonlyMap<string, PitfallRow> | undefined;
35
+
36
+ /** Rows of every markdown table whose first column is a backticked code. */
37
+ export function parsePitfalls(markdown: string): Map<string, PitfallRow> {
38
+ const rows = new Map<string, PitfallRow>();
39
+ for (const line of markdown.split("\n")) {
40
+ const cells = line
41
+ .trim()
42
+ .replace(/^\||\|$/g, "")
43
+ .split(/(?<!\\)\|/)
44
+ .map((cell) => cell.trim());
45
+ if (cells.length < 3) continue;
46
+ const code = /^`([A-Za-z0-9_]+)`$/.exec(cells[0] ?? "")?.[1];
47
+ if (code === undefined || rows.has(code)) continue;
48
+ rows.set(code, { code, whatHappened: cells[1] ?? "", fix: cells.slice(2).join(" | ") });
49
+ }
50
+ return rows;
51
+ }
52
+
53
+ /** The pitfalls the skill ships, read once. An absent file (a tree without the skill) yields no rows. */
54
+ export function loadPitfalls(): ReadonlyMap<string, PitfallRow> {
55
+ const file = fileURLToPath(PITFALLS_FILE);
56
+ pitfallsCache ??= existsSync(file) ? parsePitfalls(readFileSync(file, "utf8")) : new Map();
57
+ return pitfallsCache;
58
+ }
59
+
60
+ function toMatch(record: ErrorCodeRecord, pitfalls: ReadonlyMap<string, PitfallRow>): ErrorMatch {
61
+ const pitfall = pitfalls.get(record.code);
62
+ return {
63
+ code: record.code,
64
+ package: record.package,
65
+ declared: `${record.file}:${record.line}`,
66
+ errorClass: record.errorClass,
67
+ meaning: record.meaning,
68
+ sampleMessage: record.sampleMessage,
69
+ docs: record.docs,
70
+ ...(pitfall !== undefined ? { pitfall: { whatHappened: pitfall.whatHappened, fix: pitfall.fix } } : {}),
71
+ };
72
+ }
73
+
74
+ /**
75
+ * An error code's meaning, owner, declaration site, docs and the fix `pitfalls.md` lists. The match is exact
76
+ * and case-sensitive. A code can be declared by more than one package, so the result is a list. An unknown code
77
+ * returns `found: false` and the nearest codes, never an exception.
78
+ */
79
+ export function lookupError(index: ErrorsIndex, code: string, pitfalls: ReadonlyMap<string, PitfallRow> = loadPitfalls()): ErrorsResult {
80
+ const wanted = code.trim();
81
+ const exact = index.codes.filter((record) => record.code === wanted);
82
+ if (exact.length > 0) return { found: true, matches: exact.map((record) => toMatch(record, pitfalls)), nearest: [] };
83
+ return {
84
+ found: false,
85
+ matches: [],
86
+ nearest: nearest(
87
+ index.codes.map((record) => record.code),
88
+ wanted,
89
+ ),
90
+ note: `no error code "${wanted}"`,
91
+ };
92
+ }
@@ -0,0 +1,117 @@
1
+ import { HostBuilderError } from "../errors.js";
2
+ import type { ExampleRecord, ExamplesIndex, LoadHostBuilderIndexOptions } from "../indexes.js";
3
+ import { readExampleSource } from "../indexes.js";
4
+ import { byteLength, MAX_RESULT_BYTES, truncateBytes, truncationMarker } from "./bound.js";
5
+ import { nearest, tokens } from "./text.js";
6
+
7
+ export interface ExamplesQuery {
8
+ /** Words matched against the example path, title and imported packages. */
9
+ readonly query?: string;
10
+ /** Only examples that import this package. */
11
+ readonly package?: string;
12
+ /** An indexed example path (`examples/define-package.ts`): returns its source. */
13
+ readonly path?: string;
14
+ }
15
+
16
+ export interface ExampleMatch extends Pick<ExampleRecord, "path" | "title" | "imports" | "needsCredentials" | "requiresEnv" | "gate"> {}
17
+
18
+ export interface ExamplesResult {
19
+ readonly found: boolean;
20
+ readonly matches: readonly ExampleMatch[];
21
+ readonly nearest: readonly string[];
22
+ /** The verbatim source, when `path` was given and found. */
23
+ readonly source?: string;
24
+ readonly truncated?: boolean;
25
+ readonly note?: string;
26
+ }
27
+
28
+ const MAX_MATCHES = 15;
29
+ /** Leaves room for the JSON envelope around the source. */
30
+ const SOURCE_BUDGET = MAX_RESULT_BYTES - 4096;
31
+
32
+ function toMatch(example: ExampleRecord): ExampleMatch {
33
+ return {
34
+ path: example.path,
35
+ title: example.title,
36
+ imports: example.imports,
37
+ needsCredentials: example.needsCredentials,
38
+ requiresEnv: example.requiresEnv,
39
+ gate: example.gate,
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Ranked examples, or one example's source. `path` resolves only to a path `examples.json` lists (an example or
45
+ * a support file), so anything else, including a traversal, is "not found". Without `path`, `query` and
46
+ * `package` filter and rank the examples.
47
+ */
48
+ export async function lookupExamples(
49
+ index: ExamplesIndex,
50
+ input: ExamplesQuery,
51
+ options?: LoadHostBuilderIndexOptions,
52
+ ): Promise<ExamplesResult> {
53
+ if (input.path !== undefined) {
54
+ const path = input.path.trim();
55
+ const record = index.examples.find((example) => example.path === path);
56
+ try {
57
+ const raw = await readExampleSource(path, options);
58
+ const cut = truncateBytes(raw, SOURCE_BUDGET);
59
+ const source = cut.truncated ? `${cut.text}${truncationMarker(byteLength(raw) - byteLength(cut.text))}` : cut.text;
60
+ return {
61
+ found: true,
62
+ matches: record !== undefined ? [toMatch(record)] : [],
63
+ nearest: [],
64
+ source,
65
+ ...(cut.truncated ? { truncated: true } : {}),
66
+ ...(record === undefined ? { note: "support file of an example, not an example itself" } : {}),
67
+ };
68
+ } catch (error) {
69
+ if (!(error instanceof HostBuilderError) || error.code !== "ERR_PRISM_HOST_BUILDER_EXAMPLE") throw error;
70
+ return {
71
+ found: false,
72
+ matches: [],
73
+ nearest: nearest([...index.examples.map((example) => example.path), ...index.support], path),
74
+ note: `"${path}" is not an indexed example`,
75
+ };
76
+ }
77
+ }
78
+ const pool =
79
+ input.package === undefined ? index.examples : index.examples.filter((example) => example.imports.includes(input.package as string));
80
+ const words = tokens(input.query ?? "");
81
+ if (words.length === 0) {
82
+ const matches = pool.slice(0, MAX_MATCHES).map(toMatch);
83
+ return {
84
+ found: matches.length > 0,
85
+ matches,
86
+ nearest: [],
87
+ ...(pool.length > MAX_MATCHES ? { note: `${pool.length - MAX_MATCHES} more; narrow with query or package` } : {}),
88
+ ...(matches.length === 0 ? { note: "no example imports that package" } : {}),
89
+ };
90
+ }
91
+ const scored: Array<{ example: ExampleRecord; score: number }> = [];
92
+ for (const example of pool) {
93
+ const path = example.path.toLowerCase();
94
+ const title = tokens(example.title);
95
+ const imports = example.imports.join(" ").toLowerCase();
96
+ let score = 0;
97
+ for (const word of words) {
98
+ if (title.includes(word)) score += 6;
99
+ if (path.includes(word)) score += 4;
100
+ if (imports.includes(word)) score += 2;
101
+ }
102
+ if (score > 0) scored.push({ example, score });
103
+ }
104
+ scored.sort((a, b) => b.score - a.score);
105
+ if (scored.length === 0) {
106
+ return {
107
+ found: false,
108
+ matches: [],
109
+ nearest: nearest(
110
+ pool.map((example) => example.path),
111
+ (input.query ?? "").trim(),
112
+ ),
113
+ note: "no example matched the query",
114
+ };
115
+ }
116
+ return { found: true, matches: scored.slice(0, MAX_MATCHES).map((entry) => toMatch(entry.example)), nearest: [] };
117
+ }
@@ -0,0 +1,60 @@
1
+ /** Lower-case word tokens of `text`, splitting camelCase, snake_case, kebab-case and punctuation. */
2
+ export function tokens(text: string): string[] {
3
+ return text
4
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
5
+ .toLowerCase()
6
+ .split(/[^a-z0-9]+/)
7
+ .filter((token) => token.length > 1);
8
+ }
9
+
10
+ /** Levenshtein distance, capped: returns `cap + 1` as soon as the distance must exceed `cap`. */
11
+ function distance(a: string, b: string, cap: number): number {
12
+ if (Math.abs(a.length - b.length) > cap) return cap + 1;
13
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
14
+ for (let i = 1; i <= a.length; i++) {
15
+ const row = [i];
16
+ let best = i;
17
+ for (let j = 1; j <= b.length; j++) {
18
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
19
+ const value = Math.min((previous[j] ?? 0) + 1, (row[j - 1] ?? 0) + 1, (previous[j - 1] ?? 0) + cost);
20
+ row.push(value);
21
+ if (value < best) best = value;
22
+ }
23
+ if (best > cap) return cap + 1;
24
+ previous = row;
25
+ }
26
+ return previous[b.length] ?? cap + 1;
27
+ }
28
+
29
+ /**
30
+ * The `limit` names closest to `target`: a substring either way ranks first, then small edit distance.
31
+ * Pure and deterministic; ties keep input order.
32
+ */
33
+ export function nearest(names: Iterable<string>, target: string, limit = 5): string[] {
34
+ const wanted = target.toLowerCase();
35
+ const scored: Array<{ name: string; score: number; order: number }> = [];
36
+ const seen = new Set<string>();
37
+ let order = 0;
38
+ for (const name of names) {
39
+ if (seen.has(name)) continue;
40
+ seen.add(name);
41
+ const lower = name.toLowerCase();
42
+ let score: number;
43
+ if (lower === wanted) score = 0;
44
+ else if (lower.includes(wanted) || (lower.length >= 4 && wanted.includes(lower))) score = 1;
45
+ else {
46
+ const cap = Math.max(2, Math.floor(wanted.length / 3));
47
+ const d = distance(lower, wanted, cap);
48
+ if (d > cap) {
49
+ order++;
50
+ continue;
51
+ }
52
+ score = 1 + d;
53
+ }
54
+ scored.push({ name, score, order: order++ });
55
+ }
56
+ return scored
57
+ .sort((a, b) => a.score - b.score || a.order - b.order)
58
+ .slice(0, limit)
59
+ .map((entry) => entry.name);
60
+ }