@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,623 @@
1
+ import { type JsonSchema, type ToolCapabilityKind, type ToolInfo, validateJsonSchema } from "@arnilo/prism";
2
+ import { EvalError } from "./errors.js";
3
+ import type { ExecutionStep, ExecutionTimeline, ScoreResult, Scorer, ScorerInput } from "./types.js";
4
+
5
+ // ─── Caps & Limits ────────────────────────────────────────────────────────────
6
+
7
+ export const DEFAULT_MAX_EXPECTED_CALLS = 64;
8
+ export const HARD_MAX_EXPECTED_CALLS = 256;
9
+
10
+ // ─── ToolCallSpec & Helpers ───────────────────────────────────────────────────
11
+
12
+ export interface ToolCallSpec {
13
+ readonly name: string;
14
+ readonly args?: (actual: Record<string, unknown>) => boolean;
15
+ }
16
+
17
+ export type ToolCallMatchMode = "strict" | "unordered" | "subset" | "superset";
18
+
19
+ export interface ToolCallMatchScorerOptions {
20
+ readonly id?: string;
21
+ readonly mode: ToolCallMatchMode;
22
+ readonly expected?: readonly (string | ToolCallSpec)[];
23
+ readonly deny?: readonly (string | ToolCallSpec)[];
24
+ /** When true, marks failures as invariant violations that fail closed in thresholds. Defaults to true if deny is set. */
25
+ readonly invariant?: boolean;
26
+ }
27
+
28
+ function normalizeSpec(item: string | ToolCallSpec): ToolCallSpec {
29
+ if (typeof item === "string") return { name: item };
30
+ return item;
31
+ }
32
+
33
+ function matchesSpec(step: ExecutionStep, spec: ToolCallSpec): boolean {
34
+ if (step.name !== spec.name) return false;
35
+ if (spec.args) {
36
+ const inputObj = (typeof step.input === "object" && step.input !== null ? step.input : {}) as Record<string, unknown>;
37
+ return spec.args(inputObj);
38
+ }
39
+ return true;
40
+ }
41
+
42
+ /**
43
+ * Trajectory match scorer evaluating actual timeline tool steps against expected specs.
44
+ *
45
+ * - `"strict"`: exact sequence in exact order (no extras, no missing).
46
+ * - `"unordered"`: exact multiset of expected calls (no extras, order ignored).
47
+ * - `"subset"`: every actual tool call was expected (unexpected/extra tool calls fail).
48
+ * - `"superset"`: every expected tool call was performed (extra tool calls are allowed).
49
+ * - `deny`: forbidden tool specs; if any match, score is immediately 0.
50
+ */
51
+ export function createToolCallMatchScorer<TInput = unknown, TExpected = unknown>(
52
+ options: ToolCallMatchScorerOptions,
53
+ ): Scorer<TInput, TExpected> {
54
+ const mode = options.mode;
55
+ const isInvariant = options.invariant ?? (options.deny !== undefined && options.deny.length > 0);
56
+ const rawExpected = options.expected ?? [];
57
+ if (rawExpected.length > HARD_MAX_EXPECTED_CALLS) {
58
+ throw new EvalError(
59
+ `expected tool calls count (${rawExpected.length}) exceeds hard limit (${HARD_MAX_EXPECTED_CALLS})`,
60
+ "ERR_PRISM_EVAL_TRAJECTORY_BOUNDS",
61
+ );
62
+ }
63
+ const expectedSpecs = rawExpected.map(normalizeSpec);
64
+ const denySpecs = (options.deny ?? []).map(normalizeSpec);
65
+
66
+ return {
67
+ id: options.id ?? `tool_call_match_${mode}`,
68
+ description: `tool call match (${mode})`,
69
+ requires: ["timeline"],
70
+ invariant: isInvariant,
71
+ score(input: ScorerInput<TInput, TExpected>): ScoreResult {
72
+ const timeline: ExecutionTimeline | undefined = input.timeline ?? input.target?.timeline;
73
+ if (!timeline) {
74
+ return {
75
+ score: 0,
76
+ reason: "no execution timeline available for trajectory scoring",
77
+ };
78
+ }
79
+
80
+ const toolSteps = timeline.steps.filter((s) => s.kind === "tool");
81
+
82
+ // 1. Deny list check
83
+ for (const step of toolSteps) {
84
+ for (const deny of denySpecs) {
85
+ if (matchesSpec(step, deny)) {
86
+ return {
87
+ score: 0,
88
+ reason: `forbidden tool "${step.name}" was called`,
89
+ metadata: { forbiddenTool: step.name },
90
+ };
91
+ }
92
+ }
93
+ }
94
+
95
+ // 2. Mode match check
96
+ switch (mode) {
97
+ case "strict": {
98
+ if (toolSteps.length !== expectedSpecs.length) {
99
+ return {
100
+ score: 0,
101
+ reason: `strict match count mismatch: expected ${expectedSpecs.length}, got ${toolSteps.length}`,
102
+ };
103
+ }
104
+ for (let i = 0; i < toolSteps.length; i++) {
105
+ const step = toolSteps[i]!;
106
+ const expected = expectedSpecs[i]!;
107
+ if (!matchesSpec(step, expected)) {
108
+ return {
109
+ score: 0,
110
+ reason: `strict match mismatch at index ${i}: expected "${expected.name}", got "${step.name}"`,
111
+ };
112
+ }
113
+ }
114
+ return { score: 1 };
115
+ }
116
+
117
+ case "unordered": {
118
+ if (toolSteps.length !== expectedSpecs.length) {
119
+ return {
120
+ score: 0,
121
+ reason: `unordered match count mismatch: expected ${expectedSpecs.length}, got ${toolSteps.length}`,
122
+ };
123
+ }
124
+ const unmatchedIndices = new Set(toolSteps.keys());
125
+ for (const expected of expectedSpecs) {
126
+ let matchedIndex: number | undefined;
127
+ for (const idx of unmatchedIndices) {
128
+ if (matchesSpec(toolSteps[idx]!, expected)) {
129
+ matchedIndex = idx;
130
+ break;
131
+ }
132
+ }
133
+ if (matchedIndex === undefined) {
134
+ return {
135
+ score: 0,
136
+ reason: `unordered match failed: expected tool "${expected.name}" not found in unmatched actual steps`,
137
+ };
138
+ }
139
+ unmatchedIndices.delete(matchedIndex);
140
+ }
141
+ return { score: 1 };
142
+ }
143
+
144
+ case "subset": {
145
+ // Every actual call must match at least one expected spec (no unexpected extra calls)
146
+ const availableSpecs = [...expectedSpecs];
147
+ for (const step of toolSteps) {
148
+ const specIdx = availableSpecs.findIndex((s) => matchesSpec(step, s));
149
+ if (specIdx === -1) {
150
+ return {
151
+ score: 0,
152
+ reason: `subset match failed: extra tool "${step.name}" was not in expected set`,
153
+ };
154
+ }
155
+ availableSpecs.splice(specIdx, 1);
156
+ }
157
+ return { score: 1 };
158
+ }
159
+
160
+ case "superset": {
161
+ // All expected specs must be satisfied by actual steps (extra tool calls are ok)
162
+ let stepSearchIndex = 0;
163
+ for (const expected of expectedSpecs) {
164
+ let found = false;
165
+ while (stepSearchIndex < toolSteps.length) {
166
+ const candidate = toolSteps[stepSearchIndex++]!;
167
+ if (matchesSpec(candidate, expected)) {
168
+ found = true;
169
+ break;
170
+ }
171
+ }
172
+ if (!found) {
173
+ return {
174
+ score: 0,
175
+ reason: `superset match failed: expected tool "${expected.name}" was not found in sequence`,
176
+ };
177
+ }
178
+ }
179
+ return { score: 1 };
180
+ }
181
+ }
182
+ },
183
+ };
184
+ }
185
+
186
+ // ─── Step Budget Scorer (R-E2) ────────────────────────────────────────────────
187
+
188
+ export interface StepBudgetScorerOptions {
189
+ readonly id?: string;
190
+ readonly maxTurns?: number;
191
+ readonly maxToolCalls?: number;
192
+ readonly maxDurationMs?: number;
193
+ readonly maxTotalTokens?: number;
194
+ readonly maxCost?: number;
195
+ }
196
+
197
+ /**
198
+ * Verifies that the run stayed within resource and turn limits.
199
+ */
200
+ export function createStepBudgetScorer<TInput = unknown, TExpected = unknown>(options: StepBudgetScorerOptions): Scorer<TInput, TExpected> {
201
+ return {
202
+ id: options.id ?? "step_budget",
203
+ description: "step budget and resource ceiling scorer",
204
+ requires: ["timeline"],
205
+ score(input: ScorerInput<TInput, TExpected>): ScoreResult {
206
+ const timeline = input.timeline ?? input.target?.timeline;
207
+ if (!timeline) {
208
+ return { score: 0, reason: "no timeline available for step budget evaluation" };
209
+ }
210
+
211
+ if (options.maxTurns !== undefined) {
212
+ const turnSteps = timeline.steps.filter((s) => s.kind === "turn");
213
+ if (turnSteps.length > options.maxTurns) {
214
+ return {
215
+ score: 0,
216
+ reason: `turns exceeded maxTurns (${turnSteps.length} > ${options.maxTurns})`,
217
+ };
218
+ }
219
+ }
220
+
221
+ if (options.maxToolCalls !== undefined) {
222
+ const toolCalls = timeline.steps.filter((s) => s.kind === "tool");
223
+ if (toolCalls.length > options.maxToolCalls) {
224
+ return {
225
+ score: 0,
226
+ reason: `tool calls exceeded maxToolCalls (${toolCalls.length} > ${options.maxToolCalls})`,
227
+ };
228
+ }
229
+ }
230
+
231
+ if (options.maxDurationMs !== undefined) {
232
+ if (timeline.startedAt && timeline.finishedAt) {
233
+ const duration = Date.parse(timeline.finishedAt) - Date.parse(timeline.startedAt);
234
+ if (Number.isFinite(duration) && duration > options.maxDurationMs) {
235
+ return {
236
+ score: 0,
237
+ reason: `duration exceeded maxDurationMs (${duration}ms > ${options.maxDurationMs}ms)`,
238
+ };
239
+ }
240
+ }
241
+ }
242
+
243
+ if (options.maxTotalTokens !== undefined) {
244
+ const tokens = timeline.usage?.totalTokens ?? input.result.usage?.totalTokens ?? 0;
245
+ if (tokens > options.maxTotalTokens) {
246
+ return {
247
+ score: 0,
248
+ reason: `total tokens exceeded maxTotalTokens (${tokens} > ${options.maxTotalTokens})`,
249
+ };
250
+ }
251
+ }
252
+
253
+ if (options.maxCost !== undefined) {
254
+ const cost = timeline.usage?.cost ?? input.result.usage?.cost ?? 0;
255
+ if (cost > options.maxCost) {
256
+ return {
257
+ score: 0,
258
+ reason: `cost exceeded maxCost (${cost} > ${options.maxCost})`,
259
+ };
260
+ }
261
+ }
262
+
263
+ return { score: 1 };
264
+ },
265
+ };
266
+ }
267
+
268
+ // ─── No-Loop Scorer (R-E2) ────────────────────────────────────────────────────
269
+
270
+ export interface NoLoopScorerOptions {
271
+ readonly id?: string;
272
+ /** Maximum consecutive identical tool+arguments calls before failing. Defaults to 2 (3 consecutive fails). */
273
+ readonly maxRepeatedToolCalls?: number;
274
+ }
275
+
276
+ /**
277
+ * Detects degenerate loops where an agent calls the exact same tool with identical arguments repeatedly.
278
+ */
279
+ export function createNoLoopScorer<TInput = unknown, TExpected = unknown>(options: NoLoopScorerOptions = {}): Scorer<TInput, TExpected> {
280
+ const threshold = options.maxRepeatedToolCalls ?? 2;
281
+
282
+ return {
283
+ id: options.id ?? "no_loop",
284
+ description: "detects identical tool+arguments repetitive loops",
285
+ requires: ["timeline"],
286
+ invariant: true,
287
+ score(input: ScorerInput<TInput, TExpected>): ScoreResult {
288
+ const timeline = input.timeline ?? input.target?.timeline;
289
+ if (!timeline) {
290
+ return { score: 0, reason: "no timeline available for loop detection" };
291
+ }
292
+
293
+ const toolSteps = timeline.steps.filter((s) => s.kind === "tool");
294
+ let streakTool = "";
295
+ let streakArgs = "";
296
+ let streakCount = 0;
297
+
298
+ for (const step of toolSteps) {
299
+ const serializedArgs = JSON.stringify(step.input ?? null);
300
+ if (step.name === streakTool && serializedArgs === streakArgs) {
301
+ streakCount++;
302
+ if (streakCount > threshold) {
303
+ return {
304
+ score: 0,
305
+ reason: `loop detected: tool "${step.name}" called ${streakCount} times with identical arguments`,
306
+ metadata: { loopingTool: step.name },
307
+ };
308
+ }
309
+ } else {
310
+ streakTool = step.name;
311
+ streakArgs = serializedArgs;
312
+ streakCount = 1;
313
+ }
314
+ }
315
+
316
+ return { score: 1 };
317
+ },
318
+ };
319
+ }
320
+
321
+ // ─── Schema Scorer (R-E2) ─────────────────────────────────────────────────────
322
+
323
+ export interface SchemaScorerOptions {
324
+ readonly id?: string;
325
+ readonly schema: Record<string, unknown>;
326
+ readonly target?: "result" | "step";
327
+ readonly stepName?: string;
328
+ }
329
+
330
+ /**
331
+ * Validates agent final output or a named step output against a JSON schema.
332
+ */
333
+ export function createSchemaScorer<TInput = unknown, TExpected = unknown>(options: SchemaScorerOptions): Scorer<TInput, TExpected> {
334
+ return {
335
+ id: options.id ?? "schema_validation",
336
+ description: "validates output against JSON schema",
337
+ // Only the step-target read needs a timeline; a result-target schema check does not.
338
+ ...(options.target === "step" ? { requires: ["timeline"] as const } : {}),
339
+ async score(input: ScorerInput<TInput, TExpected>): Promise<ScoreResult> {
340
+ let candidate: unknown;
341
+
342
+ if (options.target === "step" && options.stepName) {
343
+ const timeline = input.timeline ?? input.target?.timeline;
344
+ const step = timeline?.steps.find((s) => s.name === options.stepName);
345
+ if (!step) {
346
+ return { score: 0, reason: `step "${options.stepName}" not found on timeline` };
347
+ }
348
+ candidate = step.output;
349
+ } else {
350
+ // Output from result or timeline
351
+ const resultOutput = (input.result as { output?: unknown }).output;
352
+ if (resultOutput !== undefined) {
353
+ candidate = resultOutput;
354
+ } else if (input.result.text) {
355
+ try {
356
+ candidate = JSON.parse(input.result.text);
357
+ } catch {
358
+ candidate = input.result.text;
359
+ }
360
+ }
361
+ }
362
+
363
+ if (candidate === undefined || candidate === null) {
364
+ return { score: 0, reason: "output value is empty or undefined" };
365
+ }
366
+
367
+ const res = validateJsonSchema(options.schema as JsonSchema, candidate);
368
+ if (!res.ok) {
369
+ const messages = res.errors ? res.errors.map((e) => e.message).join("; ") : "invalid schema";
370
+ return { score: 0, reason: `schema validation failed: ${messages}` };
371
+ }
372
+
373
+ return { score: 1 };
374
+ },
375
+ };
376
+ }
377
+
378
+ // ─── Error Class Scorer (R-E2) ────────────────────────────────────────────────
379
+
380
+ export interface ErrorClassScorerOptions {
381
+ readonly id?: string;
382
+ readonly deny?: readonly (string | number)[];
383
+ }
384
+
385
+ /**
386
+ * Checks that denied error codes or blocked executions did not occur on the timeline.
387
+ */
388
+ export function createErrorClassScorer<TInput = unknown, TExpected = unknown>(
389
+ options: ErrorClassScorerOptions = {},
390
+ ): Scorer<TInput, TExpected> {
391
+ const deniedSet = options.deny ? new Set(options.deny.map(String)) : undefined;
392
+
393
+ return {
394
+ id: options.id ?? "error_class",
395
+ description: "checks for denied error codes and blocked executions",
396
+ requires: ["timeline"],
397
+ // A general "any failure" check is a quality signal; a deny-list check is a safety rule.
398
+ invariant: deniedSet !== undefined,
399
+ score(input: ScorerInput<TInput, TExpected>): ScoreResult {
400
+ const timeline = input.timeline ?? input.target?.timeline;
401
+ if (!timeline) {
402
+ // No evidence of the errors being absent is not evidence that they did not happen.
403
+ return { score: 0, reason: "no timeline available for error class verification" };
404
+ }
405
+
406
+ for (const step of timeline.steps) {
407
+ if (step.status === "failed" || step.status === "blocked") {
408
+ const code = step.error?.code !== undefined ? String(step.error.code) : undefined;
409
+ const reason = typeof step.metadata?.reason === "string" ? step.metadata.reason : undefined;
410
+
411
+ if (deniedSet) {
412
+ if (code && deniedSet.has(code)) {
413
+ return {
414
+ score: 0,
415
+ reason: `denied error code "${code}" encountered on step "${step.name}"`,
416
+ metadata: { errorCode: code },
417
+ };
418
+ }
419
+ if (reason && deniedSet.has(reason)) {
420
+ return {
421
+ score: 0,
422
+ reason: `denied blocked reason "${reason}" encountered on step "${step.name}"`,
423
+ metadata: { reason },
424
+ };
425
+ }
426
+ } else {
427
+ // General error denial
428
+ return {
429
+ score: 0,
430
+ reason: `step "${step.name}" failed with status "${step.status}"`,
431
+ };
432
+ }
433
+ }
434
+ }
435
+
436
+ return { score: 1 };
437
+ },
438
+ };
439
+ }
440
+
441
+ // ─── Guardrail-Pack Violation Scorer ──────────────────────────────────────────
442
+
443
+ /** Pack-compiled guardrails are named `<prefix><pack>/<rule>` (plan 092 Task 2); this scorer keys off that. */
444
+ export const DEFAULT_PACK_RULE_PREFIX = "pack:";
445
+
446
+ export interface GuardrailPackScorerOptions {
447
+ readonly id?: string;
448
+ /** Rule-name prefixes that count as a violation. Defaults to every `pack:` rule. */
449
+ readonly rules?: readonly string[];
450
+ /** Tool names whose successful execution is a violation even when no rule denied it (pack missing or missed). */
451
+ readonly forbidTools?: readonly string[];
452
+ }
453
+
454
+ function matchesRule(name: string, prefixes: readonly string[]): boolean {
455
+ return prefixes.some((prefix) => name === prefix || name.startsWith(prefix));
456
+ }
457
+
458
+ /**
459
+ * Fails a trajectory that attempted a guardrail-pack violation: a denying pack rule on the
460
+ * timeline names the rule, and a forbidden tool that still executed fails without a rule name.
461
+ * A compliant trajectory (no pack denial, no forbidden execution) scores 1.
462
+ */
463
+ export function createGuardrailPackScorer<TInput = unknown, TExpected = unknown>(
464
+ options: GuardrailPackScorerOptions = {},
465
+ ): Scorer<TInput, TExpected> {
466
+ const prefixes = options.rules ?? [DEFAULT_PACK_RULE_PREFIX];
467
+ const forbidden = new Set(options.forbidTools ?? []);
468
+
469
+ return {
470
+ id: options.id ?? "guardrail_pack",
471
+ description: "fails when a guardrail pack denied the trajectory or a forbidden tool executed",
472
+ requires: ["timeline"],
473
+ invariant: true,
474
+ score(input: ScorerInput<TInput, TExpected>): ScoreResult {
475
+ const timeline: ExecutionTimeline | undefined = input.timeline ?? input.target?.timeline;
476
+ if (!timeline) {
477
+ return {
478
+ score: 0,
479
+ reason: "no execution timeline available for guardrail pack scoring",
480
+ };
481
+ }
482
+
483
+ const deniedRules: string[] = [];
484
+ for (const step of timeline.steps) {
485
+ if (step.kind !== "guardrail" || step.status !== "denied") continue;
486
+ const rule = typeof step.metadata?.guardrail === "string" ? step.metadata.guardrail : step.name;
487
+ if (matchesRule(rule, prefixes)) deniedRules.push(rule);
488
+ }
489
+
490
+ const executed = timeline.steps.filter((step) => step.kind === "tool" && step.status === "succeeded" && forbidden.has(step.name));
491
+ if (executed.length > 0) {
492
+ return {
493
+ score: 0,
494
+ reason: `forbidden tool "${executed[0]!.name}" executed without a pack denial`,
495
+ metadata: { toolName: executed[0]!.name, rules: deniedRules },
496
+ };
497
+ }
498
+
499
+ if (deniedRules.length > 0) {
500
+ const extra = deniedRules.length > 1 ? ` (and ${deniedRules.length - 1} more pack rule denials)` : "";
501
+ return {
502
+ score: 0,
503
+ reason: `guardrail pack rule "${deniedRules[0]}" denied the trajectory${extra}`,
504
+ metadata: { rule: deniedRules[0], rules: deniedRules },
505
+ };
506
+ }
507
+
508
+ return { score: 1 };
509
+ },
510
+ };
511
+ }
512
+
513
+ // ─── Approval-Before-Effect Scorer (R-E12) ────────────────────────────────────
514
+
515
+ export interface ApprovalBeforeEffectScorerOptions {
516
+ readonly id?: string;
517
+ /** Name of the sensitive tool/effect requiring prior approval. If omitted, checks all tools with effect metadata. */
518
+ readonly toolName?: string;
519
+ /**
520
+ * The agent's tools (normally `agent.tools`). Calls whose `effects` include `write`, `execute`,
521
+ * or `external` need approval; a tool step whose name is not listed is treated as effectful.
522
+ * Omit to check every tool step.
523
+ */
524
+ readonly tools?: readonly ToolInfo[];
525
+ /** Custom matcher to correlate an approval step with an effect step. Receives `hitl` steps only. */
526
+ readonly matchApproval?: (approvalStep: ExecutionStep, effectStep: ExecutionStep) => boolean;
527
+ }
528
+
529
+ /** Effects a human must approve before they run (plan 197 Task 3). */
530
+ const APPROVAL_REQUIRED_EFFECTS: readonly ToolCapabilityKind[] = ["write", "execute", "external"];
531
+
532
+ /**
533
+ * The tool call an approval or tool step refers to. `run.suspended`/`decision.resolved` carry it as
534
+ * `metadata.toolCallId`; a tool step also encodes it in its `tool:<callId>` id (timeline.ts).
535
+ */
536
+ function toolCallIdOf(step: ExecutionStep): string | undefined {
537
+ const explicit = step.metadata?.toolCallId;
538
+ if (typeof explicit === "string" && explicit.length > 0) return explicit;
539
+ return step.id.startsWith("tool:") ? step.id.slice("tool:".length) : undefined;
540
+ }
541
+
542
+ /**
543
+ * Hard invariant scorer requiring explicit approval on the timeline BEFORE any sensitive effect execution.
544
+ *
545
+ * Approval is evidence, not inference: an effect passes only when a `hitl` step for the same tool call
546
+ * settled `approved` before it. A denied or still-`suspended` decision fails the call, and a
547
+ * `succeeded` guardrail step never stands in for a human decision.
548
+ */
549
+ export function createApprovalBeforeEffectScorer<TInput = unknown, TExpected = unknown>(
550
+ options: ApprovalBeforeEffectScorerOptions = {},
551
+ ): Scorer<TInput, TExpected> {
552
+ const effectful = options.tools ? new Map(options.tools.map((tool) => [tool.name, tool.effects])) : undefined;
553
+
554
+ const needsApproval = (step: ExecutionStep): boolean => {
555
+ // An explicitly named tool is checked as named; otherwise the declared effects decide.
556
+ if (options.toolName !== undefined) return step.name === options.toolName;
557
+ if (!effectful) return true;
558
+ const effects = effectful.get(step.name);
559
+ // Fail closed: a tool the agent does not declare is assumed effectful.
560
+ if (!effects) return true;
561
+ return effects.some((effect) => APPROVAL_REQUIRED_EFFECTS.includes(effect));
562
+ };
563
+
564
+ return {
565
+ id: options.id ?? "approval_before_effect",
566
+ description: "verifies approval occurred on timeline prior to tool effect",
567
+ requires: ["timeline"],
568
+ invariant: true,
569
+ score(input: ScorerInput<TInput, TExpected>): ScoreResult {
570
+ const timeline = input.timeline ?? input.target?.timeline;
571
+ if (!timeline) {
572
+ return {
573
+ score: 0,
574
+ reason: "no timeline available for approval-before-effect verification",
575
+ };
576
+ }
577
+
578
+ // One pass: the first decision step per tool call, so a verdict resolves in O(1) per effect.
579
+ const decisions = new Map<string, ExecutionStep>();
580
+ for (const step of timeline.steps) {
581
+ if (step.kind !== "hitl") continue;
582
+ const callId = toolCallIdOf(step);
583
+ if (callId !== undefined && !decisions.has(callId)) decisions.set(callId, step);
584
+ }
585
+
586
+ for (const effect of timeline.steps) {
587
+ if (effect.kind !== "tool" || effect.status === "blocked" || !needsApproval(effect)) continue;
588
+
589
+ if (options.matchApproval) {
590
+ const approved = timeline.steps.some(
591
+ (step) => step.kind === "hitl" && step.order < effect.order && options.matchApproval!(step, effect),
592
+ );
593
+ if (approved) continue;
594
+ return {
595
+ score: 0,
596
+ reason: `effect tool "${effect.name}" executed at step order ${effect.order} without prior approval`,
597
+ metadata: { unapprovedTool: effect.name },
598
+ };
599
+ }
600
+
601
+ const callId = toolCallIdOf(effect);
602
+ const decision = callId === undefined ? undefined : decisions.get(callId);
603
+ if (decision?.status === "approved" && decision.order < effect.order) continue;
604
+
605
+ const reason =
606
+ decision === undefined
607
+ ? `effect tool "${effect.name}" executed at step order ${effect.order} without prior approval`
608
+ : decision.order >= effect.order
609
+ ? `effect tool "${effect.name}" ran at step order ${effect.order} before its approval at step order ${decision.order}`
610
+ : decision.status === "denied"
611
+ ? `effect tool "${effect.name}" ran after its approval request was denied`
612
+ : `effect tool "${effect.name}" ran while its approval was still ${decision.status}`;
613
+ return {
614
+ score: 0,
615
+ reason,
616
+ metadata: { unapprovedTool: effect.name, ...(callId ? { toolCallId: callId } : {}) },
617
+ };
618
+ }
619
+
620
+ return { score: 1 };
621
+ },
622
+ };
623
+ }