@warlock.js/ai-panoptic 5.52.0 → 5.53.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 +23 -0
- package/cjs/index.cjs +592 -424
- package/cjs/index.cjs.map +1 -1
- package/esm/config/apply-panoptic-config.d.mts.map +1 -1
- package/esm/config/apply-panoptic-config.mjs +9 -3
- package/esm/config/apply-panoptic-config.mjs.map +1 -1
- package/esm/config/panoptic-config.type.d.mts +7 -0
- package/esm/config/panoptic-config.type.d.mts.map +1 -1
- package/esm/dashboard/index.d.mts +1 -0
- package/esm/dashboard/index.mjs +1 -1
- package/esm/dashboard/parse-query.mjs +23 -1
- package/esm/dashboard/parse-query.mjs.map +1 -1
- package/esm/dashboard/serve.mjs +55 -10
- package/esm/dashboard/serve.mjs.map +1 -1
- package/esm/dashboard/trace-summary.d.mts +24 -0
- package/esm/dashboard/trace-summary.d.mts.map +1 -0
- package/esm/dashboard/trace-summary.mjs +27 -0
- package/esm/dashboard/trace-summary.mjs.map +1 -0
- package/esm/dashboard/ui.html.mjs +68 -18
- package/esm/dashboard/ui.html.mjs.map +1 -1
- package/esm/index.d.mts +2 -1
- package/esm/index.mjs +1 -1
- package/esm/store/cache-trace-store.d.mts.map +1 -1
- package/esm/store/cache-trace-store.mjs +37 -17
- package/esm/store/cache-trace-store.mjs.map +1 -1
- package/esm/store/in-memory-trace-store.d.mts.map +1 -1
- package/esm/store/in-memory-trace-store.mjs +2 -9
- package/esm/store/in-memory-trace-store.mjs.map +1 -1
- package/esm/store/sort-newest-first.mjs +14 -0
- package/esm/store/sort-newest-first.mjs.map +1 -0
- package/llms-full.txt +9 -9
- package/llms.txt +1 -1
- package/package.json +4 -4
- package/skills/use-local-dashboard/SKILL.md +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply-panoptic-config.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/config/apply-panoptic-config.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"apply-panoptic-config.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/config/apply-panoptic-config.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;wBAoDgB,oBAAoB,SAAS"}
|
|
@@ -7,6 +7,8 @@ import { log } from "@warlock.js/logger";
|
|
|
7
7
|
|
|
8
8
|
//#region ../../packages/ai-panoptic/src/config/apply-panoptic-config.ts
|
|
9
9
|
let applied;
|
|
10
|
+
/** Traces kept by the store panoptic creates for the dashboard, unless `capacity` says otherwise. */
|
|
11
|
+
const DEFAULT_DASHBOARD_STORE_CAPACITY = 1e3;
|
|
10
12
|
/**
|
|
11
13
|
* Read a {@link PanopticConfig} and wire panoptic onto the core observe
|
|
12
14
|
* seam — the bridge `ai.config({ panoptic })` resolves through. Builds a
|
|
@@ -35,11 +37,15 @@ function applyPanopticConfig(config) {
|
|
|
35
37
|
let store = findStore(exporters);
|
|
36
38
|
let cacheStore;
|
|
37
39
|
if (store === void 0 && config.dashboard) {
|
|
40
|
+
const capacity = config.capacity ?? 1e3;
|
|
38
41
|
if (config.cache !== void 0) {
|
|
39
42
|
const onError = config.onError ?? ((error) => log.error("ai-panoptic", "cacheStore", error));
|
|
40
|
-
cacheStore = createCacheTraceStore(config.cache, {
|
|
43
|
+
cacheStore = createCacheTraceStore(config.cache, {
|
|
44
|
+
onError,
|
|
45
|
+
capacity
|
|
46
|
+
});
|
|
41
47
|
store = cacheStore;
|
|
42
|
-
} else store = createInMemoryTraceStore();
|
|
48
|
+
} else store = createInMemoryTraceStore({ capacity });
|
|
43
49
|
exporters.push(store);
|
|
44
50
|
}
|
|
45
51
|
const panopticInstance = panoptic({
|
|
@@ -87,5 +93,5 @@ function startDashboard(store, dashboardConfig) {
|
|
|
87
93
|
}
|
|
88
94
|
|
|
89
95
|
//#endregion
|
|
90
|
-
export { applyPanopticConfig };
|
|
96
|
+
export { DEFAULT_DASHBOARD_STORE_CAPACITY, applyPanopticConfig };
|
|
91
97
|
//# sourceMappingURL=apply-panoptic-config.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply-panoptic-config.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/config/apply-panoptic-config.ts"],"sourcesContent":["import type { ExecutionReport, Observer } from \"@warlock.js/ai\";\nimport { registerObserver, setObserveAll } from \"@warlock.js/ai\";\nimport { log } from \"@warlock.js/logger\";\nimport type { ExporterContract } from \"../contracts/exporter.contract\";\nimport { dashboard } from \"../dashboard/dashboard\";\nimport type { DashboardHandle, DashboardOptions } from \"../dashboard/dashboard.type\";\nimport { panoptic } from \"../panoptic/panoptic\";\nimport type { Panoptic } from \"../panoptic/panoptic.type\";\nimport { createCacheTraceStore } from \"../store/cache-trace-store\";\nimport type { CacheTraceStoreHandle } from \"../store/cache-trace-store\";\nimport { createInMemoryTraceStore } from \"../store/in-memory-trace-store\";\nimport type { TraceStoreContract } from \"../store/trace-store.contract\";\nimport type { PanopticConfig } from \"./panoptic-config.type\";\n\n/**\n * Module-level applied state. Applying panoptic config is idempotent:\n * the collector is registered as a core `Observer` exactly once, the\n * dashboard is started at most once, and repeat calls only refresh the\n * `observeAll` flag (the latest config wins) without double-registering.\n */\ntype AppliedState = {\n /** The single collector registered as a core `Observer`. */\n panopticInstance: Panoptic;\n /** The dashboard handle, once started. Started at most once. */\n dashboardHandle?: DashboardHandle;\n};\n\nlet applied: AppliedState | undefined;\n\n/**\n * Read a {@link PanopticConfig} and wire panoptic onto the core observe\n * seam — the bridge `ai.config({ panoptic })` resolves through. Builds a\n * collector via the EXISTING {@link panoptic} factory (reusing its\n * collection pipeline, not reinventing it), registers it once via core's\n * `registerObserver` (the subscriber's `collect(report)` structurally IS\n * an {@link Observer}, threaded through a thin wrapper), sets\n * `observeAll`, and — when `config.dashboard` is set — starts the\n * dashboard over the config's store (a store-shaped exporter, or a fresh\n * in-memory store panoptic registers when none was supplied).\n *\n * **Idempotent.** Safe to call on every `onConfigApplied` notification:\n * the observer is registered once, the dashboard started once. Repeat\n * calls update `observeAll` to the latest value but never double-register\n * or double-start. `undefined` config is a no-op (nothing wired).\n *\n * @returns the resolved store-shaped exporter when the dashboard needs\n * one and a fresh store was created — primarily for tests; callers can\n * ignore it.\n */\nexport function applyPanopticConfig(config?: PanopticConfig): void {\n if (config === undefined) {\n return;\n }\n\n // observeAll always tracks the latest config, even on a repeat call.\n setObserveAll(Boolean(config.observeAll));\n\n if (applied === undefined) {\n const exporters = [...(config.exporters ?? [])];\n let store = findStore(exporters);\n\n // Track a cache store separately so we can await its hydration before\n // the dashboard reads it — the in-memory store needs no warm-up.\n let cacheStore: CacheTraceStoreHandle | undefined;\n\n // The dashboard needs a queryable store. If none was supplied via\n // exporters but a dashboard is requested, create one and register it\n // as an exporter so the collector fills it. A configured `cache` picks\n // the durable cache-backed store; otherwise fall back to in-memory so\n // the dashboard works with no cache configured.\n if (store === undefined && config.dashboard) {\n if (config.cache !== undefined) {\n const onError =\n config.onError ?? ((error: unknown) => log.error(\"ai-panoptic\", \"cacheStore\", error));\n\n cacheStore = createCacheTraceStore(config.cache, { onError });\n store = cacheStore;\n } else {\n store = createInMemoryTraceStore();\n }\n\n exporters.push(store as unknown as ExporterContract);\n }\n\n const panopticInstance = panoptic({\n exporters,\n captureContent: config.captureContent,\n fullHistory: config.fullHistory,\n });\n registerObserver(toObserver(panopticInstance));\n\n applied = { panopticInstance };\n\n if (config.dashboard && store !== undefined) {\n const resolvedStore = store;\n\n // Hydrate the cache mirror (if any) before serving, so a restart\n // surfaces previously-persisted traces immediately. A bare in-memory\n // store resolves the readyGate instantly.\n const readyGate = cacheStore !== undefined ? cacheStore.ready() : Promise.resolve();\n\n void readyGate\n .catch(() => {\n // Hydration is best-effort — never block the dashboard on it.\n })\n .then(() => startDashboard(resolvedStore, config.dashboard ?? {}))\n .then((handle) => {\n if (applied !== undefined) {\n applied.dashboardHandle = handle;\n }\n });\n }\n }\n}\n\n/**\n * Reset the applied state — internal, test-only. Closes any running\n * dashboard and forgets the registered collector so a fresh\n * `applyPanopticConfig` starts clean. NOT part of the public surface and\n * does NOT unregister from the core observer registry (use core's\n * `clearObservers` for that in tests).\n */\nexport async function resetAppliedPanopticConfig(): Promise<void> {\n const handle = applied?.dashboardHandle;\n applied = undefined;\n\n if (handle !== undefined) {\n await handle.close();\n }\n}\n\n/**\n * The currently-running dashboard handle, or `undefined` when no\n * dashboard is active. Internal, test-only — lets a spec await the\n * asynchronously-started dashboard. NOT part of the public surface.\n */\nexport function getActiveDashboardHandle(): DashboardHandle | undefined {\n return applied?.dashboardHandle;\n}\n\n/**\n * Wrap a {@link Panoptic} subscriber as a core {@link Observer}. The\n * subscriber already exposes `collect(report)` with a matching signature,\n * but the thin wrapper makes the structural adaptation explicit and keeps\n * the registered object a minimal `Observer` rather than the whole\n * subscriber surface.\n */\nfunction toObserver(instance: Panoptic): Observer {\n return {\n collect(report: ExecutionReport): Promise<void> {\n return instance.collect(report);\n },\n };\n}\n\n/**\n * Find the first exporter that satisfies the {@link TraceStoreContract}\n * read surface (`query` / `get` / `aggregate`) — the in-memory store\n * doubles as an exporter, so a store passed via `exporters` is reused for\n * the dashboard rather than creating a second one.\n */\nfunction findStore(exporters: ExporterContract[]): TraceStoreContract | undefined {\n for (const exporter of exporters) {\n const candidate = exporter as unknown as Partial<TraceStoreContract>;\n\n if (\n typeof candidate.query === \"function\" &&\n typeof candidate.get === \"function\" &&\n typeof candidate.aggregate === \"function\"\n ) {\n return candidate as TraceStoreContract;\n }\n }\n\n return undefined;\n}\n\n/** Start the dashboard, normalizing the `true | DashboardOptions` switch. */\nfunction startDashboard(\n store: TraceStoreContract,\n dashboardConfig: boolean | DashboardOptions,\n): Promise<DashboardHandle> {\n const options: DashboardOptions = typeof dashboardConfig === \"object\" ? dashboardConfig : {};\n\n return dashboard(store, options);\n}\n"],"mappings":";;;;;;;;AA2BA,IAAI;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"apply-panoptic-config.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/config/apply-panoptic-config.ts"],"sourcesContent":["import type { ExecutionReport, Observer } from \"@warlock.js/ai\";\nimport { registerObserver, setObserveAll } from \"@warlock.js/ai\";\nimport { log } from \"@warlock.js/logger\";\nimport type { ExporterContract } from \"../contracts/exporter.contract\";\nimport { dashboard } from \"../dashboard/dashboard\";\nimport type { DashboardHandle, DashboardOptions } from \"../dashboard/dashboard.type\";\nimport { panoptic } from \"../panoptic/panoptic\";\nimport type { Panoptic } from \"../panoptic/panoptic.type\";\nimport { createCacheTraceStore } from \"../store/cache-trace-store\";\nimport type { CacheTraceStoreHandle } from \"../store/cache-trace-store\";\nimport { createInMemoryTraceStore } from \"../store/in-memory-trace-store\";\nimport type { TraceStoreContract } from \"../store/trace-store.contract\";\nimport type { PanopticConfig } from \"./panoptic-config.type\";\n\n/**\n * Module-level applied state. Applying panoptic config is idempotent:\n * the collector is registered as a core `Observer` exactly once, the\n * dashboard is started at most once, and repeat calls only refresh the\n * `observeAll` flag (the latest config wins) without double-registering.\n */\ntype AppliedState = {\n /** The single collector registered as a core `Observer`. */\n panopticInstance: Panoptic;\n /** The dashboard handle, once started. Started at most once. */\n dashboardHandle?: DashboardHandle;\n};\n\nlet applied: AppliedState | undefined;\n\n/** Traces kept by the store panoptic creates for the dashboard, unless `capacity` says otherwise. */\nexport const DEFAULT_DASHBOARD_STORE_CAPACITY = 1000;\n\n/**\n * Read a {@link PanopticConfig} and wire panoptic onto the core observe\n * seam — the bridge `ai.config({ panoptic })` resolves through. Builds a\n * collector via the EXISTING {@link panoptic} factory (reusing its\n * collection pipeline, not reinventing it), registers it once via core's\n * `registerObserver` (the subscriber's `collect(report)` structurally IS\n * an {@link Observer}, threaded through a thin wrapper), sets\n * `observeAll`, and — when `config.dashboard` is set — starts the\n * dashboard over the config's store (a store-shaped exporter, or a fresh\n * in-memory store panoptic registers when none was supplied).\n *\n * **Idempotent.** Safe to call on every `onConfigApplied` notification:\n * the observer is registered once, the dashboard started once. Repeat\n * calls update `observeAll` to the latest value but never double-register\n * or double-start. `undefined` config is a no-op (nothing wired).\n *\n * @returns the resolved store-shaped exporter when the dashboard needs\n * one and a fresh store was created — primarily for tests; callers can\n * ignore it.\n */\nexport function applyPanopticConfig(config?: PanopticConfig): void {\n if (config === undefined) {\n return;\n }\n\n // observeAll always tracks the latest config, even on a repeat call.\n setObserveAll(Boolean(config.observeAll));\n\n if (applied === undefined) {\n const exporters = [...(config.exporters ?? [])];\n let store = findStore(exporters);\n\n // Track a cache store separately so we can await its hydration before\n // the dashboard reads it — the in-memory store needs no warm-up.\n let cacheStore: CacheTraceStoreHandle | undefined;\n\n // The dashboard needs a queryable store. If none was supplied via\n // exporters but a dashboard is requested, create one and register it\n // as an exporter so the collector fills it. A configured `cache` picks\n // the durable cache-backed store; otherwise fall back to in-memory so\n // the dashboard works with no cache configured.\n if (store === undefined && config.dashboard) {\n const capacity = config.capacity ?? DEFAULT_DASHBOARD_STORE_CAPACITY;\n\n if (config.cache !== undefined) {\n const onError =\n config.onError ?? ((error: unknown) => log.error(\"ai-panoptic\", \"cacheStore\", error));\n\n cacheStore = createCacheTraceStore(config.cache, { onError, capacity });\n store = cacheStore;\n } else {\n store = createInMemoryTraceStore({ capacity });\n }\n\n exporters.push(store as unknown as ExporterContract);\n }\n\n const panopticInstance = panoptic({\n exporters,\n captureContent: config.captureContent,\n fullHistory: config.fullHistory,\n });\n registerObserver(toObserver(panopticInstance));\n\n applied = { panopticInstance };\n\n if (config.dashboard && store !== undefined) {\n const resolvedStore = store;\n\n // Hydrate the cache mirror (if any) before serving, so a restart\n // surfaces previously-persisted traces immediately. A bare in-memory\n // store resolves the readyGate instantly.\n const readyGate = cacheStore !== undefined ? cacheStore.ready() : Promise.resolve();\n\n void readyGate\n .catch(() => {\n // Hydration is best-effort — never block the dashboard on it.\n })\n .then(() => startDashboard(resolvedStore, config.dashboard ?? {}))\n .then((handle) => {\n if (applied !== undefined) {\n applied.dashboardHandle = handle;\n }\n });\n }\n }\n}\n\n/**\n * Reset the applied state — internal, test-only. Closes any running\n * dashboard and forgets the registered collector so a fresh\n * `applyPanopticConfig` starts clean. NOT part of the public surface and\n * does NOT unregister from the core observer registry (use core's\n * `clearObservers` for that in tests).\n */\nexport async function resetAppliedPanopticConfig(): Promise<void> {\n const handle = applied?.dashboardHandle;\n applied = undefined;\n\n if (handle !== undefined) {\n await handle.close();\n }\n}\n\n/**\n * The currently-running dashboard handle, or `undefined` when no\n * dashboard is active. Internal, test-only — lets a spec await the\n * asynchronously-started dashboard. NOT part of the public surface.\n */\nexport function getActiveDashboardHandle(): DashboardHandle | undefined {\n return applied?.dashboardHandle;\n}\n\n/**\n * Wrap a {@link Panoptic} subscriber as a core {@link Observer}. The\n * subscriber already exposes `collect(report)` with a matching signature,\n * but the thin wrapper makes the structural adaptation explicit and keeps\n * the registered object a minimal `Observer` rather than the whole\n * subscriber surface.\n */\nfunction toObserver(instance: Panoptic): Observer {\n return {\n collect(report: ExecutionReport): Promise<void> {\n return instance.collect(report);\n },\n };\n}\n\n/**\n * Find the first exporter that satisfies the {@link TraceStoreContract}\n * read surface (`query` / `get` / `aggregate`) — the in-memory store\n * doubles as an exporter, so a store passed via `exporters` is reused for\n * the dashboard rather than creating a second one.\n */\nfunction findStore(exporters: ExporterContract[]): TraceStoreContract | undefined {\n for (const exporter of exporters) {\n const candidate = exporter as unknown as Partial<TraceStoreContract>;\n\n if (\n typeof candidate.query === \"function\" &&\n typeof candidate.get === \"function\" &&\n typeof candidate.aggregate === \"function\"\n ) {\n return candidate as TraceStoreContract;\n }\n }\n\n return undefined;\n}\n\n/** Start the dashboard, normalizing the `true | DashboardOptions` switch. */\nfunction startDashboard(\n store: TraceStoreContract,\n dashboardConfig: boolean | DashboardOptions,\n): Promise<DashboardHandle> {\n const options: DashboardOptions = typeof dashboardConfig === \"object\" ? dashboardConfig : {};\n\n return dashboard(store, options);\n}\n"],"mappings":";;;;;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OAAO,UAAU,UAAU,cAC3B,OAAO,UAAU,QAAQ,cACzB,OAAO,UAAU,cAAc,YAE/B,OAAO;CAEX;AAGF;;AAGA,SAAS,eACP,OACA,iBAC0B;CAG1B,OAAO,UAAU,OAFiB,OAAO,oBAAoB,WAAW,kBAAkB,CAAC,CAE5D;AACjC"}
|
|
@@ -53,6 +53,13 @@ export type PanopticConfig = {
|
|
|
53
53
|
* and registers when none was supplied.
|
|
54
54
|
*/
|
|
55
55
|
dashboard?: boolean | DashboardOptions;
|
|
56
|
+
/**
|
|
57
|
+
* How many traces the store panoptic creates for the dashboard keeps (the
|
|
58
|
+
* in-memory store, or the cache-backed one when {@link cache} is set).
|
|
59
|
+
* Past it the oldest trace is dropped. Default `1000`; `0` keeps every
|
|
60
|
+
* trace. Ignored when you supply your own store through `exporters`.
|
|
61
|
+
*/
|
|
62
|
+
capacity?: number;
|
|
56
63
|
/**
|
|
57
64
|
* Observe every flow (`ai.agent` / `ai.workflow` / `ai.supervisor` /
|
|
58
65
|
* `ai.team`) by default. Individual flows opt out with `observe: false`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"panoptic-config.type.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/config/panoptic-config.type.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;YA0BY;;;;;;;EAOV,YAAY;;;;;;;;;;;;;EAaZ,QAAQ;;;;;;;;EAQR,sBAAsB;;;;;;
|
|
1
|
+
{"version":3,"file":"panoptic-config.type.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/config/panoptic-config.type.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;YA0BY;;;;;;;EAOV,YAAY;;;;;;;;;;;;;EAaZ,QAAQ;;;;;;;;EAQR,sBAAsB;;;;;;;EAOtB;;;;;;EAMA;;;;;;EAMA;;;;;;EAMA;;;;;;;;;;;EAWA,WAAW;;;YAQD;;IAER,WAAW"}
|
|
@@ -3,4 +3,5 @@ import { dashboard } from "./dashboard.mjs";
|
|
|
3
3
|
import "./serve.mjs";
|
|
4
4
|
import "./parse-query.mjs";
|
|
5
5
|
import { NO_PROMPT_KEY, NO_SESSION_KEY, NO_TYPE_KEY, PromptGroup, SessionGroup, TraceFilter, TypeGroup, TypeStat, aggregateByType, filterTraces, groupByPrompt, groupBySession, groupByType, heatIntensity, matchesFilter, maxNodeCost, percentile, rollupCost, traceCost, tracePromptKey } from "./trace-filter.mjs";
|
|
6
|
+
import { TraceSpanSummary, TraceSummary } from "./trace-summary.mjs";
|
|
6
7
|
export { type DashboardHandle, type DashboardOptions, dashboard };
|
package/esm/dashboard/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { parseQuery } from "./parse-query.mjs";
|
|
2
|
+
import { NO_PROMPT_KEY, NO_SESSION_KEY, NO_TYPE_KEY, aggregateByType, filterTraces, groupByPrompt, groupBySession, groupByType, heatIntensity, matchesFilter, maxNodeCost, percentile, rollupCost, traceCost, tracePromptKey } from "./trace-filter.mjs";
|
|
2
3
|
import { dashboardHtml } from "./ui.html.mjs";
|
|
3
4
|
import { createRequestHandler } from "./serve.mjs";
|
|
4
5
|
import { dashboard } from "./dashboard.mjs";
|
|
5
|
-
import { NO_PROMPT_KEY, NO_SESSION_KEY, NO_TYPE_KEY, aggregateByType, filterTraces, groupByPrompt, groupBySession, groupByType, heatIntensity, matchesFilter, maxNodeCost, percentile, rollupCost, traceCost, tracePromptKey } from "./trace-filter.mjs";
|
|
6
6
|
|
|
7
7
|
export { dashboard };
|
|
@@ -49,7 +49,29 @@ function parseQuery(params) {
|
|
|
49
49
|
if (startedBefore !== null && startedBefore.length > 0) query.startedBefore = startedBefore;
|
|
50
50
|
return query;
|
|
51
51
|
}
|
|
52
|
+
/** Traces `GET api/traces` returns when the request names no `limit`. */
|
|
53
|
+
const DEFAULT_TRACE_LIST_LIMIT = 200;
|
|
54
|
+
/**
|
|
55
|
+
* Read `?limit=` (a positive integer, default {@link DEFAULT_TRACE_LIST_LIMIT})
|
|
56
|
+
* and `?full=1` from a `GET api/traces` request. An invalid `limit` falls
|
|
57
|
+
* back to the default. Page further back with `?startedBefore=` set to the
|
|
58
|
+
* `startedAt` of the last trace received.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* parseListOptions(new URLSearchParams("limit=50&full=1"));
|
|
62
|
+
* // → { limit: 50, full: true }
|
|
63
|
+
*/
|
|
64
|
+
function parseListOptions(params) {
|
|
65
|
+
const raw = params.get("limit");
|
|
66
|
+
const parsed = raw === null ? NaN : Number(raw);
|
|
67
|
+
const limit = Number.isInteger(parsed) && parsed > 0 ? parsed : 200;
|
|
68
|
+
const full = params.get("full");
|
|
69
|
+
return {
|
|
70
|
+
limit,
|
|
71
|
+
full: full === "1" || full === "true"
|
|
72
|
+
};
|
|
73
|
+
}
|
|
52
74
|
|
|
53
75
|
//#endregion
|
|
54
|
-
export { parseQuery };
|
|
76
|
+
export { parseListOptions, parseQuery };
|
|
55
77
|
//# sourceMappingURL=parse-query.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-query.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/parse-query.ts"],"sourcesContent":["import type { ReportStatus } from \"@warlock.js/ai\";\nimport type { TraceQuery } from \"../store/trace-query.type\";\n\n/**\n * The set of terminal statuses a stored trace can carry. Used to keep\n * `parseQuery` from forwarding arbitrary `?status=` junk into the store.\n */\nconst KNOWN_STATUSES: readonly ReportStatus[] = [\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"incomplete\",\n \"max-iterations\",\n \"awaiting-input\",\n \"awaiting-approval\",\n] as const;\n\n/**\n * Map a request's query string onto a {@link TraceQuery} the trace store\n * understands. Every field is optional — an absent param is \"don't care\",\n * so an empty query string yields an empty filter that matches every\n * stored trace.\n *\n * - `traceId` / `sessionId` — passed through verbatim (first value wins).\n * - `status` — **repeatable**: `?status=failed&status=cancelled` becomes\n * `[\"failed\", \"cancelled\"]`; a single value stays a scalar. Unknown\n * status tokens are dropped so a typo never silently matches nothing in\n * a confusing way (it simply isn't filtered on).\n * - `startedAfter` / `startedBefore` — forwarded as ISO strings; the\n * store accepts either a string or `Date`, and `matchTrace` does the\n * inclusive bound comparison.\n *\n * Unknown params are ignored. Pure — takes a `URLSearchParams`, returns a\n * plain object — so it's trivially testable without a live server.\n *\n * @example\n * parseQuery(new URLSearchParams(\"status=failed&status=cancelled&sessionId=s1\"));\n * // → { status: [\"failed\", \"cancelled\"], sessionId: \"s1\" }\n */\nexport function parseQuery(params: URLSearchParams): TraceQuery {\n const query: TraceQuery = {};\n\n const traceId = params.get(\"traceId\");\n if (traceId !== null && traceId.length > 0) {\n query.traceId = traceId;\n }\n\n const sessionId = params.get(\"sessionId\");\n if (sessionId !== null && sessionId.length > 0) {\n query.sessionId = sessionId;\n }\n\n const statuses = params\n .getAll(\"status\")\n .filter((value): value is ReportStatus =>\n (KNOWN_STATUSES as readonly string[]).includes(value),\n );\n if (statuses.length === 1) {\n query.status = statuses[0];\n } else if (statuses.length > 1) {\n query.status = statuses;\n }\n\n const startedAfter = params.get(\"startedAfter\");\n if (startedAfter !== null && startedAfter.length > 0) {\n query.startedAfter = startedAfter;\n }\n\n const startedBefore = params.get(\"startedBefore\");\n if (startedBefore !== null && startedBefore.length > 0) {\n query.startedBefore = startedBefore;\n }\n\n return query;\n}\n"],"mappings":";;;;;AAOA,MAAM,iBAA0C;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,WAAW,QAAqC;CAC9D,MAAM,QAAoB,CAAC;CAE3B,MAAM,UAAU,OAAO,IAAI,SAAS;CACpC,IAAI,YAAY,QAAQ,QAAQ,SAAS,GACvC,MAAM,UAAU;CAGlB,MAAM,YAAY,OAAO,IAAI,WAAW;CACxC,IAAI,cAAc,QAAQ,UAAU,SAAS,GAC3C,MAAM,YAAY;CAGpB,MAAM,WAAW,OACd,OAAO,QAAQ,CAAC,CAChB,QAAQ,UACN,eAAqC,SAAS,KAAK,CACtD;CACF,IAAI,SAAS,WAAW,GACtB,MAAM,SAAS,SAAS;MACnB,IAAI,SAAS,SAAS,GAC3B,MAAM,SAAS;CAGjB,MAAM,eAAe,OAAO,IAAI,cAAc;CAC9C,IAAI,iBAAiB,QAAQ,aAAa,SAAS,GACjD,MAAM,eAAe;CAGvB,MAAM,gBAAgB,OAAO,IAAI,eAAe;CAChD,IAAI,kBAAkB,QAAQ,cAAc,SAAS,GACnD,MAAM,gBAAgB;CAGxB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"parse-query.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/parse-query.ts"],"sourcesContent":["import type { ReportStatus } from \"@warlock.js/ai\";\nimport type { TraceQuery } from \"../store/trace-query.type\";\n\n/**\n * The set of terminal statuses a stored trace can carry. Used to keep\n * `parseQuery` from forwarding arbitrary `?status=` junk into the store.\n */\nconst KNOWN_STATUSES: readonly ReportStatus[] = [\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"incomplete\",\n \"max-iterations\",\n \"awaiting-input\",\n \"awaiting-approval\",\n] as const;\n\n/**\n * Map a request's query string onto a {@link TraceQuery} the trace store\n * understands. Every field is optional — an absent param is \"don't care\",\n * so an empty query string yields an empty filter that matches every\n * stored trace.\n *\n * - `traceId` / `sessionId` — passed through verbatim (first value wins).\n * - `status` — **repeatable**: `?status=failed&status=cancelled` becomes\n * `[\"failed\", \"cancelled\"]`; a single value stays a scalar. Unknown\n * status tokens are dropped so a typo never silently matches nothing in\n * a confusing way (it simply isn't filtered on).\n * - `startedAfter` / `startedBefore` — forwarded as ISO strings; the\n * store accepts either a string or `Date`, and `matchTrace` does the\n * inclusive bound comparison.\n *\n * Unknown params are ignored. Pure — takes a `URLSearchParams`, returns a\n * plain object — so it's trivially testable without a live server.\n *\n * @example\n * parseQuery(new URLSearchParams(\"status=failed&status=cancelled&sessionId=s1\"));\n * // → { status: [\"failed\", \"cancelled\"], sessionId: \"s1\" }\n */\nexport function parseQuery(params: URLSearchParams): TraceQuery {\n const query: TraceQuery = {};\n\n const traceId = params.get(\"traceId\");\n if (traceId !== null && traceId.length > 0) {\n query.traceId = traceId;\n }\n\n const sessionId = params.get(\"sessionId\");\n if (sessionId !== null && sessionId.length > 0) {\n query.sessionId = sessionId;\n }\n\n const statuses = params\n .getAll(\"status\")\n .filter((value): value is ReportStatus =>\n (KNOWN_STATUSES as readonly string[]).includes(value),\n );\n if (statuses.length === 1) {\n query.status = statuses[0];\n } else if (statuses.length > 1) {\n query.status = statuses;\n }\n\n const startedAfter = params.get(\"startedAfter\");\n if (startedAfter !== null && startedAfter.length > 0) {\n query.startedAfter = startedAfter;\n }\n\n const startedBefore = params.get(\"startedBefore\");\n if (startedBefore !== null && startedBefore.length > 0) {\n query.startedBefore = startedBefore;\n }\n\n return query;\n}\n\n/** Traces `GET api/traces` returns when the request names no `limit`. */\nexport const DEFAULT_TRACE_LIST_LIMIT = 200;\n\n/** Paging and shape options of `GET api/traces`. */\nexport type TraceListOptions = {\n /** Newest traces to return. */\n limit: number;\n /** Return full traces (span tree and captured content) instead of summaries. */\n full: boolean;\n};\n\n/**\n * Read `?limit=` (a positive integer, default {@link DEFAULT_TRACE_LIST_LIMIT})\n * and `?full=1` from a `GET api/traces` request. An invalid `limit` falls\n * back to the default. Page further back with `?startedBefore=` set to the\n * `startedAt` of the last trace received.\n *\n * @example\n * parseListOptions(new URLSearchParams(\"limit=50&full=1\"));\n * // → { limit: 50, full: true }\n */\nexport function parseListOptions(params: URLSearchParams): TraceListOptions {\n const raw = params.get(\"limit\");\n const parsed = raw === null ? Number.NaN : Number(raw);\n const limit = Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_TRACE_LIST_LIMIT;\n const full = params.get(\"full\");\n\n return { limit, full: full === \"1\" || full === \"true\" };\n}\n"],"mappings":";;;;;AAOA,MAAM,iBAA0C;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,WAAW,QAAqC;CAC9D,MAAM,QAAoB,CAAC;CAE3B,MAAM,UAAU,OAAO,IAAI,SAAS;CACpC,IAAI,YAAY,QAAQ,QAAQ,SAAS,GACvC,MAAM,UAAU;CAGlB,MAAM,YAAY,OAAO,IAAI,WAAW;CACxC,IAAI,cAAc,QAAQ,UAAU,SAAS,GAC3C,MAAM,YAAY;CAGpB,MAAM,WAAW,OACd,OAAO,QAAQ,CAAC,CAChB,QAAQ,UACN,eAAqC,SAAS,KAAK,CACtD;CACF,IAAI,SAAS,WAAW,GACtB,MAAM,SAAS,SAAS;MACnB,IAAI,SAAS,SAAS,GAC3B,MAAM,SAAS;CAGjB,MAAM,eAAe,OAAO,IAAI,cAAc;CAC9C,IAAI,iBAAiB,QAAQ,aAAa,SAAS,GACjD,MAAM,eAAe;CAGvB,MAAM,gBAAgB,OAAO,IAAI,eAAe;CAChD,IAAI,kBAAkB,QAAQ,cAAc,SAAS,GACnD,MAAM,gBAAgB;CAGxB,OAAO;AACT;;AAGA,MAAa,2BAA2B;;;;;;;;;;;AAoBxC,SAAgB,iBAAiB,QAA2C;CAC1E,MAAM,MAAM,OAAO,IAAI,OAAO;CAC9B,MAAM,SAAS,QAAQ,OAAO,MAAa,OAAO,GAAG;CACrD,MAAM,QAAQ,OAAO,UAAU,MAAM,KAAK,SAAS,IAAI;CACvD,MAAM,OAAO,OAAO,IAAI,MAAM;CAE9B,OAAO;EAAE;EAAO,MAAM,SAAS,OAAO,SAAS;CAAO;AACxD"}
|
package/esm/dashboard/serve.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { evaluateSystemPrompt } from "../evaluate/evaluate-system-prompt.mjs";
|
|
2
2
|
import { extractLastSystemPrompt } from "../evaluate/extract-last-system-prompt.mjs";
|
|
3
3
|
import { findSpanById } from "../evaluate/find-span-by-id.mjs";
|
|
4
|
-
import { parseQuery } from "./parse-query.mjs";
|
|
4
|
+
import { parseListOptions, parseQuery } from "./parse-query.mjs";
|
|
5
|
+
import { toTraceSummary } from "./trace-summary.mjs";
|
|
5
6
|
import { dashboardHtml } from "./ui.html.mjs";
|
|
6
7
|
import { timingSafeEqual } from "node:crypto";
|
|
7
8
|
|
|
@@ -69,8 +70,10 @@ function isAuthorized(req, url, token, allowQueryToken) {
|
|
|
69
70
|
*
|
|
70
71
|
* Routes (all under `config.basePath`):
|
|
71
72
|
*
|
|
72
|
-
* - `GET api/traces` →
|
|
73
|
-
*
|
|
73
|
+
* - `GET api/traces` → the newest `?limit=` (default 200) matches of
|
|
74
|
+
* `store.query(parseQuery(searchParams))`, as {@link TraceSummary}
|
|
75
|
+
* entries (no span tree or captured content); `?full=1` returns full traces
|
|
76
|
+
* - `GET api/traces/:id` → `store.get(id)` or `404` (`400` for a malformed id)
|
|
74
77
|
* - `GET api/aggregate` → `store.aggregate(parseQuery(searchParams))`
|
|
75
78
|
* - `GET {basePath}` → the self-contained HTML page
|
|
76
79
|
* - `POST api/traces/:traceId/spans/:spanId/evaluate` → ONLY when
|
|
@@ -80,6 +83,8 @@ function isAuthorized(req, url, token, allowQueryToken) {
|
|
|
80
83
|
* other route (the path is never even pattern-matched).
|
|
81
84
|
*
|
|
82
85
|
* Anything else → `404`. A method the matched route doesn't accept → `405`.
|
|
86
|
+
* A handler failure answers `500` instead of escaping the server's
|
|
87
|
+
* `request` listener, so one bad request can never take the app down.
|
|
83
88
|
* Host allowlist + bearer-token auth (S4) are checked for EVERY request,
|
|
84
89
|
* regardless of method, before any routing. The store shapes
|
|
85
90
|
* ({@link Trace}/{@link TraceSpan}) are already JSON-safe, so GET responses
|
|
@@ -93,6 +98,13 @@ function createRequestHandler(store, config) {
|
|
|
93
98
|
const base = config.basePath;
|
|
94
99
|
const apiPrefix = `${base}api`;
|
|
95
100
|
return function handle(req, res) {
|
|
101
|
+
try {
|
|
102
|
+
route(req, res);
|
|
103
|
+
} catch {
|
|
104
|
+
sendInternalError(res);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
function route(req, res) {
|
|
96
108
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
97
109
|
const pathname = url.pathname;
|
|
98
110
|
const host = hostHeaderName(req.headers.host);
|
|
@@ -107,8 +119,12 @@ function createRequestHandler(store, config) {
|
|
|
107
119
|
}
|
|
108
120
|
if (req.method === "POST" && config.evaluate) {
|
|
109
121
|
const match = matchEvaluatePath(pathname, apiPrefix);
|
|
122
|
+
if (match === "malformed") {
|
|
123
|
+
sendJson(res, 400, { error: "bad_trace_id" });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
110
126
|
if (match) {
|
|
111
|
-
handleEvaluate(store, config.evaluate, match.traceId, match.spanId, req, res);
|
|
127
|
+
handleEvaluate(store, config.evaluate, match.traceId, match.spanId, req, res).catch(() => sendInternalError(res));
|
|
112
128
|
return;
|
|
113
129
|
}
|
|
114
130
|
}
|
|
@@ -117,11 +133,17 @@ function createRequestHandler(store, config) {
|
|
|
117
133
|
return;
|
|
118
134
|
}
|
|
119
135
|
if (pathname === `${apiPrefix}/traces`) {
|
|
120
|
-
|
|
136
|
+
const { limit, full } = parseListOptions(url.searchParams);
|
|
137
|
+
const traces = store.query(parseQuery(url.searchParams)).slice(0, limit);
|
|
138
|
+
sendJson(res, 200, full ? traces : traces.map(toTraceSummary));
|
|
121
139
|
return;
|
|
122
140
|
}
|
|
123
141
|
if (pathname.startsWith(`${apiPrefix}/traces/`)) {
|
|
124
|
-
const traceId =
|
|
142
|
+
const traceId = safeDecode(pathname.slice(`${apiPrefix}/traces/`.length));
|
|
143
|
+
if (traceId === void 0) {
|
|
144
|
+
sendJson(res, 400, { error: "bad_trace_id" });
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
125
147
|
const trace = traceId.length > 0 ? store.get(traceId) : void 0;
|
|
126
148
|
if (trace === void 0) {
|
|
127
149
|
sendJson(res, 404, {
|
|
@@ -146,7 +168,26 @@ function createRequestHandler(store, config) {
|
|
|
146
168
|
return;
|
|
147
169
|
}
|
|
148
170
|
sendJson(res, 404, { error: "not_found" });
|
|
149
|
-
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* `decodeURIComponent` that answers `undefined` for a malformed escape
|
|
175
|
+
* (`%E0%A4%A`) instead of throwing a `URIError`.
|
|
176
|
+
*/
|
|
177
|
+
function safeDecode(value) {
|
|
178
|
+
try {
|
|
179
|
+
return decodeURIComponent(value);
|
|
180
|
+
} catch {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/** Answer `500` unless a response is already on its way. */
|
|
185
|
+
function sendInternalError(res) {
|
|
186
|
+
if (res.headersSent) {
|
|
187
|
+
res.end();
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
sendJson(res, 500, { error: "internal" });
|
|
150
191
|
}
|
|
151
192
|
/** Write a JSON response with the given status code and security headers. */
|
|
152
193
|
function sendJson(res, status, body) {
|
|
@@ -160,16 +201,20 @@ function sendJson(res, status, body) {
|
|
|
160
201
|
* Match `{apiPrefix}/traces/:traceId/spans/:spanId/evaluate` — the one
|
|
161
202
|
* write route. Returns `undefined` for anything else, including the plain
|
|
162
203
|
* `{apiPrefix}/traces/:id` read route (no `/spans/.../evaluate` suffix),
|
|
163
|
-
* so the two never collide.
|
|
204
|
+
* so the two never collide. `"malformed"` when an id is not valid
|
|
205
|
+
* percent-encoding.
|
|
164
206
|
*/
|
|
165
207
|
function matchEvaluatePath(pathname, apiPrefix) {
|
|
166
208
|
const prefix = `${apiPrefix}/traces/`;
|
|
167
209
|
if (!pathname.startsWith(prefix)) return;
|
|
168
210
|
const match = /^([^/]+)\/spans\/([^/]+)\/evaluate$/.exec(pathname.slice(prefix.length));
|
|
169
211
|
if (!match) return;
|
|
212
|
+
const traceId = safeDecode(match[1] ?? "");
|
|
213
|
+
const spanId = safeDecode(match[2] ?? "");
|
|
214
|
+
if (traceId === void 0 || spanId === void 0) return "malformed";
|
|
170
215
|
return {
|
|
171
|
-
traceId
|
|
172
|
-
spanId
|
|
216
|
+
traceId,
|
|
217
|
+
spanId
|
|
173
218
|
};
|
|
174
219
|
}
|
|
175
220
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/serve.ts"],"sourcesContent":["import { timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { EvaluateConfig } from \"../evaluate/evaluate.type\";\nimport { evaluateSystemPrompt } from \"../evaluate/evaluate-system-prompt\";\nimport { extractLastSystemPrompt } from \"../evaluate/extract-last-system-prompt\";\nimport { findSpanById } from \"../evaluate/find-span-by-id\";\nimport type { TraceStoreContract } from \"../store/trace-store.contract\";\nimport { parseQuery } from \"./parse-query\";\nimport { dashboardHtml } from \"./ui.html\";\n\n/** Fully-resolved routing config the request handler closes over. */\nexport type ServeConfig = {\n /** Normalized mount path, always ending in `/` (e.g. `\"/\"`). */\n basePath: string;\n /** Header title baked into the served page. */\n title: string;\n /** Bearer token required on every request when set (S4). */\n authToken?: string;\n /** `Host` header allowlist — defends against DNS-rebinding (S4). */\n allowedHosts: string[];\n /**\n * Enables the one write route: `POST\n * {basePath}api/traces/:traceId/spans/:spanId/evaluate`. Absent ⇒ the\n * route 405s (POST isn't accepted by any route) and the served page never\n * renders the Evaluate button.\n */\n evaluate?: EvaluateConfig;\n};\n\n/** Request body accepted by the evaluate route — everything optional. */\ntype EvaluateRequestBody = {\n /** Per-run instructions override; falls back to `config.evaluate.instructions`. */\n instructions?: string;\n};\n\n/** Hard cap on the evaluate route's request body — well beyond a real instructions string. */\nconst MAX_EVALUATE_BODY_BYTES = 64 * 1024;\n\n/**\n * Security response headers added to every dashboard response (S4):\n * block MIME-sniffing, framing, referrer leakage, and lock the page's\n * content sources down to itself (the UI is fully self-contained — no CDN).\n */\nconst SECURITY_HEADERS: Record<string, string> = {\n \"x-content-type-options\": \"nosniff\",\n \"x-frame-options\": \"DENY\",\n \"referrer-policy\": \"no-referrer\",\n \"content-security-policy\":\n \"default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'\",\n};\n\n/** Extract the host (no port) from a `Host` header value. */\nfunction hostHeaderName(hostHeader: string | undefined): string | undefined {\n if (!hostHeader) return undefined;\n // IPv6 literal `[::1]:4319` → `[::1]`; otherwise strip `:port`.\n if (hostHeader.startsWith(\"[\")) {\n return hostHeader.slice(0, hostHeader.indexOf(\"]\") + 1);\n }\n const colon = hostHeader.indexOf(\":\");\n return colon === -1 ? hostHeader : hostHeader.slice(0, colon);\n}\n\n/**\n * Constant-time string equality (S4) — guards against a timing\n * side-channel that could otherwise let a network-adjacent attacker\n * recover the token byte-by-byte via repeated timed guesses. Plain `===`\n * short-circuits on the first differing byte, so response latency leaks\n * how many leading bytes matched; `timingSafeEqual` does not. Lengths are\n * compared first (a length mismatch is not secret and `timingSafeEqual`\n * requires equal-length buffers anyway).\n */\nfunction constantTimeEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n}\n\n/**\n * Bearer-token check (S4): `Authorization: Bearer <token>` header, or\n * (only when `allowQueryToken`) a `?token=` query param.\n *\n * The query-string form only exists for the one request that structurally\n * cannot carry a custom header — the initial browser navigation that\n * loads the HTML shell (a typed/clicked/bookmarked URL). Every other\n * request the served page makes is same-origin `fetch()`, which can and\n * does set `Authorization` (see `ui.html.ts`'s `fetchAuthed`), so the API\n * routes never need to accept a query-string token. Restricting the\n * fallback to just the page route minimizes the token's exposure in\n * server access logs, proxy logs, and browser history to a single route\n * instead of every poll.\n */\nfunction isAuthorized(\n req: IncomingMessage,\n url: URL,\n token: string,\n allowQueryToken: boolean,\n): boolean {\n const header = req.headers.authorization;\n if (header && constantTimeEqual(header, `Bearer ${token}`)) return true;\n if (!allowQueryToken) return false;\n const queryToken = url.searchParams.get(\"token\");\n return queryToken !== null && constantTimeEqual(queryToken, token);\n}\n\n/**\n * Build the `node:http` request handler for the dashboard over a given\n * trace store. Kept separate from the server lifecycle so it can be unit\n * tested by feeding it a fake `req`/`res` without binding a port.\n *\n * Routes (all under `config.basePath`):\n *\n * - `GET api/traces` → `store.query(parseQuery(searchParams))`\n * - `GET api/traces/:id` → `store.get(id)` or `404`\n * - `GET api/aggregate` → `store.aggregate(parseQuery(searchParams))`\n * - `GET {basePath}` → the self-contained HTML page\n * - `POST api/traces/:traceId/spans/:spanId/evaluate` → ONLY when\n * `config.evaluate` is set; grades the span's last captured system\n * prompt and returns a {@link EvaluateVerdict}. The dashboard's one\n * write route — absent config, POST 405s like it would against any\n * other route (the path is never even pattern-matched).\n *\n * Anything else → `404`. A method the matched route doesn't accept → `405`.\n * Host allowlist + bearer-token auth (S4) are checked for EVERY request,\n * regardless of method, before any routing. The store shapes\n * ({@link Trace}/{@link TraceSpan}) are already JSON-safe, so GET responses\n * are a plain `JSON.stringify` with no serializer.\n *\n * @example\n * const handler = createRequestHandler(store, { basePath: \"/\", title: \"Panoptic\" });\n * http.createServer(handler).listen(4319, \"127.0.0.1\");\n */\nexport function createRequestHandler(\n store: TraceStoreContract,\n config: ServeConfig,\n): (req: IncomingMessage, res: ServerResponse) => void {\n const base = config.basePath;\n const apiPrefix = `${base}api`;\n\n return function handle(req: IncomingMessage, res: ServerResponse): void {\n // `req.url` is path + query only; a dummy origin lets URL parse it.\n const url = new URL(req.url ?? \"/\", \"http://localhost\");\n const pathname = url.pathname;\n\n // Host-header allowlist — blocks DNS-rebinding attacks that point a\n // hostile domain at this loopback port (S4). Checked for every method.\n const host = hostHeaderName(req.headers.host);\n if (!host || !config.allowedHosts.includes(host.toLowerCase())) {\n sendJson(res, 403, { error: \"host_not_allowed\" });\n\n return;\n }\n\n // Bearer-token auth when configured (always required off loopback, S4).\n // `?token=` is only honored on the HTML page route — see `isAuthorized`.\n const isPageRoute = pathname === base || pathname === base.replace(/\\/$/, \"\");\n if (config.authToken && !isAuthorized(req, url, config.authToken, isPageRoute)) {\n sendJson(res, 401, { error: \"unauthorized\" });\n\n return;\n }\n\n // The one write route — opt-in via `config.evaluate`, so it must be\n // checked before the blanket GET-only gate below.\n if (req.method === \"POST\" && config.evaluate) {\n const match = matchEvaluatePath(pathname, apiPrefix);\n\n if (match) {\n void handleEvaluate(store, config.evaluate, match.traceId, match.spanId, req, res);\n\n return;\n }\n }\n\n if (req.method !== \"GET\") {\n sendJson(res, 405, { error: \"method_not_allowed\" });\n\n return;\n }\n\n if (pathname === `${apiPrefix}/traces`) {\n sendJson(res, 200, store.query(parseQuery(url.searchParams)));\n\n return;\n }\n\n if (pathname.startsWith(`${apiPrefix}/traces/`)) {\n const traceId = decodeURIComponent(pathname.slice(`${apiPrefix}/traces/`.length));\n const trace = traceId.length > 0 ? store.get(traceId) : undefined;\n\n if (trace === undefined) {\n sendJson(res, 404, { error: \"trace_not_found\", traceId });\n\n return;\n }\n\n sendJson(res, 200, trace);\n\n return;\n }\n\n if (pathname === `${apiPrefix}/aggregate`) {\n sendJson(res, 200, store.aggregate(parseQuery(url.searchParams)));\n\n return;\n }\n\n if (pathname === base || pathname === base.replace(/\\/$/, \"\")) {\n res.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n ...SECURITY_HEADERS,\n });\n res.end(\n dashboardHtml(\n base,\n config.title,\n Boolean(config.evaluate),\n config.evaluate?.instructions ?? \"\",\n ),\n );\n\n return;\n }\n\n sendJson(res, 404, { error: \"not_found\" });\n };\n}\n\n/** Write a JSON response with the given status code and security headers. */\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n ...SECURITY_HEADERS,\n });\n res.end(JSON.stringify(body));\n}\n\n/**\n * Match `{apiPrefix}/traces/:traceId/spans/:spanId/evaluate` — the one\n * write route. Returns `undefined` for anything else, including the plain\n * `{apiPrefix}/traces/:id` read route (no `/spans/.../evaluate` suffix),\n * so the two never collide.\n */\nfunction matchEvaluatePath(\n pathname: string,\n apiPrefix: string,\n): { traceId: string; spanId: string } | undefined {\n const prefix = `${apiPrefix}/traces/`;\n\n if (!pathname.startsWith(prefix)) {\n return undefined;\n }\n\n const match = /^([^/]+)\\/spans\\/([^/]+)\\/evaluate$/.exec(pathname.slice(prefix.length));\n\n if (!match) {\n return undefined;\n }\n\n return {\n traceId: decodeURIComponent(match[1]),\n spanId: decodeURIComponent(match[2]),\n };\n}\n\n/**\n * Collect and JSON-parse a request body, capped at\n * {@link MAX_EVALUATE_BODY_BYTES} so an oversized body can't hold the\n * connection open indefinitely. An empty body resolves to `undefined` —\n * the evaluate route treats that as \"no per-run override\".\n */\nfunction readJsonBody<T>(req: IncomingMessage): Promise<T | undefined> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n\n req.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n\n if (size > MAX_EVALUATE_BODY_BYTES) {\n req.destroy();\n reject(new Error(\"payload_too_large\"));\n\n return;\n }\n\n chunks.push(chunk);\n });\n\n req.on(\"end\", () => {\n if (chunks.length === 0) {\n resolve(undefined);\n\n return;\n }\n\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString(\"utf-8\")) as T);\n } catch {\n reject(new Error(\"invalid_json\"));\n }\n });\n\n req.on(\"error\", reject);\n });\n}\n\n/**\n * Handle `POST {apiPrefix}/traces/:traceId/spans/:spanId/evaluate`. Looks\n * up the trace + span, extracts its last captured system prompt, and\n * grades it via {@link evaluateSystemPrompt}. `judgePromptBody` itself\n * never throws (a broken judge degrades to an issues-only outcome) — the\n * try/catch here only guards `config.evaluate.model` resolution, the one\n * step that CAN throw (e.g. a factory constructing an SDK client).\n */\nasync function handleEvaluate(\n store: TraceStoreContract,\n evaluate: EvaluateConfig,\n traceId: string,\n spanId: string,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<void> {\n const trace = store.get(traceId);\n\n if (trace === undefined) {\n sendJson(res, 404, { error: \"trace_not_found\", traceId });\n\n return;\n }\n\n const span = findSpanById(trace.root, spanId);\n\n if (span === undefined) {\n sendJson(res, 404, { error: \"span_not_found\", spanId });\n\n return;\n }\n\n const systemPrompt = extractLastSystemPrompt(span);\n\n if (systemPrompt === undefined) {\n sendJson(res, 422, { error: \"no_system_prompt\" });\n\n return;\n }\n\n let body: EvaluateRequestBody | undefined;\n\n try {\n body = await readJsonBody<EvaluateRequestBody>(req);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"invalid_json\";\n sendJson(res, message === \"payload_too_large\" ? 413 : 400, { error: message });\n\n return;\n }\n\n try {\n const verdict = await evaluateSystemPrompt(systemPrompt, evaluate, body?.instructions);\n sendJson(res, 200, verdict);\n } catch (error) {\n sendJson(res, 502, {\n error: \"evaluate_failed\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n}\n"],"mappings":";;;;;;;;;AAoCA,MAAM,0BAA0B;;;;;;AAOhC,MAAM,mBAA2C;CAC/C,0BAA0B;CAC1B,mBAAmB;CACnB,mBAAmB;CACnB,2BACE;AACJ;;AAGA,SAAS,eAAe,YAAoD;CAC1E,IAAI,CAAC,YAAY,OAAO;CAExB,IAAI,WAAW,WAAW,GAAG,GAC3B,OAAO,WAAW,MAAM,GAAG,WAAW,QAAQ,GAAG,IAAI,CAAC;CAExD,MAAM,QAAQ,WAAW,QAAQ,GAAG;CACpC,OAAO,UAAU,KAAK,aAAa,WAAW,MAAM,GAAG,KAAK;AAC9D;;;;;;;;;;AAWA,SAAS,kBAAkB,GAAW,GAAoB;CACxD,MAAM,OAAO,OAAO,KAAK,CAAC;CAC1B,MAAM,OAAO,OAAO,KAAK,CAAC;CAE1B,IAAI,KAAK,WAAW,KAAK,QAAQ,OAAO;CAExC,OAAO,gBAAgB,MAAM,IAAI;AACnC;;;;;;;;;;;;;;;AAgBA,SA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AAc,UAAU,MAAM,YAAY,CAC3D;CAC5B,SAAS,OAAO;EACd,SAAS,KAAK,KAAK;GACjB,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"serve.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/serve.ts"],"sourcesContent":["import { timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { EvaluateConfig } from \"../evaluate/evaluate.type\";\nimport { evaluateSystemPrompt } from \"../evaluate/evaluate-system-prompt\";\nimport { extractLastSystemPrompt } from \"../evaluate/extract-last-system-prompt\";\nimport { findSpanById } from \"../evaluate/find-span-by-id\";\nimport type { TraceStoreContract } from \"../store/trace-store.contract\";\nimport { parseListOptions, parseQuery } from \"./parse-query\";\nimport { toTraceSummary } from \"./trace-summary\";\nimport { dashboardHtml } from \"./ui.html\";\n\n/** Fully-resolved routing config the request handler closes over. */\nexport type ServeConfig = {\n /** Normalized mount path, always ending in `/` (e.g. `\"/\"`). */\n basePath: string;\n /** Header title baked into the served page. */\n title: string;\n /** Bearer token required on every request when set (S4). */\n authToken?: string;\n /** `Host` header allowlist — defends against DNS-rebinding (S4). */\n allowedHosts: string[];\n /**\n * Enables the one write route: `POST\n * {basePath}api/traces/:traceId/spans/:spanId/evaluate`. Absent ⇒ the\n * route 405s (POST isn't accepted by any route) and the served page never\n * renders the Evaluate button.\n */\n evaluate?: EvaluateConfig;\n};\n\n/** Request body accepted by the evaluate route — everything optional. */\ntype EvaluateRequestBody = {\n /** Per-run instructions override; falls back to `config.evaluate.instructions`. */\n instructions?: string;\n};\n\n/** Hard cap on the evaluate route's request body — well beyond a real instructions string. */\nconst MAX_EVALUATE_BODY_BYTES = 64 * 1024;\n\n/**\n * Security response headers added to every dashboard response (S4):\n * block MIME-sniffing, framing, referrer leakage, and lock the page's\n * content sources down to itself (the UI is fully self-contained — no CDN).\n */\nconst SECURITY_HEADERS: Record<string, string> = {\n \"x-content-type-options\": \"nosniff\",\n \"x-frame-options\": \"DENY\",\n \"referrer-policy\": \"no-referrer\",\n \"content-security-policy\":\n \"default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'\",\n};\n\n/** Extract the host (no port) from a `Host` header value. */\nfunction hostHeaderName(hostHeader: string | undefined): string | undefined {\n if (!hostHeader) return undefined;\n // IPv6 literal `[::1]:4319` → `[::1]`; otherwise strip `:port`.\n if (hostHeader.startsWith(\"[\")) {\n return hostHeader.slice(0, hostHeader.indexOf(\"]\") + 1);\n }\n const colon = hostHeader.indexOf(\":\");\n return colon === -1 ? hostHeader : hostHeader.slice(0, colon);\n}\n\n/**\n * Constant-time string equality (S4) — guards against a timing\n * side-channel that could otherwise let a network-adjacent attacker\n * recover the token byte-by-byte via repeated timed guesses. Plain `===`\n * short-circuits on the first differing byte, so response latency leaks\n * how many leading bytes matched; `timingSafeEqual` does not. Lengths are\n * compared first (a length mismatch is not secret and `timingSafeEqual`\n * requires equal-length buffers anyway).\n */\nfunction constantTimeEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n}\n\n/**\n * Bearer-token check (S4): `Authorization: Bearer <token>` header, or\n * (only when `allowQueryToken`) a `?token=` query param.\n *\n * The query-string form only exists for the one request that structurally\n * cannot carry a custom header — the initial browser navigation that\n * loads the HTML shell (a typed/clicked/bookmarked URL). Every other\n * request the served page makes is same-origin `fetch()`, which can and\n * does set `Authorization` (see `ui.html.ts`'s `fetchAuthed`), so the API\n * routes never need to accept a query-string token. Restricting the\n * fallback to just the page route minimizes the token's exposure in\n * server access logs, proxy logs, and browser history to a single route\n * instead of every poll.\n */\nfunction isAuthorized(\n req: IncomingMessage,\n url: URL,\n token: string,\n allowQueryToken: boolean,\n): boolean {\n const header = req.headers.authorization;\n if (header && constantTimeEqual(header, `Bearer ${token}`)) return true;\n if (!allowQueryToken) return false;\n const queryToken = url.searchParams.get(\"token\");\n return queryToken !== null && constantTimeEqual(queryToken, token);\n}\n\n/**\n * Build the `node:http` request handler for the dashboard over a given\n * trace store. Kept separate from the server lifecycle so it can be unit\n * tested by feeding it a fake `req`/`res` without binding a port.\n *\n * Routes (all under `config.basePath`):\n *\n * - `GET api/traces` → the newest `?limit=` (default 200) matches of\n * `store.query(parseQuery(searchParams))`, as {@link TraceSummary}\n * entries (no span tree or captured content); `?full=1` returns full traces\n * - `GET api/traces/:id` → `store.get(id)` or `404` (`400` for a malformed id)\n * - `GET api/aggregate` → `store.aggregate(parseQuery(searchParams))`\n * - `GET {basePath}` → the self-contained HTML page\n * - `POST api/traces/:traceId/spans/:spanId/evaluate` → ONLY when\n * `config.evaluate` is set; grades the span's last captured system\n * prompt and returns a {@link EvaluateVerdict}. The dashboard's one\n * write route — absent config, POST 405s like it would against any\n * other route (the path is never even pattern-matched).\n *\n * Anything else → `404`. A method the matched route doesn't accept → `405`.\n * A handler failure answers `500` instead of escaping the server's\n * `request` listener, so one bad request can never take the app down.\n * Host allowlist + bearer-token auth (S4) are checked for EVERY request,\n * regardless of method, before any routing. The store shapes\n * ({@link Trace}/{@link TraceSpan}) are already JSON-safe, so GET responses\n * are a plain `JSON.stringify` with no serializer.\n *\n * @example\n * const handler = createRequestHandler(store, { basePath: \"/\", title: \"Panoptic\" });\n * http.createServer(handler).listen(4319, \"127.0.0.1\");\n */\nexport function createRequestHandler(\n store: TraceStoreContract,\n config: ServeConfig,\n): (req: IncomingMessage, res: ServerResponse) => void {\n const base = config.basePath;\n const apiPrefix = `${base}api`;\n\n return function handle(req: IncomingMessage, res: ServerResponse): void {\n try {\n route(req, res);\n } catch {\n sendInternalError(res);\n }\n };\n\n function route(req: IncomingMessage, res: ServerResponse): void {\n // `req.url` is path + query only; a dummy origin lets URL parse it.\n const url = new URL(req.url ?? \"/\", \"http://localhost\");\n const pathname = url.pathname;\n\n // Host-header allowlist — blocks DNS-rebinding attacks that point a\n // hostile domain at this loopback port (S4). Checked for every method.\n const host = hostHeaderName(req.headers.host);\n if (!host || !config.allowedHosts.includes(host.toLowerCase())) {\n sendJson(res, 403, { error: \"host_not_allowed\" });\n\n return;\n }\n\n // Bearer-token auth when configured (always required off loopback, S4).\n // `?token=` is only honored on the HTML page route — see `isAuthorized`.\n const isPageRoute = pathname === base || pathname === base.replace(/\\/$/, \"\");\n if (config.authToken && !isAuthorized(req, url, config.authToken, isPageRoute)) {\n sendJson(res, 401, { error: \"unauthorized\" });\n\n return;\n }\n\n // The one write route — opt-in via `config.evaluate`, so it must be\n // checked before the blanket GET-only gate below.\n if (req.method === \"POST\" && config.evaluate) {\n const match = matchEvaluatePath(pathname, apiPrefix);\n\n if (match === \"malformed\") {\n sendJson(res, 400, { error: \"bad_trace_id\" });\n\n return;\n }\n\n if (match) {\n handleEvaluate(store, config.evaluate, match.traceId, match.spanId, req, res).catch(() =>\n sendInternalError(res),\n );\n\n return;\n }\n }\n\n if (req.method !== \"GET\") {\n sendJson(res, 405, { error: \"method_not_allowed\" });\n\n return;\n }\n\n if (pathname === `${apiPrefix}/traces`) {\n const { limit, full } = parseListOptions(url.searchParams);\n const traces = store.query(parseQuery(url.searchParams)).slice(0, limit);\n\n sendJson(res, 200, full ? traces : traces.map(toTraceSummary));\n\n return;\n }\n\n if (pathname.startsWith(`${apiPrefix}/traces/`)) {\n const traceId = safeDecode(pathname.slice(`${apiPrefix}/traces/`.length));\n\n if (traceId === undefined) {\n sendJson(res, 400, { error: \"bad_trace_id\" });\n\n return;\n }\n\n const trace = traceId.length > 0 ? store.get(traceId) : undefined;\n\n if (trace === undefined) {\n sendJson(res, 404, { error: \"trace_not_found\", traceId });\n\n return;\n }\n\n sendJson(res, 200, trace);\n\n return;\n }\n\n if (pathname === `${apiPrefix}/aggregate`) {\n sendJson(res, 200, store.aggregate(parseQuery(url.searchParams)));\n\n return;\n }\n\n if (pathname === base || pathname === base.replace(/\\/$/, \"\")) {\n res.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n ...SECURITY_HEADERS,\n });\n res.end(\n dashboardHtml(\n base,\n config.title,\n Boolean(config.evaluate),\n config.evaluate?.instructions ?? \"\",\n ),\n );\n\n return;\n }\n\n sendJson(res, 404, { error: \"not_found\" });\n }\n}\n\n/**\n * `decodeURIComponent` that answers `undefined` for a malformed escape\n * (`%E0%A4%A`) instead of throwing a `URIError`.\n */\nfunction safeDecode(value: string): string | undefined {\n try {\n return decodeURIComponent(value);\n } catch {\n return undefined;\n }\n}\n\n/** Answer `500` unless a response is already on its way. */\nfunction sendInternalError(res: ServerResponse): void {\n if (res.headersSent) {\n res.end();\n\n return;\n }\n\n sendJson(res, 500, { error: \"internal\" });\n}\n\n/** Write a JSON response with the given status code and security headers. */\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n ...SECURITY_HEADERS,\n });\n res.end(JSON.stringify(body));\n}\n\n/**\n * Match `{apiPrefix}/traces/:traceId/spans/:spanId/evaluate` — the one\n * write route. Returns `undefined` for anything else, including the plain\n * `{apiPrefix}/traces/:id` read route (no `/spans/.../evaluate` suffix),\n * so the two never collide. `\"malformed\"` when an id is not valid\n * percent-encoding.\n */\nfunction matchEvaluatePath(\n pathname: string,\n apiPrefix: string,\n): { traceId: string; spanId: string } | \"malformed\" | undefined {\n const prefix = `${apiPrefix}/traces/`;\n\n if (!pathname.startsWith(prefix)) {\n return undefined;\n }\n\n const match = /^([^/]+)\\/spans\\/([^/]+)\\/evaluate$/.exec(pathname.slice(prefix.length));\n\n if (!match) {\n return undefined;\n }\n\n const traceId = safeDecode(match[1] ?? \"\");\n const spanId = safeDecode(match[2] ?? \"\");\n\n if (traceId === undefined || spanId === undefined) {\n return \"malformed\";\n }\n\n return { traceId, spanId };\n}\n\n/**\n * Collect and JSON-parse a request body, capped at\n * {@link MAX_EVALUATE_BODY_BYTES} so an oversized body can't hold the\n * connection open indefinitely. An empty body resolves to `undefined` —\n * the evaluate route treats that as \"no per-run override\".\n */\nfunction readJsonBody<T>(req: IncomingMessage): Promise<T | undefined> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n\n req.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n\n if (size > MAX_EVALUATE_BODY_BYTES) {\n req.destroy();\n reject(new Error(\"payload_too_large\"));\n\n return;\n }\n\n chunks.push(chunk);\n });\n\n req.on(\"end\", () => {\n if (chunks.length === 0) {\n resolve(undefined);\n\n return;\n }\n\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString(\"utf-8\")) as T);\n } catch {\n reject(new Error(\"invalid_json\"));\n }\n });\n\n req.on(\"error\", reject);\n });\n}\n\n/**\n * Handle `POST {apiPrefix}/traces/:traceId/spans/:spanId/evaluate`. Looks\n * up the trace + span, extracts its last captured system prompt, and\n * grades it via {@link evaluateSystemPrompt}. `judgePromptBody` itself\n * never throws (a broken judge degrades to an issues-only outcome) — the\n * try/catch here only guards `config.evaluate.model` resolution, the one\n * step that CAN throw (e.g. a factory constructing an SDK client).\n */\nasync function handleEvaluate(\n store: TraceStoreContract,\n evaluate: EvaluateConfig,\n traceId: string,\n spanId: string,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<void> {\n const trace = store.get(traceId);\n\n if (trace === undefined) {\n sendJson(res, 404, { error: \"trace_not_found\", traceId });\n\n return;\n }\n\n const span = findSpanById(trace.root, spanId);\n\n if (span === undefined) {\n sendJson(res, 404, { error: \"span_not_found\", spanId });\n\n return;\n }\n\n const systemPrompt = extractLastSystemPrompt(span);\n\n if (systemPrompt === undefined) {\n sendJson(res, 422, { error: \"no_system_prompt\" });\n\n return;\n }\n\n let body: EvaluateRequestBody | undefined;\n\n try {\n body = await readJsonBody<EvaluateRequestBody>(req);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"invalid_json\";\n sendJson(res, message === \"payload_too_large\" ? 413 : 400, { error: message });\n\n return;\n }\n\n try {\n const verdict = await evaluateSystemPrompt(systemPrompt, evaluate, body?.instructions);\n sendJson(res, 200, verdict);\n } catch (error) {\n sendJson(res, 502, {\n error: \"evaluate_failed\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAqCA,MAAM,0BAA0B;;;;;;AAOhC,MAAM,mBAA2C;CAC/C,0BAA0B;CAC1B,mBAAmB;CACnB,mBAAmB;CACnB,2BACE;AACJ;;AAGA,SAAS,eAAe,YAAoD;CAC1E,IAAI,CAAC,YAAY,OAAO;CAExB,IAAI,WAAW,WAAW,GAAG,GAC3B,OAAO,WAAW,MAAM,GAAG,WAAW,QAAQ,GAAG,IAAI,CAAC;CAExD,MAAM,QAAQ,WAAW,QAAQ,GAAG;CACpC,OAAO,UAAU,KAAK,aAAa,WAAW,MAAM,GAAG,KAAK;AAC9D;;;;;;;;;;AAWA,SAAS,kBAAkB,GAAW,GAAoB;CACxD,MAAM,OAAO,OAAO,KAAK,CAAC;CAC1B,MAAM,OAAO,OAAO,KAAK,CAAC;CAE1B,IAAI,KAAK,WAAW,KAAK,QAAQ,OAAO;CAExC,OAAO,gBAAgB,MAAM,IAAI;AACnC;;;;;;;;;;;;;;;AAgBA,SAAS,aACP,KACA,KACA,OACA,iBACS;CACT,MAAM,SAAS,IAAI,QAAQ;CAC3B,IAAI,UAAU,kBAAkB,QAAQ,UAAU,OAAO,GAAG,OAAO;CACnE,IAAI,CAAC,iBAAiB,OAAO;CAC7B,MAAM,aAAa,IAAI,aAAa,IAAI,OAAO;CAC/C,OAAO,eAAe,QAAQ,kBAAkB,YAAY,KAAK;AACnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,qBACd,OACA,QACqD;CACrD,MAAM,OAAO,OAAO;CACpB,MAAM,YAAY,GAAG,KAAK;CAE1B,OAAO,SAAS,OAAO,KAAs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AAwB,IAAI;CAEjD,IAAI,iBAAiB,QAAW;EAC9B,SAAS,KAAK,KAAK,EAAE,OAAO,mBAAmB,CAAC;EAEhD;CACF;CAEA,IAAI;CAEJ,IAAI;EACF,OAAO,MAAM,aAAkC,GAAG;CACpD,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;EACzD,SAAS,KAAK,YAAY,sBAAsB,MAAM,KAAK,EAAE,OAAO,QAAQ,CAAC;EAE7E;CACF;CAEA,IAAI;EAEF,SAAS,KAAK,KAAK,MADG,qBAAqB,cAAc,UAAU,MAAM,YAAY,CAC3D;CAC5B,SAAS,OAAO;EACd,SAAS,KAAK,KAAK;GACjB,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Trace, TraceSpan, TraceSpanError } from "../contracts/trace.type.mjs";
|
|
2
|
+
//#region ../../packages/ai-panoptic/src/dashboard/trace-summary.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The root span of a {@link TraceSummary}: identity, timing, status,
|
|
5
|
+
* usage and attributes, without captured content (`input` / `output`),
|
|
6
|
+
* children or the error's stack and cause.
|
|
7
|
+
*/
|
|
8
|
+
export type TraceSpanSummary = Omit<TraceSpan, "input" | "output" | "children" | "error"> & {
|
|
9
|
+
error?: Pick<TraceSpanError, "type" | "message">;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* One entry of the dashboard's `GET api/traces` list: everything the trace
|
|
13
|
+
* list renders, without the span tree or captured content. The full trace
|
|
14
|
+
* stays on `GET api/traces/:id` (or the list with `?full=1`).
|
|
15
|
+
*/
|
|
16
|
+
export type TraceSummary = Omit<Trace, "root"> & {
|
|
17
|
+
root: TraceSpanSummary;
|
|
18
|
+
/** Number of spans in the trace tree, the root included. */
|
|
19
|
+
spanCount: number;
|
|
20
|
+
/** Total USD cost of the trace (its priced root usage, else the rollup of its subtree). */
|
|
21
|
+
totalCost: number;
|
|
22
|
+
};
|
|
23
|
+
//#endregion
|
|
24
|
+
//# sourceMappingURL=trace-summary.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace-summary.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/trace-summary.ts"],"mappings":";;;;;;;YAQY,mBAAmB,KAAK;EAClC,QAAQ,KAAK;;;;;;;YAQH,eAAe,KAAK;EAC9B,MAAM;;EAEN;;EAEA"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { traceCost } from "./trace-filter.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/ai-panoptic/src/dashboard/trace-summary.ts
|
|
4
|
+
function countSpans(span) {
|
|
5
|
+
let count = 1;
|
|
6
|
+
for (const child of span.children) count += countSpans(child);
|
|
7
|
+
return count;
|
|
8
|
+
}
|
|
9
|
+
/** Project a stored trace onto the list summary served by `GET api/traces`. */
|
|
10
|
+
function toTraceSummary(trace) {
|
|
11
|
+
const { input: _input, output: _output, children: _children, error, ...root } = trace.root;
|
|
12
|
+
const summaryRoot = root;
|
|
13
|
+
if (error !== void 0) summaryRoot.error = {
|
|
14
|
+
type: error.type,
|
|
15
|
+
message: error.message
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
...trace,
|
|
19
|
+
root: summaryRoot,
|
|
20
|
+
spanCount: countSpans(trace.root),
|
|
21
|
+
totalCost: traceCost(trace)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
//#endregion
|
|
26
|
+
export { toTraceSummary };
|
|
27
|
+
//# sourceMappingURL=trace-summary.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace-summary.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/trace-summary.ts"],"sourcesContent":["import type { Trace, TraceSpan, TraceSpanError } from \"../contracts/trace.type\";\nimport { traceCost } from \"./trace-filter\";\n\n/**\n * The root span of a {@link TraceSummary}: identity, timing, status,\n * usage and attributes, without captured content (`input` / `output`),\n * children or the error's stack and cause.\n */\nexport type TraceSpanSummary = Omit<TraceSpan, \"input\" | \"output\" | \"children\" | \"error\"> & {\n error?: Pick<TraceSpanError, \"type\" | \"message\">;\n};\n\n/**\n * One entry of the dashboard's `GET api/traces` list: everything the trace\n * list renders, without the span tree or captured content. The full trace\n * stays on `GET api/traces/:id` (or the list with `?full=1`).\n */\nexport type TraceSummary = Omit<Trace, \"root\"> & {\n root: TraceSpanSummary;\n /** Number of spans in the trace tree, the root included. */\n spanCount: number;\n /** Total USD cost of the trace (its priced root usage, else the rollup of its subtree). */\n totalCost: number;\n};\n\nfunction countSpans(span: TraceSpan): number {\n let count = 1;\n\n for (const child of span.children) {\n count += countSpans(child);\n }\n\n return count;\n}\n\n/** Project a stored trace onto the list summary served by `GET api/traces`. */\nexport function toTraceSummary(trace: Trace): TraceSummary {\n const { input: _input, output: _output, children: _children, error, ...root } = trace.root;\n const summaryRoot: TraceSpanSummary = root;\n\n if (error !== undefined) {\n summaryRoot.error = { type: error.type, message: error.message };\n }\n\n return {\n ...trace,\n root: summaryRoot,\n spanCount: countSpans(trace.root),\n totalCost: traceCost(trace),\n };\n}\n"],"mappings":";;;AAyBA,SAAS,WAAW,MAAyB;CAC3C,IAAI,QAAQ;CAEZ,KAAK,MAAM,SAAS,KAAK,UACvB,SAAS,WAAW,KAAK;CAG3B,OAAO;AACT;;AAGA,SAAgB,eAAe,OAA4B;CACzD,MAAM,EAAE,OAAO,QAAQ,QAAQ,SAAS,UAAU,WAAW,OAAO,GAAG,SAAS,MAAM;CACtF,MAAM,cAAgC;CAEtC,IAAI,UAAU,QACZ,YAAY,QAAQ;EAAE,MAAM,MAAM;EAAM,SAAS,MAAM;CAAQ;CAGjE,OAAO;EACL,GAAG;EACH,MAAM;EACN,WAAW,WAAW,MAAM,IAAI;EAChC,WAAW,UAAU,KAAK;CAC5B;AACF"}
|