@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.
- 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 +6167 -0
- package/host-builder/data/errors.json +546 -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 +252 -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 +317 -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 +64 -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,27 @@
|
|
|
1
|
+
// @types/bun's globals add `fetch.preconnect`, which conflicts with the plain `fetch` shapes in
|
|
2
|
+
// @arnilo/prism-extensions/mcp and @arnilo/prism-knowledge/rag. The package's tsconfig scopes `types` to
|
|
3
|
+
// node + bun-types/test.d.ts, so the two Bun globals this host uses are declared here.
|
|
4
|
+
declare const Bun: {
|
|
5
|
+
sleep(ms: number): Promise<void>;
|
|
6
|
+
spawn(command: string[], options: { stdout: "pipe"; stderr: "pipe" }): {
|
|
7
|
+
readonly exited: Promise<number>;
|
|
8
|
+
readonly stdout: ReadableStream<Uint8Array>;
|
|
9
|
+
readonly stderr: ReadableStream<Uint8Array>;
|
|
10
|
+
kill(signal?: number | NodeJS.Signals): void;
|
|
11
|
+
};
|
|
12
|
+
serve(options: {
|
|
13
|
+
readonly hostname?: string;
|
|
14
|
+
readonly port?: number;
|
|
15
|
+
readonly fetch: (request: Request) => Response | Promise<Response>;
|
|
16
|
+
}): {
|
|
17
|
+
readonly hostname: string;
|
|
18
|
+
readonly port: number;
|
|
19
|
+
stop(closeActiveConnections?: boolean): Promise<void> | void;
|
|
20
|
+
};
|
|
21
|
+
readonly Transpiler: new (options: {
|
|
22
|
+
readonly loader: "ts" | "tsx" | "js" | "jsx";
|
|
23
|
+
readonly target: "browser" | "bun" | "node";
|
|
24
|
+
}) => {
|
|
25
|
+
transformSync(source: string): string;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inspector comparison over existing 072 artifacts.
|
|
3
|
+
* Does not invent a report schema: TimelineSummary + ExperimentAggregate fields only.
|
|
4
|
+
* Invariant failures block quality winners so a good answer cannot average away a forbidden tool.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { DevtoolsError } from "./errors.js";
|
|
8
|
+
|
|
9
|
+
export interface InspectorCostSlice {
|
|
10
|
+
readonly amount: number;
|
|
11
|
+
readonly currency: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface InspectorSummarySlice {
|
|
15
|
+
readonly durationMs: number;
|
|
16
|
+
readonly errorCount: number;
|
|
17
|
+
readonly toolCallCount: number;
|
|
18
|
+
readonly status: string;
|
|
19
|
+
readonly cost?: InspectorCostSlice;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface InspectorAggregateSlice {
|
|
23
|
+
readonly macroMean?: number;
|
|
24
|
+
readonly scorers?: Readonly<Record<string, { readonly mean: number; readonly ci95?: { readonly low: number; readonly high: number } }>>;
|
|
25
|
+
readonly invariantsPassed?: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface InspectorCompareSide {
|
|
29
|
+
readonly summary: InspectorSummarySlice;
|
|
30
|
+
readonly aggregate?: InspectorAggregateSlice;
|
|
31
|
+
readonly manifest?: { readonly runtimeRevision?: string; readonly datasetVersion?: string };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type InspectorCompareWinner = "left" | "right" | "tie" | "unknown" | "invariant_blocked";
|
|
35
|
+
|
|
36
|
+
export interface InspectorComparison {
|
|
37
|
+
readonly left: InspectorCompareSide;
|
|
38
|
+
readonly right: InspectorCompareSide;
|
|
39
|
+
readonly latencyWinner: InspectorCompareWinner;
|
|
40
|
+
readonly costWinner: InspectorCompareWinner;
|
|
41
|
+
readonly qualityWinner: InspectorCompareWinner;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const MAX_COMPARE_BYTES = 64 * 1024;
|
|
45
|
+
|
|
46
|
+
export function compareInspectorRuns(left: InspectorCompareSide, right: InspectorCompareSide): InspectorComparison {
|
|
47
|
+
const invariantBlocked = left.aggregate?.invariantsPassed === false || right.aggregate?.invariantsPassed === false;
|
|
48
|
+
return {
|
|
49
|
+
left,
|
|
50
|
+
right,
|
|
51
|
+
latencyWinner: numericWinner(left.summary.durationMs, right.summary.durationMs, "lower"),
|
|
52
|
+
costWinner: numericWinner(left.summary.cost?.amount, right.summary.cost?.amount, "lower"),
|
|
53
|
+
qualityWinner: invariantBlocked ? "invariant_blocked" : qualityWinner(left.aggregate, right.aggregate),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function qualityWinner(left?: InspectorAggregateSlice, right?: InspectorAggregateSlice): InspectorCompareWinner {
|
|
58
|
+
const winner = numericWinner(left?.macroMean, right?.macroMean, "higher");
|
|
59
|
+
const ids = Object.keys(left?.scorers ?? {});
|
|
60
|
+
if (!ids.length || ids.length !== Object.keys(right?.scorers ?? {}).length) return winner;
|
|
61
|
+
const pairs = ids.map((id) => [left?.scorers?.[id]?.ci95, right?.scorers?.[id]?.ci95] as const);
|
|
62
|
+
if (pairs.some(([a, b]) => !a || !b)) return winner;
|
|
63
|
+
// A macro winner needs every scorer's interval to support the same direction.
|
|
64
|
+
return pairs.every(([a, b]) => (winner === "left" ? a!.low > b!.high : winner === "right" && b!.low > a!.high)) ? winner : "tie";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function parseInspectorCompareBody(text: string): InspectorComparison {
|
|
68
|
+
if (Buffer.byteLength(text, "utf8") > MAX_COMPARE_BYTES) {
|
|
69
|
+
throw new DevtoolsError("compare body too large", "ERR_PRISM_DEVTOOLS_LIMIT", 413);
|
|
70
|
+
}
|
|
71
|
+
let parsed: unknown;
|
|
72
|
+
try {
|
|
73
|
+
parsed = JSON.parse(text) as unknown;
|
|
74
|
+
} catch {
|
|
75
|
+
throw new DevtoolsError("invalid compare JSON", "ERR_PRISM_DEVTOOLS_REQUEST", 400);
|
|
76
|
+
}
|
|
77
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
78
|
+
throw new DevtoolsError("compare body must be { left, right }", "ERR_PRISM_DEVTOOLS_REQUEST", 400);
|
|
79
|
+
}
|
|
80
|
+
const body = parsed as { left?: unknown; right?: unknown };
|
|
81
|
+
const left = asSide(body.left);
|
|
82
|
+
const right = asSide(body.right);
|
|
83
|
+
if (!left || !right) {
|
|
84
|
+
throw new DevtoolsError("left and right must carry a metadata summary", "ERR_PRISM_DEVTOOLS_REQUEST", 400);
|
|
85
|
+
}
|
|
86
|
+
return compareInspectorRuns(left, right);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function asSide(value: unknown): InspectorCompareSide | undefined {
|
|
90
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
91
|
+
const raw = value as { summary?: unknown; aggregate?: unknown; manifest?: unknown };
|
|
92
|
+
const summary = asSummary(raw.summary);
|
|
93
|
+
if (!summary) return undefined;
|
|
94
|
+
const aggregate = asAggregate(raw.aggregate);
|
|
95
|
+
const manifest = asManifest(raw.manifest);
|
|
96
|
+
return {
|
|
97
|
+
summary,
|
|
98
|
+
...(aggregate ? { aggregate } : {}),
|
|
99
|
+
...(manifest ? { manifest } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function asSummary(value: unknown): InspectorSummarySlice | undefined {
|
|
104
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
105
|
+
const s = value as Record<string, unknown>;
|
|
106
|
+
if (!finiteNonNeg(s.durationMs) || !finiteNonNeg(s.errorCount) || !finiteNonNeg(s.toolCallCount)) return undefined;
|
|
107
|
+
if (typeof s.status !== "string" || s.status.length < 1 || s.status.length > 64) return undefined;
|
|
108
|
+
const cost = asCost(s.cost);
|
|
109
|
+
return {
|
|
110
|
+
durationMs: s.durationMs as number,
|
|
111
|
+
errorCount: s.errorCount as number,
|
|
112
|
+
toolCallCount: s.toolCallCount as number,
|
|
113
|
+
status: s.status,
|
|
114
|
+
...(cost ? { cost } : {}),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function asCost(value: unknown): InspectorCostSlice | undefined {
|
|
119
|
+
if (value === undefined) return undefined;
|
|
120
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
121
|
+
const c = value as Record<string, unknown>;
|
|
122
|
+
if (!finiteNonNeg(c.amount) || typeof c.currency !== "string" || c.currency.length < 1 || c.currency.length > 8) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
return { amount: c.amount as number, currency: c.currency };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function asAggregate(value: unknown): InspectorAggregateSlice | undefined {
|
|
129
|
+
if (value === undefined) return undefined;
|
|
130
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
131
|
+
const a = value as Record<string, unknown>;
|
|
132
|
+
const macroMean = a.macroMean === undefined ? undefined : finiteUnit(a.macroMean) ? (a.macroMean as number) : undefined;
|
|
133
|
+
const invariantsPassed = typeof a.invariantsPassed === "boolean" ? a.invariantsPassed : undefined;
|
|
134
|
+
let scorers: InspectorAggregateSlice["scorers"];
|
|
135
|
+
if (a.scorers && typeof a.scorers === "object" && !Array.isArray(a.scorers)) {
|
|
136
|
+
const entries = Object.entries(a.scorers).map(([id, value]) => {
|
|
137
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
138
|
+
const raw = value as Record<string, unknown>;
|
|
139
|
+
if (!finiteUnit(raw.mean)) return undefined;
|
|
140
|
+
const interval = raw.ci95 as { low?: unknown; high?: unknown } | undefined;
|
|
141
|
+
if (interval !== undefined && (!interval || !finiteUnit(interval.low) || !finiteUnit(interval.high) || interval.low > interval.high))
|
|
142
|
+
return undefined;
|
|
143
|
+
return [
|
|
144
|
+
id,
|
|
145
|
+
{ mean: raw.mean, ...(interval ? { ci95: { low: interval.low as number, high: interval.high as number } } : {}) },
|
|
146
|
+
] as const;
|
|
147
|
+
});
|
|
148
|
+
if (entries.some((entry) => entry === undefined))
|
|
149
|
+
throw new DevtoolsError("invalid scorer statistics", "ERR_PRISM_DEVTOOLS_REQUEST", 400);
|
|
150
|
+
scorers = Object.fromEntries(entries as NonNullable<(typeof entries)[number]>[]);
|
|
151
|
+
}
|
|
152
|
+
if (macroMean === undefined && invariantsPassed === undefined && scorers === undefined) return undefined;
|
|
153
|
+
return {
|
|
154
|
+
...(macroMean === undefined ? {} : { macroMean }),
|
|
155
|
+
...(scorers === undefined ? {} : { scorers }),
|
|
156
|
+
...(invariantsPassed === undefined ? {} : { invariantsPassed }),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function asManifest(value: unknown): InspectorCompareSide["manifest"] | undefined {
|
|
161
|
+
if (value === undefined) return undefined;
|
|
162
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
163
|
+
const m = value as Record<string, unknown>;
|
|
164
|
+
const runtimeRevision = shortId(m.runtimeRevision);
|
|
165
|
+
const datasetVersion = shortId(m.datasetVersion);
|
|
166
|
+
if (!runtimeRevision && !datasetVersion) return undefined;
|
|
167
|
+
return {
|
|
168
|
+
...(runtimeRevision ? { runtimeRevision } : {}),
|
|
169
|
+
...(datasetVersion ? { datasetVersion } : {}),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function finiteNonNeg(value: unknown): value is number {
|
|
174
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function finiteUnit(value: unknown): value is number {
|
|
178
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function shortId(value: unknown): string | undefined {
|
|
182
|
+
return typeof value === "string" && value.length >= 1 && value.length <= 128 && !value.includes("\0") ? value : undefined;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function numericWinner(left: number | undefined, right: number | undefined, prefer: "lower" | "higher"): InspectorCompareWinner {
|
|
186
|
+
if (left === undefined || right === undefined) return "unknown";
|
|
187
|
+
if (left === right) return "tie";
|
|
188
|
+
if (prefer === "lower") return left < right ? "left" : "right";
|
|
189
|
+
return left > right ? "left" : "right";
|
|
190
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A devtools failure with a stable code. `status` is the HTTP status a route answers with; construction
|
|
3
|
+
* errors (a non-loopback bind without a token, a literal token) never reach a response.
|
|
4
|
+
*/
|
|
5
|
+
export class DevtoolsError extends Error {
|
|
6
|
+
readonly code: string;
|
|
7
|
+
readonly status: number;
|
|
8
|
+
|
|
9
|
+
constructor(message: string, code = "ERR_PRISM_DEVTOOLS", status = 400) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "DevtoolsError";
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.status = status;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@arnilo/prism-hosts/devtools`: a loopback developer inspector over one Prism `Agent`.
|
|
3
|
+
*
|
|
4
|
+
* `serveDevtools(agent, { port })` serves the page and its JSON routes. Each route reads the public
|
|
5
|
+
* `Agent` API only. The `prism-devtools` bin serves a manifest-built agent with the same server.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export { type DevtoolsArgs, DevtoolsArgsError, type DevtoolsModel, parseDevtoolsArgs } from "./args.js";
|
|
9
|
+
export {
|
|
10
|
+
compareInspectorRuns,
|
|
11
|
+
type InspectorCompareSide,
|
|
12
|
+
type InspectorCompareWinner,
|
|
13
|
+
type InspectorComparison,
|
|
14
|
+
parseInspectorCompareBody,
|
|
15
|
+
} from "./compare.js";
|
|
16
|
+
export { DevtoolsError } from "./errors.js";
|
|
17
|
+
export { REPLAY_DEFAULT_LIMIT, REPLAY_MAX_LIMIT, type ReplayPage, replayPage } from "./replay.js";
|
|
18
|
+
export {
|
|
19
|
+
DEVTOOLS_DEFAULT_HOSTNAME,
|
|
20
|
+
DEVTOOLS_DEFAULT_PORT,
|
|
21
|
+
type DevtoolsOptions,
|
|
22
|
+
type DevtoolsServer,
|
|
23
|
+
type ServeDevtoolsOptions,
|
|
24
|
+
serveDevtools,
|
|
25
|
+
} from "./serve.js";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paged replay over a session's stored entries. Read-only: no run starts and no provider is consulted.
|
|
3
|
+
* A cursor is the index of the next entry, so a page is a slice of the list the session already holds.
|
|
4
|
+
*/
|
|
5
|
+
import type { SessionEntry } from "@arnilo/prism";
|
|
6
|
+
import { DevtoolsError } from "./errors.js";
|
|
7
|
+
|
|
8
|
+
export const REPLAY_DEFAULT_LIMIT = 100;
|
|
9
|
+
export const REPLAY_MAX_LIMIT = 500;
|
|
10
|
+
|
|
11
|
+
export interface ReplayPage {
|
|
12
|
+
readonly items: readonly SessionEntry[];
|
|
13
|
+
readonly nextCursor?: string;
|
|
14
|
+
readonly terminal: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function replayPage(
|
|
18
|
+
entries: readonly SessionEntry[],
|
|
19
|
+
options: { readonly cursor?: string; readonly limit?: number } = {},
|
|
20
|
+
): ReplayPage {
|
|
21
|
+
const start = parseCursor(options.cursor);
|
|
22
|
+
const limit = options.limit ?? REPLAY_DEFAULT_LIMIT;
|
|
23
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > REPLAY_MAX_LIMIT) {
|
|
24
|
+
throw new DevtoolsError(`limit must be an integer from 1 to ${REPLAY_MAX_LIMIT}`, "ERR_PRISM_DEVTOOLS_QUERY");
|
|
25
|
+
}
|
|
26
|
+
if (start > entries.length) throw new DevtoolsError("cursor is past the last entry", "ERR_PRISM_DEVTOOLS_QUERY");
|
|
27
|
+
const end = Math.min(entries.length, start + limit);
|
|
28
|
+
const terminal = end === entries.length;
|
|
29
|
+
return { items: entries.slice(start, end), terminal, ...(terminal ? {} : { nextCursor: String(end) }) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function parseCursor(cursor: string | undefined): number {
|
|
33
|
+
if (cursor === undefined) return 0;
|
|
34
|
+
if (!/^\d{1,15}$/.test(cursor)) throw new DevtoolsError("cursor must be a non-negative integer", "ERR_PRISM_DEVTOOLS_QUERY");
|
|
35
|
+
return Number(cursor);
|
|
36
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bearer-token guard for the devtools server. A token is a ref (`env:NAME`), never a literal: the
|
|
3
|
+
* value is read from the environment at serve time and compared in constant time on every request.
|
|
4
|
+
*/
|
|
5
|
+
import { timingSafeEqual } from "node:crypto";
|
|
6
|
+
import { DevtoolsError } from "./errors.js";
|
|
7
|
+
|
|
8
|
+
const ENV_REF = /^env:([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
9
|
+
|
|
10
|
+
export const DEVTOOLS_JSON_HEADERS = {
|
|
11
|
+
"content-type": "application/json; charset=utf-8",
|
|
12
|
+
"cache-control": "no-store",
|
|
13
|
+
"x-content-type-options": "nosniff",
|
|
14
|
+
} as const;
|
|
15
|
+
|
|
16
|
+
export interface DevtoolsHostOriginOptions {
|
|
17
|
+
readonly allowedHosts?: readonly string[];
|
|
18
|
+
readonly allowedOrigins?: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Host/Origin matching parity with hosts/remote/src/http-gate.ts hostOriginRejection.
|
|
23
|
+
* Rejects requests with unexpected Host or Origin headers to protect loopback devtools from DNS rebinding.
|
|
24
|
+
*/
|
|
25
|
+
export function hostOriginRejection(request: Request, options: DevtoolsHostOriginOptions): Response | undefined {
|
|
26
|
+
if (options.allowedHosts?.length) {
|
|
27
|
+
const host = request.headers.get("host")?.toLowerCase();
|
|
28
|
+
if (!host || !options.allowedHosts.some((allowed) => allowed.toLowerCase() === host)) {
|
|
29
|
+
return new Response(
|
|
30
|
+
JSON.stringify({
|
|
31
|
+
error: {
|
|
32
|
+
code: "ERR_PRISM_DEVTOOLS_FORBIDDEN_HOST",
|
|
33
|
+
message: "Forbidden host",
|
|
34
|
+
},
|
|
35
|
+
}),
|
|
36
|
+
{ status: 403, headers: DEVTOOLS_JSON_HEADERS },
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (options.allowedOrigins?.length) {
|
|
41
|
+
const origin = request.headers.get("origin");
|
|
42
|
+
if (origin && !options.allowedOrigins.some((allowed) => allowed.toLowerCase() === origin.toLowerCase())) {
|
|
43
|
+
return new Response(
|
|
44
|
+
JSON.stringify({
|
|
45
|
+
error: {
|
|
46
|
+
code: "ERR_PRISM_DEVTOOLS_FORBIDDEN_ORIGIN",
|
|
47
|
+
message: "Forbidden origin",
|
|
48
|
+
},
|
|
49
|
+
}),
|
|
50
|
+
{ status: 403, headers: DEVTOOLS_JSON_HEADERS },
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Resolves a token ref to its value. `undefined` in, `undefined` out: the server then runs without a guard. */
|
|
58
|
+
export function resolveDevtoolsToken(
|
|
59
|
+
ref: string | undefined,
|
|
60
|
+
env: Readonly<Record<string, string | undefined>> = process.env,
|
|
61
|
+
): string | undefined {
|
|
62
|
+
if (ref === undefined) return undefined;
|
|
63
|
+
const match = ENV_REF.exec(ref);
|
|
64
|
+
if (!match) {
|
|
65
|
+
throw new DevtoolsError(
|
|
66
|
+
"token must be an env: ref (for example env:PRISM_DEVTOOLS_TOKEN); a literal token is refused",
|
|
67
|
+
"ERR_PRISM_DEVTOOLS_TOKEN_LITERAL",
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
const value = env[match[1]!];
|
|
71
|
+
if (!value) throw new DevtoolsError(`token ref ${ref} is not set`, "ERR_PRISM_DEVTOOLS_TOKEN_UNSET");
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** True when the request carries `Authorization: Bearer <token>`. Constant time over the header bytes. */
|
|
76
|
+
export function bearerMatches(request: Request, token: string): boolean {
|
|
77
|
+
const presented = Buffer.from(request.headers.get("authorization") ?? "");
|
|
78
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
79
|
+
return presented.length === expected.length && timingSafeEqual(presented, expected);
|
|
80
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `serveDevtools(agent, options)`: the developer inspector over one `Agent`.
|
|
3
|
+
*
|
|
4
|
+
* Served on `Bun.serve`. Every route reads through the public `Agent`: `inspect()`, `sessions`,
|
|
5
|
+
* `session({ id }).entries()`, and `subscribe()`. This module builds no agent and reaches no kernel
|
|
6
|
+
* internal. JSON bodies and SSE events pass the agent's redactor on the way out. A bearer token ref
|
|
7
|
+
* guards every route, the page included, when one is set. A non-loopback bind requires one.
|
|
8
|
+
*/
|
|
9
|
+
import { type Agent, type AgentEvent, isSessionNotFound, type SecretRedactor } from "@arnilo/prism";
|
|
10
|
+
import { isLoopbackHostname } from "@arnilo/prism/net";
|
|
11
|
+
import { parseInspectorCompareBody } from "./compare.js";
|
|
12
|
+
import { DevtoolsError } from "./errors.js";
|
|
13
|
+
import { REPLAY_MAX_LIMIT, replayPage } from "./replay.js";
|
|
14
|
+
import { bearerMatches, type DevtoolsHostOriginOptions, hostOriginRejection, resolveDevtoolsToken } from "./security.js";
|
|
15
|
+
import { inspectorPageResponse, inspectorScriptResponse } from "./ui/assets.js";
|
|
16
|
+
|
|
17
|
+
export const DEVTOOLS_DEFAULT_PORT = 4311;
|
|
18
|
+
export const DEVTOOLS_DEFAULT_HOSTNAME = "127.0.0.1";
|
|
19
|
+
const SESSION_LIST_MAX_LIMIT = 200;
|
|
20
|
+
|
|
21
|
+
export interface DevtoolsOptions {
|
|
22
|
+
/** Listen port. `0` picks a free one. Defaults to 4311. */
|
|
23
|
+
readonly port?: number;
|
|
24
|
+
/** Listen address. Defaults to `127.0.0.1`. A non-loopback address requires `token`. */
|
|
25
|
+
readonly hostname?: string;
|
|
26
|
+
/** Bearer token ref (`env:NAME`). Required for a non-loopback `hostname`. Checked on every route when set. */
|
|
27
|
+
readonly token?: string;
|
|
28
|
+
/** Allowed Host header values. Defaults to the bound loopback host:port pairs (`127.0.0.1:<port>`, `localhost:<port>`, `[::1]:<port>`). */
|
|
29
|
+
readonly allowedHosts?: readonly string[];
|
|
30
|
+
/** Allowed Origin header values. Defaults to the bound loopback origins (`http://127.0.0.1:<port>`, `http://localhost:<port>`, `http://[::1]:<port>`). */
|
|
31
|
+
readonly allowedOrigins?: readonly string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type ServeDevtoolsOptions = DevtoolsOptions;
|
|
35
|
+
|
|
36
|
+
export interface DevtoolsServer {
|
|
37
|
+
/** The base URL the page is served from. */
|
|
38
|
+
readonly url: string;
|
|
39
|
+
readonly hostname: string;
|
|
40
|
+
readonly port: number;
|
|
41
|
+
/** Closes live event streams and the listener. */
|
|
42
|
+
close(): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface RouteContext {
|
|
46
|
+
readonly agent: Agent;
|
|
47
|
+
readonly redactor: SecretRedactor | undefined;
|
|
48
|
+
/** Closers for open SSE feeds, so `close()` ends them without waiting for a client. */
|
|
49
|
+
readonly feeds: Set<() => void>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const JSON_HEADERS = {
|
|
53
|
+
"content-type": "application/json; charset=utf-8",
|
|
54
|
+
"cache-control": "no-store",
|
|
55
|
+
"x-content-type-options": "nosniff",
|
|
56
|
+
} as const;
|
|
57
|
+
|
|
58
|
+
const SSE_HEADERS = {
|
|
59
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
60
|
+
"cache-control": "no-store",
|
|
61
|
+
"x-accel-buffering": "no",
|
|
62
|
+
} as const;
|
|
63
|
+
|
|
64
|
+
export function serveDevtools(agent: Agent, options: DevtoolsOptions = {}): DevtoolsServer {
|
|
65
|
+
const hostname = options.hostname ?? DEVTOOLS_DEFAULT_HOSTNAME;
|
|
66
|
+
const loopback = isLoopbackHostname(hostname);
|
|
67
|
+
if (!loopback && options.token === undefined) {
|
|
68
|
+
throw new DevtoolsError(
|
|
69
|
+
`non-loopback hostname "${hostname}" requires a token ref (for example token: "env:PRISM_DEVTOOLS_TOKEN")`,
|
|
70
|
+
"ERR_PRISM_DEVTOOLS_REMOTE_BIND",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
// Resolved before the listener exists, so an unset token ref fails without a socket.
|
|
74
|
+
const token = resolveDevtoolsToken(options.token);
|
|
75
|
+
const context: RouteContext = { agent, redactor: agent.config.redactor, feeds: new Set() };
|
|
76
|
+
let gate: DevtoolsHostOriginOptions;
|
|
77
|
+
const server = Bun.serve({
|
|
78
|
+
hostname,
|
|
79
|
+
port: options.port ?? DEVTOOLS_DEFAULT_PORT,
|
|
80
|
+
fetch: (request) => handle(request, context, token, gate),
|
|
81
|
+
});
|
|
82
|
+
// A unix-socket server reports no hostname/port; fall back to the requested values.
|
|
83
|
+
const boundHostname = server.hostname ?? hostname;
|
|
84
|
+
const boundPort = server.port ?? options.port ?? DEVTOOLS_DEFAULT_PORT;
|
|
85
|
+
gate = {
|
|
86
|
+
allowedHosts: options.allowedHosts ?? [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`],
|
|
87
|
+
allowedOrigins: options.allowedOrigins ?? [
|
|
88
|
+
`http://127.0.0.1:${boundPort}`,
|
|
89
|
+
`http://localhost:${boundPort}`,
|
|
90
|
+
`http://[::1]:${boundPort}`,
|
|
91
|
+
],
|
|
92
|
+
};
|
|
93
|
+
const displayHost = boundHostname.includes(":") ? `[${boundHostname}]` : boundHostname;
|
|
94
|
+
return {
|
|
95
|
+
url: `http://${displayHost}:${boundPort}`,
|
|
96
|
+
hostname: boundHostname,
|
|
97
|
+
port: boundPort,
|
|
98
|
+
async close() {
|
|
99
|
+
for (const closeFeed of [...context.feeds]) closeFeed();
|
|
100
|
+
context.feeds.clear();
|
|
101
|
+
await server.stop(true);
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function handle(
|
|
107
|
+
request: Request,
|
|
108
|
+
context: RouteContext,
|
|
109
|
+
token: string | undefined,
|
|
110
|
+
gate: DevtoolsHostOriginOptions,
|
|
111
|
+
): Promise<Response> {
|
|
112
|
+
const denied = hostOriginRejection(request, gate);
|
|
113
|
+
if (denied) return denied;
|
|
114
|
+
if (token !== undefined && !bearerMatches(request, token)) {
|
|
115
|
+
return errorResponse(401, "ERR_PRISM_DEVTOOLS_UNAUTHORIZED", "Unauthorized", { "www-authenticate": 'Bearer realm="prism-devtools"' });
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
return await route(request, new URL(request.url), context);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (isSessionNotFound(error)) return errorResponse(404, "ERR_PRISM_DEVTOOLS_NOT_FOUND", "Session not found");
|
|
121
|
+
if (error instanceof DevtoolsError) return errorResponse(error.status, error.code, error.message);
|
|
122
|
+
return errorResponse(500, "ERR_PRISM_DEVTOOLS", "Devtools request failed");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function route(request: Request, url: URL, context: RouteContext): Promise<Response> {
|
|
127
|
+
const { method } = request;
|
|
128
|
+
const path = url.pathname;
|
|
129
|
+
if (method === "GET" && path === "/") return inspectorPageResponse();
|
|
130
|
+
if (method === "GET" && path === "/assets/inspector.js") return inspectorScriptResponse();
|
|
131
|
+
if (method === "GET" && path === "/api/inspect") return json(context, context.agent.inspect());
|
|
132
|
+
if (method === "GET" && path === "/api/sessions") {
|
|
133
|
+
return json(context, await context.agent.sessions.list(listQuery(url)));
|
|
134
|
+
}
|
|
135
|
+
if (method === "GET" && path === "/api/replay") {
|
|
136
|
+
const session = await context.agent.session({ id: requiredParam(url, "session") });
|
|
137
|
+
const cursor = url.searchParams.get("cursor") ?? undefined;
|
|
138
|
+
return json(context, replayPage(await session.entries(), { cursor, limit: limitParam(url, REPLAY_MAX_LIMIT) }));
|
|
139
|
+
}
|
|
140
|
+
if (method === "POST" && path === "/api/compare") {
|
|
141
|
+
return json(context, parseInspectorCompareBody(await request.text()));
|
|
142
|
+
}
|
|
143
|
+
if (method === "GET" && path === "/api/events") {
|
|
144
|
+
return eventStream(context, url.searchParams.get("session"));
|
|
145
|
+
}
|
|
146
|
+
const match = /^\/api\/sessions\/([^/]+)(\/entries)?$/.exec(path);
|
|
147
|
+
if (method === "GET" && match) {
|
|
148
|
+
const id = decodeSegment(match[1]!);
|
|
149
|
+
if (match[2]) {
|
|
150
|
+
const opened = await context.agent.session({ id });
|
|
151
|
+
return json(context, { sessionId: id, entries: await opened.entries() });
|
|
152
|
+
}
|
|
153
|
+
const summary = await context.agent.sessions.get(id);
|
|
154
|
+
if (summary === undefined) return errorResponse(404, "ERR_PRISM_DEVTOOLS_NOT_FOUND", "Session not found");
|
|
155
|
+
return json(context, summary);
|
|
156
|
+
}
|
|
157
|
+
return errorResponse(404, "ERR_PRISM_DEVTOOLS_NOT_FOUND", "Not found");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Every JSON body passes the agent's redactor, so no route can return a secret the agent holds. */
|
|
161
|
+
function json(context: RouteContext, body: unknown, status = 200): Response {
|
|
162
|
+
const safe = context.redactor ? context.redactor.redact(body) : body;
|
|
163
|
+
return new Response(JSON.stringify(safe), { status, headers: JSON_HEADERS });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function errorResponse(status: number, code: string, message: string, headers: Record<string, string> = {}): Response {
|
|
167
|
+
return new Response(JSON.stringify({ error: { code, message } }), {
|
|
168
|
+
status,
|
|
169
|
+
headers: { ...JSON_HEADERS, ...headers },
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Server-sent events: `agent` for `agent.subscribe()`, and `session` for the `?session=` session's
|
|
175
|
+
* `subscribe()`. Both subscriptions open when the request arrives. A client disconnect or `close()`
|
|
176
|
+
* ends them, and a failing source ends only its own feed.
|
|
177
|
+
*/
|
|
178
|
+
async function eventStream(context: RouteContext, sessionId: string | null): Promise<Response> {
|
|
179
|
+
// Opens the session first, so an unknown id fails before any agent subscription exists.
|
|
180
|
+
const session = sessionId === null ? undefined : await context.agent.session({ id: sessionId });
|
|
181
|
+
const sources: Array<{ name: string; events: AsyncIterable<AgentEvent> }> = [{ name: "agent", events: context.agent.subscribe() }];
|
|
182
|
+
// A Session's subscribers belong to that Session object. This feed sees runs started through the object
|
|
183
|
+
// the route opened, and `acrossRuns` keeps it open across them. Runs on another instance of the same id are
|
|
184
|
+
// not visible through the public API; the agent feed still carries `session.opened` / `session.closed`.
|
|
185
|
+
if (session) sources.push({ name: "session", events: session.subscribe({ acrossRuns: true }) });
|
|
186
|
+
const encoder = new TextEncoder();
|
|
187
|
+
const feeds = context.feeds;
|
|
188
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
189
|
+
start(controller) {
|
|
190
|
+
let open = true;
|
|
191
|
+
let live = sources.length;
|
|
192
|
+
const iterators = sources.map(({ name, events }) => ({ name, iterator: events[Symbol.asyncIterator]() }));
|
|
193
|
+
const close = (): void => {
|
|
194
|
+
if (!open) return;
|
|
195
|
+
open = false;
|
|
196
|
+
feeds.delete(close);
|
|
197
|
+
for (const { iterator } of iterators) void iterator.return?.();
|
|
198
|
+
try {
|
|
199
|
+
controller.close();
|
|
200
|
+
} catch {
|
|
201
|
+
// Already closed by the client.
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
feeds.add(close);
|
|
205
|
+
controller.enqueue(encoder.encode(": connected\n\n"));
|
|
206
|
+
for (const { name, iterator } of iterators) {
|
|
207
|
+
void (async () => {
|
|
208
|
+
try {
|
|
209
|
+
for (;;) {
|
|
210
|
+
const next = await iterator.next();
|
|
211
|
+
if (next.done || !open) break;
|
|
212
|
+
const event = context.redactor ? context.redactor.redact(next.value) : next.value;
|
|
213
|
+
controller.enqueue(encoder.encode(`event: ${name}\ndata: ${JSON.stringify(event)}\n\n`));
|
|
214
|
+
}
|
|
215
|
+
} catch {
|
|
216
|
+
// A failed source ends its own feed; the others keep streaming.
|
|
217
|
+
} finally {
|
|
218
|
+
live -= 1;
|
|
219
|
+
if (live === 0) close();
|
|
220
|
+
}
|
|
221
|
+
})();
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
cancel() {
|
|
225
|
+
for (const closeFeed of [...feeds]) closeFeed();
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
return new Response(stream, { headers: SSE_HEADERS });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function listQuery(url: URL): { cursor?: string; limit?: number } {
|
|
232
|
+
const cursor = url.searchParams.get("cursor") ?? undefined;
|
|
233
|
+
const limit = limitParam(url, SESSION_LIST_MAX_LIMIT);
|
|
234
|
+
return { ...(cursor === undefined ? {} : { cursor }), ...(limit === undefined ? {} : { limit }) };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function limitParam(url: URL, max: number): number | undefined {
|
|
238
|
+
const raw = url.searchParams.get("limit");
|
|
239
|
+
if (raw === null) return undefined;
|
|
240
|
+
const value = Number(raw);
|
|
241
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > max) {
|
|
242
|
+
throw new DevtoolsError(`limit must be an integer from 1 to ${max}`, "ERR_PRISM_DEVTOOLS_QUERY");
|
|
243
|
+
}
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function requiredParam(url: URL, name: string): string {
|
|
248
|
+
const value = url.searchParams.get(name);
|
|
249
|
+
if (!value) throw new DevtoolsError(`${name} query parameter is required`, "ERR_PRISM_DEVTOOLS_QUERY");
|
|
250
|
+
return value;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function decodeSegment(segment: string): string {
|
|
254
|
+
try {
|
|
255
|
+
return decodeURIComponent(segment);
|
|
256
|
+
} catch {
|
|
257
|
+
throw new DevtoolsError("malformed path segment", "ERR_PRISM_DEVTOOLS_QUERY");
|
|
258
|
+
}
|
|
259
|
+
}
|