@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.
- package/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6197 -0
- package/host-builder/data/errors.json +558 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +255 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +318 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +68 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
import { toExperimentReportRecord } from "./report-record.js";
|
|
2
|
+
import type { EvaluationRecord } from "@arnilo/prism";
|
|
3
|
+
import { type Message, type RunResult, type Usage } from "@arnilo/prism";
|
|
4
|
+
import { fleissKappa, bootstrapInterval, clusteredStandardError, passAtK, passHatK, wilsonInterval } from "./stats.js";
|
|
5
|
+
import { validateSplit } from "./dataset.js";
|
|
6
|
+
import { EvalDatasetError, EvalError } from "./errors.js";
|
|
7
|
+
import { loadTimeline } from "./timeline.js";
|
|
8
|
+
import { executeScenario, isScenarioInput, validateScenario } from "./scenario-runner.js";
|
|
9
|
+
import { collectWhileRunning, mulberry32, resolveTrialsConfig, validateEvalManifest } from "./scenarios.js";
|
|
10
|
+
import { checkRequirements, defaultToAgentInput, scoreRun, skipScorers } from "./score.js";
|
|
11
|
+
import type {
|
|
12
|
+
DatasetItem,
|
|
13
|
+
ExperimentAggregate,
|
|
14
|
+
ExperimentItemResult,
|
|
15
|
+
ExperimentReport,
|
|
16
|
+
ExperimentTrials,
|
|
17
|
+
RunExperimentOptions,
|
|
18
|
+
ScorerStats,
|
|
19
|
+
TimelineFolder,
|
|
20
|
+
ExecutionTimeline,
|
|
21
|
+
UserSimulation,
|
|
22
|
+
} from "./types.js";
|
|
23
|
+
import { assertFiniteUnitInterval, hash32, mapPool, normalizeConcurrency, randomId, toErrorInfo } from "./util.js";
|
|
24
|
+
|
|
25
|
+
function aggregateEvaluations(
|
|
26
|
+
evaluations: readonly EvaluationRecord[],
|
|
27
|
+
passThresholds: ReadonlyMap<string, number>,
|
|
28
|
+
trialCount: number,
|
|
29
|
+
itemCount: number,
|
|
30
|
+
seed = 0,
|
|
31
|
+
): ExperimentAggregate {
|
|
32
|
+
const scored = evaluations.filter((record) => record.status === "scored" && record.score !== undefined);
|
|
33
|
+
const groups = new Map<string, Map<string, number[]>>();
|
|
34
|
+
const panelLabels = new Map<string, string[][]>();
|
|
35
|
+
for (const record of scored) {
|
|
36
|
+
const items = groups.get(record.scorerId) ?? new Map<string, number[]>();
|
|
37
|
+
const values = items.get(record.itemId!) ?? [];
|
|
38
|
+
values.push(record.score!);
|
|
39
|
+
items.set(record.itemId!, values);
|
|
40
|
+
groups.set(record.scorerId, items);
|
|
41
|
+
const labels = record.metadata?.labels;
|
|
42
|
+
// Fleiss requires complete, equally sized rating rows; failed/unlabeled members stay null.
|
|
43
|
+
if (Array.isArray(labels) && labels.length >= 2 && labels.every((label) => typeof label === "string" && label.trim())) {
|
|
44
|
+
const rows = panelLabels.get(record.scorerId) ?? [];
|
|
45
|
+
if (!rows.length || rows[0]!.length === labels.length) rows.push(labels);
|
|
46
|
+
panelLabels.set(record.scorerId, rows);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const scorers = Object.fromEntries(
|
|
50
|
+
[...groups].map(([id, items]): [string, ScorerStats] => {
|
|
51
|
+
const values = [...items.values()];
|
|
52
|
+
const means = values.map((scores) => scores.reduce((sum, score) => sum + score, 0) / scores.length);
|
|
53
|
+
const mean = means.reduce((sum, score) => sum + score, 0) / means.length;
|
|
54
|
+
const records = values.reduce((sum, scores) => sum + scores.length, 0);
|
|
55
|
+
const threshold = passThresholds.get(id)!;
|
|
56
|
+
const successes = values.map((scores) => scores.filter((score) => score >= threshold).length);
|
|
57
|
+
const passRate = successes.reduce((sum, c, i) => sum + c / values[i]!.length, 0) / items.size;
|
|
58
|
+
const reliability: Pick<ScorerStats, "passRate" | "passAtK" | "passHatK" | "passKCounts"> = { passRate };
|
|
59
|
+
const judgeAgreement = fleissKappa(panelLabels.get(id) ?? []);
|
|
60
|
+
const agreement = judgeAgreement === undefined ? {} : { judgeAgreement };
|
|
61
|
+
if (trialCount > 1) {
|
|
62
|
+
const at: Record<number, number> = {},
|
|
63
|
+
hat: Record<number, number> = {};
|
|
64
|
+
const counts: Record<number, { items: number; excludedItems: number }> = {};
|
|
65
|
+
for (let k = 1; k <= trialCount; k++) counts[k] = { items: 0, excludedItems: itemCount };
|
|
66
|
+
for (let i = 0; i < values.length; i++) {
|
|
67
|
+
const n = values[i]!.length,
|
|
68
|
+
c = successes[i]!;
|
|
69
|
+
let atK = passAtK(n, c, 1),
|
|
70
|
+
hatK = passHatK(n, c, 1);
|
|
71
|
+
for (let k = 1; k <= Math.min(n, trialCount); k++) {
|
|
72
|
+
// Extend the estimators by one draw, computing all k in O(n).
|
|
73
|
+
if (k > 1) {
|
|
74
|
+
atK = n - c < k ? 1 : atK + ((1 - atK) * c) / (n - k + 1);
|
|
75
|
+
hatK = c < k ? 0 : (hatK * (c - k + 1)) / (n - k + 1);
|
|
76
|
+
}
|
|
77
|
+
at[k] = (at[k] ?? 0) + atK;
|
|
78
|
+
hat[k] = (hat[k] ?? 0) + hatK;
|
|
79
|
+
counts[k]!.items++;
|
|
80
|
+
counts[k]!.excludedItems--;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (const key of Object.keys(at)) {
|
|
84
|
+
const k = Number(key);
|
|
85
|
+
at[k] = at[k]! / counts[k]!.items;
|
|
86
|
+
hat[k] = hat[k]! / counts[k]!.items;
|
|
87
|
+
}
|
|
88
|
+
Object.assign(reliability, { passAtK: at, passHatK: hat, passKCounts: counts });
|
|
89
|
+
}
|
|
90
|
+
if (items.size < 2) return [id, { items: items.size, records, mean, ...reliability, ...agreement, method: "single_item" }];
|
|
91
|
+
const binary = values.every((scores) => scores.length === 1 && (scores[0] === 0 || scores[0] === 1));
|
|
92
|
+
const se = clusteredStandardError(
|
|
93
|
+
values.flat(),
|
|
94
|
+
values.flatMap((scores, i) => scores.map(() => i)),
|
|
95
|
+
);
|
|
96
|
+
// Resampling item means preserves equal item weights even with unequal trial/step counts.
|
|
97
|
+
const ci95 = binary
|
|
98
|
+
? wilsonInterval(
|
|
99
|
+
means.reduce((sum, value) => sum + value, 0),
|
|
100
|
+
items.size,
|
|
101
|
+
)
|
|
102
|
+
: bootstrapInterval(means, {
|
|
103
|
+
seed,
|
|
104
|
+
clusterIds: [...items.keys()],
|
|
105
|
+
statistic: (sample) => sample.reduce((sum, value) => sum + value, 0) / sample.length,
|
|
106
|
+
});
|
|
107
|
+
return [
|
|
108
|
+
id,
|
|
109
|
+
{ items: items.size, records, mean, ...reliability, ...agreement, se, ci95, method: binary ? "wilson" : "cluster_bootstrap" },
|
|
110
|
+
];
|
|
111
|
+
}),
|
|
112
|
+
);
|
|
113
|
+
const stats = Object.values(scorers);
|
|
114
|
+
const macroMean = stats.length ? stats.reduce((sum, value) => sum + value.mean, 0) / stats.length : undefined;
|
|
115
|
+
|
|
116
|
+
// Written by `scoreRun` from the scorer's `invariant` declaration only; a scorer cannot set it.
|
|
117
|
+
const invariantRecords = evaluations.filter((record) => record.metadata?.invariant === true);
|
|
118
|
+
const invariantsPassed =
|
|
119
|
+
invariantRecords.length > 0 ? invariantRecords.every((record) => record.status === "scored" && record.score === 1) : undefined;
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
itemCount: 0,
|
|
123
|
+
scoredCount: scored.length,
|
|
124
|
+
skippedCount: evaluations.filter((record) => record.status === "skipped").length,
|
|
125
|
+
failedCount: evaluations.filter((record) => record.status === "failed").length,
|
|
126
|
+
macroMean,
|
|
127
|
+
scorers,
|
|
128
|
+
...(invariantsPassed !== undefined ? { invariantsPassed } : {}),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Sum observed usage; billing is published only with complete trial evidence. */
|
|
133
|
+
function aggregateCost(items: readonly ExperimentItemResult[]): NonNullable<ExperimentAggregate["cost"]> {
|
|
134
|
+
const trials = items.flatMap((item) => item.trials);
|
|
135
|
+
const totals: { -readonly [K in keyof Usage]?: Usage[K] } = {};
|
|
136
|
+
const meanPerItem: { -readonly [K in keyof Usage]?: Usage[K] } & { durationMs?: number } = {};
|
|
137
|
+
for (const field of ["inputTokens", "outputTokens", "totalTokens", "cacheReadTokens", "cacheWriteTokens"] as const) {
|
|
138
|
+
const values = trials.flatMap((trial) => (trial.usage?.[field] === undefined ? [] : [trial.usage[field]!]));
|
|
139
|
+
if (values.length) {
|
|
140
|
+
totals[field] = values.reduce((sum, value) => sum + value, 0);
|
|
141
|
+
meanPerItem[field] = totals[field]! / items.length;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (trials.some((trial) => trial.usage?.estimated)) totals.estimated = meanPerItem.estimated = true;
|
|
145
|
+
const currency = trials[0]?.usage?.currency;
|
|
146
|
+
const totalCost = trials.reduce((sum, trial) => sum + (trial.usage?.cost ?? 0), 0);
|
|
147
|
+
const costComplete =
|
|
148
|
+
trials.length > 0 && trials.every((trial) => trial.costComplete && trial.usage?.currency === currency) && Number.isFinite(totalCost);
|
|
149
|
+
if (costComplete) {
|
|
150
|
+
totals.cost = totalCost;
|
|
151
|
+
meanPerItem.cost = totalCost / items.length;
|
|
152
|
+
if (currency !== undefined) totals.currency = meanPerItem.currency = currency;
|
|
153
|
+
}
|
|
154
|
+
const durations = trials.flatMap((trial) => (trial.durationMs === undefined ? [] : [trial.durationMs])).sort((a, b) => a - b);
|
|
155
|
+
if (durations.length) meanPerItem.durationMs = durations.reduce((sum, value) => sum + value, 0) / items.length;
|
|
156
|
+
return {
|
|
157
|
+
...totals,
|
|
158
|
+
costComplete,
|
|
159
|
+
meanPerItem,
|
|
160
|
+
...(durations.length
|
|
161
|
+
? {
|
|
162
|
+
durationMs: { p50: durations[Math.ceil(durations.length * 0.5) - 1]!, p95: durations[Math.ceil(durations.length * 0.95) - 1]! },
|
|
163
|
+
}
|
|
164
|
+
: {}),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Run a pinned dataset snapshot through an agent with bounded concurrency and scorers.
|
|
170
|
+
* Item order in the report matches dataset order. `trials` re-runs each item N times.
|
|
171
|
+
*/
|
|
172
|
+
export async function runExperiment<TInput = unknown, TExpected = unknown>(
|
|
173
|
+
options: RunExperimentOptions<TInput, TExpected>,
|
|
174
|
+
): Promise<ExperimentReport<TInput, TExpected>> {
|
|
175
|
+
if (!options.scorers.length) throw new EvalError("at least one scorer is required", "ERR_PRISM_EVAL_EXPERIMENT");
|
|
176
|
+
const passThresholds = new Map(
|
|
177
|
+
options.scorers.map((scorer) => [
|
|
178
|
+
scorer.id,
|
|
179
|
+
assertFiniteUnitInterval(scorer.passThreshold === undefined ? 1 : scorer.passThreshold, `passThreshold.${scorer.id}`),
|
|
180
|
+
]),
|
|
181
|
+
);
|
|
182
|
+
if (options.manifest) validateEvalManifest(options.manifest);
|
|
183
|
+
checkRequirements(options.scorers, {
|
|
184
|
+
timeline: options.timeline !== undefined && options.timeline !== "off",
|
|
185
|
+
trace: options.traceResolver !== undefined,
|
|
186
|
+
environment: options.toEnvironment !== undefined,
|
|
187
|
+
});
|
|
188
|
+
const experimentId = options.experimentId ?? randomId("experiment");
|
|
189
|
+
const concurrency = normalizeConcurrency(options.concurrency);
|
|
190
|
+
const toAgentInput = options.toAgentInput ?? ((input: TInput) => defaultToAgentInput(input));
|
|
191
|
+
const splits = options.split === undefined ? undefined : Array.isArray(options.split) ? options.split : [options.split];
|
|
192
|
+
splits?.forEach(validateSplit);
|
|
193
|
+
const items = options.dataset.items.filter((item) => splits === undefined || (item.split !== undefined && splits.includes(item.split)));
|
|
194
|
+
if (options.allowHeldout !== true && items.some((item) => item.split === "heldout")) {
|
|
195
|
+
throw new EvalDatasetError("heldout items require allowHeldout: true", { code: "ERR_PRISM_EVAL_HELDOUT" });
|
|
196
|
+
}
|
|
197
|
+
for (const item of items) if (isScenarioInput(item.input)) validateScenario(item.input);
|
|
198
|
+
const trialPlan = options.trials !== undefined ? resolveTrialsConfig(options.trials, options.seed) : undefined;
|
|
199
|
+
const trialCount = trialPlan?.count ?? 1;
|
|
200
|
+
if (typeof options.agent !== "function" && (options.hooks !== undefined || options.slots !== undefined)) {
|
|
201
|
+
throw new EvalError("hooks and slots require an agent factory; an Agent instance cannot be reconfigured", "ERR_PRISM_EVAL_EXPERIMENT");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let aborted = false;
|
|
205
|
+
let fatal: unknown;
|
|
206
|
+
let sampleCount = 0;
|
|
207
|
+
|
|
208
|
+
const runTrial = async (
|
|
209
|
+
item: DatasetItem<TInput, TExpected>,
|
|
210
|
+
trialIndex: number,
|
|
211
|
+
): Promise<{
|
|
212
|
+
result?: RunResult;
|
|
213
|
+
accounting: ExperimentItemResult["trials"][number];
|
|
214
|
+
evaluations: readonly EvaluationRecord[];
|
|
215
|
+
error?: ExperimentItemResult<TInput, TExpected>["error"];
|
|
216
|
+
}> => {
|
|
217
|
+
if (options.signal?.aborted) {
|
|
218
|
+
aborted = true;
|
|
219
|
+
return {
|
|
220
|
+
accounting: { status: "aborted", costComplete: false },
|
|
221
|
+
evaluations: [],
|
|
222
|
+
error: toErrorInfo(options.signal.reason ?? new Error("experiment aborted")),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
let result: RunResult | undefined;
|
|
227
|
+
let error = undefined as ExperimentItemResult<TInput, TExpected>["error"];
|
|
228
|
+
|
|
229
|
+
// One stream per (item, trial): identical sampling at concurrency 1 and 8. An explicit
|
|
230
|
+
// `random` keeps the old single shared stream, which is order-dependent by nature.
|
|
231
|
+
const random = options.random ?? (options.seed !== undefined ? mulberry32(hash32(options.seed, item.id, trialIndex)) : undefined);
|
|
232
|
+
|
|
233
|
+
const agent =
|
|
234
|
+
typeof options.agent === "function" ? await options.agent({ hooks: options.hooks, slots: options.slots, item }) : options.agent;
|
|
235
|
+
const session = await agent.session();
|
|
236
|
+
const shouldProject = options.timeline && options.timeline !== "off";
|
|
237
|
+
let folder: TimelineFolder | undefined;
|
|
238
|
+
if (shouldProject) {
|
|
239
|
+
const { createTimelineFolder } = await loadTimeline();
|
|
240
|
+
folder = createTimelineFolder({ content: options.timeline, redactor: options.redactor });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const scenario = isScenarioInput(item.input) ? item.input : undefined;
|
|
244
|
+
const evaluations: EvaluationRecord[] = [];
|
|
245
|
+
let scoredSteps = 0;
|
|
246
|
+
let scoringError = false;
|
|
247
|
+
let simulation: UserSimulation | undefined;
|
|
248
|
+
const deferred: { result: RunResult; timeline?: ExecutionTimeline; environment: unknown; turnIndex: number }[] = [];
|
|
249
|
+
const score = async (turnIndex?: number, captured?: (typeof deferred)[number]) => {
|
|
250
|
+
const snapshot = captured ? captured.timeline : folder?.snapshot();
|
|
251
|
+
const timeline =
|
|
252
|
+
captured || turnIndex === undefined || snapshot === undefined
|
|
253
|
+
? snapshot
|
|
254
|
+
: { ...snapshot, steps: snapshot.steps.slice(scoredSteps) };
|
|
255
|
+
scoredSteps = snapshot?.steps.length ?? 0;
|
|
256
|
+
const environment = captured
|
|
257
|
+
? captured.environment
|
|
258
|
+
: options.toEnvironment
|
|
259
|
+
? await options.toEnvironment(item, result, timeline)
|
|
260
|
+
: undefined;
|
|
261
|
+
const scoredResult = captured?.result ?? result;
|
|
262
|
+
const metadata = {
|
|
263
|
+
...options.metadata,
|
|
264
|
+
...(trialPlan !== undefined || scenario ? { trialIndex } : {}),
|
|
265
|
+
...(turnIndex === undefined ? {} : { turnIndex }),
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
return scoredResult
|
|
269
|
+
? await scoreRun({
|
|
270
|
+
result: scoredResult,
|
|
271
|
+
scorers: options.scorers,
|
|
272
|
+
sampling: options.sampling,
|
|
273
|
+
store: options.store,
|
|
274
|
+
telemetry: options.telemetry,
|
|
275
|
+
ownership: options.ownership,
|
|
276
|
+
redactor: options.redactor,
|
|
277
|
+
secrets: options.secrets,
|
|
278
|
+
signal: options.signal,
|
|
279
|
+
datasetId: options.dataset.id,
|
|
280
|
+
itemId: item.id,
|
|
281
|
+
experimentId,
|
|
282
|
+
traceId: options.traceId,
|
|
283
|
+
traceResolver: options.traceResolver,
|
|
284
|
+
traceLimits: options.traceLimits,
|
|
285
|
+
metadata,
|
|
286
|
+
random,
|
|
287
|
+
item,
|
|
288
|
+
timeline: options.timeline,
|
|
289
|
+
injectedTimeline: timeline,
|
|
290
|
+
environment,
|
|
291
|
+
})
|
|
292
|
+
: [];
|
|
293
|
+
};
|
|
294
|
+
let durationMs = 0;
|
|
295
|
+
let startedTurns = 0,
|
|
296
|
+
completedTurns = 0;
|
|
297
|
+
let settledRunId: string | undefined;
|
|
298
|
+
let pricedTurns = true;
|
|
299
|
+
let settledRuns = true;
|
|
300
|
+
let currency: string | undefined;
|
|
301
|
+
const runResults: RunResult[] = [];
|
|
302
|
+
const run = async (input: string | Message | readonly Message[]) => {
|
|
303
|
+
const started = performance.now();
|
|
304
|
+
settledRunId = undefined;
|
|
305
|
+
const turnsBefore = completedTurns;
|
|
306
|
+
try {
|
|
307
|
+
const current = await collectWhileRunning(
|
|
308
|
+
session,
|
|
309
|
+
folder,
|
|
310
|
+
() =>
|
|
311
|
+
session.run(input, {
|
|
312
|
+
...options.runOptions,
|
|
313
|
+
signal: options.signal,
|
|
314
|
+
ownership: options.ownership ?? options.runOptions?.ownership,
|
|
315
|
+
redactor: options.redactor ?? options.runOptions?.redactor,
|
|
316
|
+
}),
|
|
317
|
+
(event) => {
|
|
318
|
+
if (event.type === "run.completed" || event.type === "run.failed" || event.type === "run.suspended") settledRunId = event.runId;
|
|
319
|
+
if (event.type === "turn.started") startedTurns++;
|
|
320
|
+
if (event.type !== "turn.completed") return;
|
|
321
|
+
if (completedTurns++ === 0) currency = event.usage?.currency;
|
|
322
|
+
const usage = event.usage;
|
|
323
|
+
pricedTurns &&=
|
|
324
|
+
usage !== undefined &&
|
|
325
|
+
usage.estimated !== true &&
|
|
326
|
+
usage.cost !== undefined &&
|
|
327
|
+
Number.isFinite(usage.cost) &&
|
|
328
|
+
usage.cost >= 0 &&
|
|
329
|
+
usage.currency === currency;
|
|
330
|
+
},
|
|
331
|
+
);
|
|
332
|
+
settledRuns &&= settledRunId === current.runId && completedTurns > turnsBefore;
|
|
333
|
+
result = current;
|
|
334
|
+
runResults.push(current);
|
|
335
|
+
if (current.status === "failed" || current.status === "aborted") {
|
|
336
|
+
error = current.error ?? toErrorInfo(new Error(`Agent run ${current.status}`));
|
|
337
|
+
}
|
|
338
|
+
return current;
|
|
339
|
+
} finally {
|
|
340
|
+
durationMs += performance.now() - started;
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
try {
|
|
344
|
+
if (scenario) {
|
|
345
|
+
simulation = await executeScenario(
|
|
346
|
+
{ ...scenario, signal: options.signal, redactor: options.redactor, secrets: options.secrets },
|
|
347
|
+
run,
|
|
348
|
+
async (current, turnIndex) => {
|
|
349
|
+
if (scenario.scoreTurns === "each") {
|
|
350
|
+
try {
|
|
351
|
+
if (scenario.user) {
|
|
352
|
+
const snapshot = folder?.snapshot();
|
|
353
|
+
const timeline = snapshot ? { ...snapshot, steps: snapshot.steps.slice(scoredSteps) } : undefined;
|
|
354
|
+
scoredSteps = snapshot?.steps.length ?? 0;
|
|
355
|
+
const environment = options.toEnvironment ? await options.toEnvironment(item, current, timeline) : undefined;
|
|
356
|
+
deferred.push({ result: current, timeline, environment, turnIndex });
|
|
357
|
+
} else evaluations.push(...(await score(turnIndex)));
|
|
358
|
+
} catch (caught) {
|
|
359
|
+
scoringError = true;
|
|
360
|
+
throw caught;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
},
|
|
364
|
+
);
|
|
365
|
+
} else {
|
|
366
|
+
await run(toAgentInput(item.input));
|
|
367
|
+
}
|
|
368
|
+
} catch (caught) {
|
|
369
|
+
if (scoringError) throw caught;
|
|
370
|
+
error = toErrorInfo(caught);
|
|
371
|
+
}
|
|
372
|
+
if (error?.code === "ERR_PRISM_EVAL_USER_SIMULATOR") {
|
|
373
|
+
evaluations.push(
|
|
374
|
+
...(await skipScorers(
|
|
375
|
+
{
|
|
376
|
+
result,
|
|
377
|
+
scorers: options.scorers,
|
|
378
|
+
store: options.store,
|
|
379
|
+
telemetry: options.telemetry,
|
|
380
|
+
ownership: options.ownership,
|
|
381
|
+
redactor: options.redactor,
|
|
382
|
+
secrets: options.secrets,
|
|
383
|
+
datasetId: options.dataset.id,
|
|
384
|
+
itemId: item.id,
|
|
385
|
+
experimentId,
|
|
386
|
+
traceId: options.traceId,
|
|
387
|
+
metadata: { ...options.metadata, trialIndex },
|
|
388
|
+
},
|
|
389
|
+
"ERR_PRISM_EVAL_USER_SIMULATOR",
|
|
390
|
+
)),
|
|
391
|
+
);
|
|
392
|
+
} else {
|
|
393
|
+
for (const turn of deferred) evaluations.push(...(await score(turn.turnIndex, turn)));
|
|
394
|
+
if (scenario?.scoreTurns !== "each") evaluations.push(...(await score()));
|
|
395
|
+
}
|
|
396
|
+
const usage: { -readonly [K in keyof Usage]?: Usage[K] } = {};
|
|
397
|
+
for (const field of ["inputTokens", "outputTokens", "totalTokens", "cacheReadTokens", "cacheWriteTokens", "cost"] as const) {
|
|
398
|
+
const values = runResults.flatMap((run) => (run.usage?.[field] === undefined ? [] : [run.usage[field]!]));
|
|
399
|
+
if (values.length) usage[field] = values.reduce((sum, value) => sum + value, 0);
|
|
400
|
+
}
|
|
401
|
+
if (runResults.some((run) => run.usage?.estimated)) usage.estimated = true;
|
|
402
|
+
const usageCurrency = runResults[0]?.usage?.currency;
|
|
403
|
+
if (runResults.every((run) => run.usage?.currency === usageCurrency) && usageCurrency !== undefined) usage.currency = usageCurrency;
|
|
404
|
+
const accounting: ExperimentItemResult["trials"][number] = {
|
|
405
|
+
simulation,
|
|
406
|
+
usage: runResults.length === 1 ? result?.usage : runResults.length ? usage : undefined,
|
|
407
|
+
durationMs,
|
|
408
|
+
status:
|
|
409
|
+
options.signal?.aborted || result?.status === "aborted"
|
|
410
|
+
? "aborted"
|
|
411
|
+
: error
|
|
412
|
+
? "failed"
|
|
413
|
+
: (result?.status ?? (simulation?.stopReason === "goal_reached" ? "completed" : "failed")),
|
|
414
|
+
costComplete:
|
|
415
|
+
error === undefined &&
|
|
416
|
+
settledRuns &&
|
|
417
|
+
runResults.length > 0 &&
|
|
418
|
+
startedTurns === completedTurns &&
|
|
419
|
+
pricedTurns &&
|
|
420
|
+
runResults.every(
|
|
421
|
+
(run) =>
|
|
422
|
+
run.status === "completed" &&
|
|
423
|
+
run.usage?.cost !== undefined &&
|
|
424
|
+
run.usage.estimated !== true &&
|
|
425
|
+
Number.isFinite(run.usage.cost) &&
|
|
426
|
+
run.usage.cost >= 0 &&
|
|
427
|
+
run.usage.currency === currency,
|
|
428
|
+
),
|
|
429
|
+
};
|
|
430
|
+
if (evaluations.length) sampleCount += 1;
|
|
431
|
+
|
|
432
|
+
return { result, accounting, evaluations, error };
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
let itemResults: ExperimentItemResult<TInput, TExpected>[];
|
|
436
|
+
try {
|
|
437
|
+
itemResults = await mapPool(
|
|
438
|
+
items,
|
|
439
|
+
concurrency,
|
|
440
|
+
async (item): Promise<ExperimentItemResult<TInput, TExpected>> => {
|
|
441
|
+
const evaluations: EvaluationRecord[] = [];
|
|
442
|
+
const trials: ExperimentItemResult["trials"][number][] = [];
|
|
443
|
+
let result: RunResult | undefined;
|
|
444
|
+
let error = undefined as ExperimentItemResult<TInput, TExpected>["error"];
|
|
445
|
+
for (let trialIndex = 0; trialIndex < trialCount; trialIndex++) {
|
|
446
|
+
const trial = await runTrial(item, trialIndex);
|
|
447
|
+
evaluations.push(...trial.evaluations);
|
|
448
|
+
trials.push(trial.accounting);
|
|
449
|
+
result = trial.result ?? result;
|
|
450
|
+
error = trial.error ?? error;
|
|
451
|
+
}
|
|
452
|
+
const itemResult: ExperimentItemResult<TInput, TExpected> = { item, result, trials, evaluations, error };
|
|
453
|
+
await options.onItem?.(itemResult);
|
|
454
|
+
return itemResult;
|
|
455
|
+
},
|
|
456
|
+
options.signal,
|
|
457
|
+
// Settle-all: finished items keep their results, unstarted ones fail with the abort reason.
|
|
458
|
+
(item, _index, error) => ({
|
|
459
|
+
item,
|
|
460
|
+
evaluations: [],
|
|
461
|
+
trials: Array.from({ length: trialCount }, () => ({
|
|
462
|
+
status: options.signal?.aborted ? ("aborted" as const) : ("failed" as const),
|
|
463
|
+
costComplete: false,
|
|
464
|
+
})),
|
|
465
|
+
error: toErrorInfo(error),
|
|
466
|
+
}),
|
|
467
|
+
);
|
|
468
|
+
} catch (error) {
|
|
469
|
+
fatal = error;
|
|
470
|
+
aborted = options.signal?.aborted === true;
|
|
471
|
+
itemResults = items.map((item) => ({
|
|
472
|
+
item,
|
|
473
|
+
trials: Array.from({ length: trialCount }, () => ({
|
|
474
|
+
status: aborted ? ("aborted" as const) : ("failed" as const),
|
|
475
|
+
costComplete: false,
|
|
476
|
+
})),
|
|
477
|
+
evaluations: [],
|
|
478
|
+
error: toErrorInfo(error),
|
|
479
|
+
}));
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const evaluations = itemResults.flatMap((item) => item.evaluations);
|
|
483
|
+
const tagGroups = new Map<string, { itemCount: number; evaluations: EvaluationRecord[] }>();
|
|
484
|
+
for (const result of itemResults)
|
|
485
|
+
for (const tag of new Set(result.item.tags ?? [])) {
|
|
486
|
+
const group = tagGroups.get(tag) ?? { itemCount: 0, evaluations: [] };
|
|
487
|
+
group.itemCount++;
|
|
488
|
+
group.evaluations.push(...result.evaluations);
|
|
489
|
+
tagGroups.set(tag, group);
|
|
490
|
+
}
|
|
491
|
+
const byTag = Object.fromEntries(
|
|
492
|
+
[...tagGroups].map(([tag, group]) => [
|
|
493
|
+
tag,
|
|
494
|
+
{
|
|
495
|
+
scorers: aggregateEvaluations(group.evaluations, passThresholds, trialCount, group.itemCount, options.seed).scorers,
|
|
496
|
+
},
|
|
497
|
+
]),
|
|
498
|
+
);
|
|
499
|
+
const aggregate = {
|
|
500
|
+
...aggregateEvaluations(evaluations, passThresholds, trialCount, items.length, options.seed),
|
|
501
|
+
itemCount: items.length,
|
|
502
|
+
cost: aggregateCost(itemResults),
|
|
503
|
+
byTag,
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
const status =
|
|
507
|
+
aborted || options.signal?.aborted
|
|
508
|
+
? "aborted"
|
|
509
|
+
: fatal || itemResults.some((item) => item.error && (!item.result || isScenarioInput(item.item.input)))
|
|
510
|
+
? "failed"
|
|
511
|
+
: "succeeded";
|
|
512
|
+
|
|
513
|
+
const trials: ExperimentTrials | undefined = trialPlan
|
|
514
|
+
? {
|
|
515
|
+
...trialPlan,
|
|
516
|
+
sampleCount,
|
|
517
|
+
}
|
|
518
|
+
: undefined;
|
|
519
|
+
|
|
520
|
+
const report: ExperimentReport<TInput, TExpected> = {
|
|
521
|
+
experimentId,
|
|
522
|
+
datasetId: options.dataset.id,
|
|
523
|
+
datasetVersion: options.dataset.version,
|
|
524
|
+
datasetContentHash: options.dataset.contentHash,
|
|
525
|
+
split: options.split,
|
|
526
|
+
canary: options.dataset.canary,
|
|
527
|
+
status,
|
|
528
|
+
items: itemResults,
|
|
529
|
+
evaluations,
|
|
530
|
+
aggregate,
|
|
531
|
+
manifest: options.manifest,
|
|
532
|
+
trials,
|
|
533
|
+
error: fatal ? toErrorInfo(fatal) : undefined,
|
|
534
|
+
};
|
|
535
|
+
await options.experimentStore?.append(toExperimentReportRecord(report, options.ownership));
|
|
536
|
+
return report;
|
|
537
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { AgentConfig, SessionEntry } from "@arnilo/prism";
|
|
2
|
+
import { EvalError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export interface SessionStore {
|
|
5
|
+
append(entry: SessionEntry, options?: unknown): Promise<void>;
|
|
6
|
+
list(sessionId: string): Promise<readonly SessionEntry[]>;
|
|
7
|
+
get?(id: string): Promise<SessionEntry | undefined>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface FailureInjectionOptions {
|
|
11
|
+
readonly failStore?: boolean;
|
|
12
|
+
readonly denyTools?: readonly string[];
|
|
13
|
+
readonly unknownEffect?: boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type HookRegistrar = Parameters<NonNullable<AgentConfig["hooks"]>>[0];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Returns an `AgentConfig.hooks` registration function for controlled eval failure injection.
|
|
20
|
+
* - `denyTools`: `tool.call` denies named tools with an injected denial.
|
|
21
|
+
* - `unknownEffect`: mutating tool executions skip their implementation and return an unknown effect result.
|
|
22
|
+
*/
|
|
23
|
+
export function failureInjection(injection: FailureInjectionOptions): NonNullable<AgentConfig["hooks"]> {
|
|
24
|
+
const denySet = new Set(injection.denyTools ?? []);
|
|
25
|
+
const unknownEffect = injection.unknownEffect === true;
|
|
26
|
+
|
|
27
|
+
return (hooks: HookRegistrar) => {
|
|
28
|
+
const mutatingCallIds = new Set<string>();
|
|
29
|
+
|
|
30
|
+
if (denySet.size > 0 || unknownEffect) {
|
|
31
|
+
hooks.on("tool.call", (payload) => {
|
|
32
|
+
if (denySet.has(payload.name)) {
|
|
33
|
+
return { deny: "injected tool denial" };
|
|
34
|
+
}
|
|
35
|
+
if (unknownEffect) {
|
|
36
|
+
const isMutating =
|
|
37
|
+
payload.effects.length === 0 || payload.effects.some((e) => e === "write" || e === "execute" || e === "external");
|
|
38
|
+
if (isMutating) {
|
|
39
|
+
mutatingCallIds.add(payload.callId);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (unknownEffect) {
|
|
47
|
+
hooks.on("tool.execute", async (payload, next) => {
|
|
48
|
+
if (mutatingCallIds.has(payload.callId)) {
|
|
49
|
+
return {
|
|
50
|
+
toolCallId: payload.callId,
|
|
51
|
+
name: payload.name,
|
|
52
|
+
error: {
|
|
53
|
+
message: "tool effect outcome requires reconciliation",
|
|
54
|
+
code: "ERR_PRISM_TOOL_EFFECT_UNKNOWN",
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return next(payload);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Wraps a SessionStore so that the run fails on its first `append`.
|
|
66
|
+
*/
|
|
67
|
+
export function failingStore(store?: SessionStore): SessionStore {
|
|
68
|
+
return {
|
|
69
|
+
async append(_entry: SessionEntry, _options?: unknown): Promise<void> {
|
|
70
|
+
throw new EvalError("injected store failure", "ERR_PRISM_EVAL_STORE_FAILURE");
|
|
71
|
+
},
|
|
72
|
+
async list(sessionId: string): Promise<readonly SessionEntry[]> {
|
|
73
|
+
return store ? store.list(sessionId) : [];
|
|
74
|
+
},
|
|
75
|
+
...(store?.get ? { get: (id: string) => store.get!(id) } : {}),
|
|
76
|
+
} as SessionStore;
|
|
77
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { AppendRunFeedbackInput, EvaluationRecord, EvaluationStore, RunFeedbackRecord, RunFeedbackStore } from "@arnilo/prism";
|
|
2
|
+
import { EvalError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export interface AppendEvaluationFeedbackInput {
|
|
5
|
+
readonly feedbackStore: RunFeedbackStore;
|
|
6
|
+
readonly evaluationStore: EvaluationStore;
|
|
7
|
+
readonly feedback: Omit<AppendRunFeedbackInput, "evaluationIds" | "scorerIds">;
|
|
8
|
+
readonly evaluationIds: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Resolve known evaluations, verify run/trace/ownership, then persist ID-only feedback linkage. */
|
|
12
|
+
export async function appendEvaluationFeedback(input: AppendEvaluationFeedbackInput): Promise<RunFeedbackRecord> {
|
|
13
|
+
if (
|
|
14
|
+
input.evaluationIds.length === 0 ||
|
|
15
|
+
input.evaluationIds.length > 64 ||
|
|
16
|
+
new Set(input.evaluationIds).size !== input.evaluationIds.length
|
|
17
|
+
) {
|
|
18
|
+
throw new EvalError("1-64 unique evaluationIds are required", "ERR_PRISM_EVAL_FEEDBACK");
|
|
19
|
+
}
|
|
20
|
+
const evaluations = await Promise.all(
|
|
21
|
+
input.evaluationIds.map(async (id) => {
|
|
22
|
+
const page = await input.evaluationStore.query({
|
|
23
|
+
id,
|
|
24
|
+
tenantId: input.feedback.tenantId,
|
|
25
|
+
accountId: input.feedback.accountId,
|
|
26
|
+
userId: input.feedback.userId,
|
|
27
|
+
limit: 1,
|
|
28
|
+
signal: input.feedback.signal,
|
|
29
|
+
});
|
|
30
|
+
const evaluation = page.items[0];
|
|
31
|
+
if (!evaluation || evaluation.id !== id) throw new EvalError("evaluation not found", "ERR_PRISM_EVAL_FEEDBACK");
|
|
32
|
+
return evaluation;
|
|
33
|
+
}),
|
|
34
|
+
);
|
|
35
|
+
for (const evaluation of evaluations) assertMatches(evaluation, input.feedback);
|
|
36
|
+
return input.feedbackStore.append({
|
|
37
|
+
...input.feedback,
|
|
38
|
+
evaluationIds: input.evaluationIds,
|
|
39
|
+
scorerIds: [...new Set(evaluations.map((evaluation) => evaluation.scorerId))],
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function assertMatches(evaluation: EvaluationRecord, feedback: AppendEvaluationFeedbackInput["feedback"]): void {
|
|
44
|
+
if (
|
|
45
|
+
evaluation.runId !== feedback.runId ||
|
|
46
|
+
evaluation.tenantId !== feedback.tenantId ||
|
|
47
|
+
evaluation.accountId !== feedback.accountId ||
|
|
48
|
+
evaluation.userId !== feedback.userId ||
|
|
49
|
+
(feedback.traceId !== undefined && evaluation.traceId !== undefined && evaluation.traceId !== feedback.traceId)
|
|
50
|
+
) {
|
|
51
|
+
throw new EvalError("evaluation does not match feedback run/trace ownership", "ERR_PRISM_EVAL_FEEDBACK");
|
|
52
|
+
}
|
|
53
|
+
}
|