@warlock.js/ai-panoptic 5.53.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/cjs/index.cjs.map +1 -1
- package/esm/collector/collector.mjs.map +1 -1
- package/esm/collector/extract-span-attributes.mjs.map +1 -1
- package/esm/collector/normalize-error.mjs.map +1 -1
- package/esm/collector/report-to-span.mjs.map +1 -1
- package/esm/collector/report-to-trace.mjs.map +1 -1
- package/esm/collector/trace-subscriptions.mjs.map +1 -1
- package/esm/config/apply-panoptic-config.mjs.map +1 -1
- package/esm/dashboard/dashboard.mjs.map +1 -1
- package/esm/dashboard/parse-query.mjs.map +1 -1
- package/esm/dashboard/serve.mjs.map +1 -1
- package/esm/dashboard/trace-filter.mjs.map +1 -1
- package/esm/dashboard/trace-summary.mjs.map +1 -1
- package/esm/dashboard/ui.html.mjs.map +1 -1
- package/esm/dashboard/warlock-logo.mjs.map +1 -1
- package/esm/evaluate/evaluate-system-prompt.mjs.map +1 -1
- package/esm/evaluate/extract-last-system-prompt.mjs.map +1 -1
- package/esm/evaluate/find-span-by-id.mjs.map +1 -1
- package/esm/exporters/console/console-exporter.mjs.map +1 -1
- package/esm/exporters/console/format-span-io.mjs.map +1 -1
- package/esm/exporters/console/format-span-line.mjs.map +1 -1
- package/esm/exporters/file/file-exporter.mjs.map +1 -1
- package/esm/exporters/langfuse/langfuse-exporter.mjs.map +1 -1
- package/esm/exporters/otel/otel-exporter.mjs.map +1 -1
- package/esm/exporters/utils/gen-ai-attributes.mjs.map +1 -1
- package/esm/exporters/utils/total-cost.mjs.map +1 -1
- package/esm/exporters/utils/walk-spans.mjs.map +1 -1
- package/esm/panoptic/panoptic-middleware.mjs.map +1 -1
- package/esm/panoptic/panoptic.mjs.map +1 -1
- package/esm/register.mjs.map +1 -1
- package/esm/store/cache-trace-store.mjs.map +1 -1
- package/esm/store/in-memory-trace-store.mjs.map +1 -1
- package/esm/store/match-trace.mjs.map +1 -1
- package/esm/store/sort-newest-first.mjs.map +1 -1
- package/esm/store/sum-usage.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collector.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/collector.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,YAAN,MAA6C;CAmBP;;;;;;CAbpC,AAAiB,4BAAY,IAAI,IAA8B;;;;;CAM/D,AAAiB,kCAAkB,IAAI,IAAY;;;;;;CAOnD,AAAO,YAAY,AAAiB,UAA4B,CAAC,GAAG;EAAhC;CAAiC;CAErE,AAAO,IAAI,UAAkC;EAC3C,IAAI,CAAC,KAAK,UAAU,IAAI,SAAS,IAAI,GACnC,KAAK,UAAU,IAAI,SAAS,MAAM,QAAQ;EAG5C,OAAO;CACT;CAEA,AAAO,QAAQ,QAAoB,WAA4B;EAC7D,OAAO,cAAc,QAAQ,WAAW,KAAK,OAAO;CACtD;CAEA,MAAa,QAAQ,QAAoB,WAAoC;EAC3E,MAAM,QAAQ,KAAK,QAAQ,QAAQ,SAAS;EAE5C,aAAa,KAAK;EAClB,MAAM,KAAK,SAAS,KAAK;CAC3B;CAEA,MAAa,QAAuB;EAClC,MAAM,KAAK,WAAW,aAAa,SAAS,QAAQ,CAAC;CACvD;CAEA,MAAa,WAA0B;EACrC,MAAM,KAAK,MAAM;EAEjB,MAAM,KAAK,WAAW,aAAa,SAAS,WAAW,CAAC;EAExD,KAAK,UAAU,MAAM;CACvB;;;;;;;;;;;CAYA,MAAc,SAAS,OAA6B;EAClD,MAAM,KAAK,UAAU,OAAO,aAAa;GACvC,MAAM,SAAS,OAAO,KAAK;GAE3B,IAAI,SAAS,eAAe,QAC1B,KAAK,MAAM,QAAQ,UAAU,MAAM,IAAI,GACrC,MAAM,SAAS,WAAW,IAAI;EAGpC,CAAC;CACH;;;;;;;CAQA,MAAc,UACZ,MACe;EACf,MAAM,OAAO,CAAC,GAAG,KAAK,UAAU,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,cACrD,QAAQ,QAAQ,CAAC,CACd,WAAW,KAAK,QAAQ,CAAC,CAAC,CAC1B,OAAO,UAAmB,KAAK,oBAAoB,MAAM,KAAK,CAAC,CACpE;EAEA,MAAM,QAAQ,WAAW,IAAI;CAC/B;;;;;;;;;CAUA,AAAQ,oBAAoB,MAAc,OAAsB;EAC9D,IAAI,KAAK,QAAQ,SAAS;GACxB,IAAI;IACF,KAAK,QAAQ,QAAQ,MAAM,KAAK;GAClC,QAAQ,CAER;GACA;EACF;EAEA,IAAI,KAAK,gBAAgB,IAAI,IAAI,GAC/B;EAGF,KAAK,gBAAgB,IAAI,IAAI;EAC7B,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,QAAQ,KAAK,wBAAwB,KAAK,6BAA6B,SAAS;CAClF;AACF;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,UAA4B,CAAC,GAAsB;CACjF,OAAO,IAAI,UAAU,OAAO;AAC9B"}
|
|
1
|
+
{"version":3,"file":"collector.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/collector.ts"],"sourcesContent":["import type { BaseReport } from \"@warlock.js/ai\";\nimport type { CollectorContract } from \"../contracts/collector.contract\";\nimport type { ExporterContract } from \"../contracts/exporter.contract\";\nimport type { Trace } from \"../contracts/trace.type\";\nimport { walkSpans } from \"../exporters/utils/walk-spans\";\nimport type { ContentCaptureOptions } from \"./content-capture.type\";\nimport { reportToTrace } from \"./report-to-trace\";\nimport { publishTrace } from \"./trace-subscriptions\";\n\n/**\n * Notified when a registered exporter throws during `collect` / `flush` /\n * `shutdown`. The failure stays isolated (the originating run never sees\n * it) — this is purely a chance to surface it (route to your logger,\n * bump a metric). Receives the exporter's `name` and the thrown error.\n */\nexport type ExporterErrorHandler = (exporterName: string, error: unknown) => void;\n\n/** Options for {@link createCollector}. */\nexport type CollectorOptions = ContentCaptureOptions & {\n /**\n * Called when an exporter throws (and is isolated). Overrides the default\n * one-time `console.warn` per exporter — route the failure to your own\n * logger / metrics instead. Errors thrown by the handler itself are\n * swallowed so observability never crashes the run.\n */\n onError?: ExporterErrorHandler;\n};\n\n/**\n * Drive the source end of the Panoptic pipeline: ingest core\n * `@warlock.js/ai` {@link BaseReport} trees, project them into {@link\n * Trace}s, and fan each trace out to every registered exporter.\n *\n * Owns exporter registration (deduped by `ExporterContract.name`), the\n * report→trace projection, and graceful shutdown so exporters drain\n * before exit. Instantiated fresh per collector via {@link\n * createCollector}; callers never see `new`.\n *\n * **Failure isolation.** An exporter that throws never propagates back\n * into the originating run — `collect`, `flush`, and `shutdown` settle\n * every exporter independently (mirrors how the core event hooks\n * swallow consumer errors). One broken exporter can neither crash the\n * agent loop nor stop sibling exporters from receiving the trace. The\n * failure is still **surfaced** — via the `onError` option, or a one-time\n * `console.warn` per exporter — so a misconfiguration (e.g. a missing\n * optional peer like `langfuse`) doesn't fail silently.\n */\nclass Collector implements CollectorContract {\n /**\n * Registered exporters in insertion order. A `Map` keyed by\n * `ExporterContract.name` gives O(1) dedupe on `use` while preserving\n * registration order for deterministic fan-out.\n */\n private readonly exporters = new Map<string, ExporterContract>();\n\n /**\n * Exporters already warned about on the default error path — so a\n * persistent misconfiguration surfaces once, not on every trace.\n */\n private readonly warnedExporters = new Set<string>();\n\n /**\n * Collector options: content capture threaded into every `toTrace`\n * projection (`captureContent` populates span `input` / `output`), plus\n * an optional `onError` for isolated exporter failures.\n */\n public constructor(private readonly options: CollectorOptions = {}) {}\n\n public use(exporter: ExporterContract): this {\n if (!this.exporters.has(exporter.name)) {\n this.exporters.set(exporter.name, exporter);\n }\n\n return this;\n }\n\n public toTrace(report: BaseReport, rootError?: unknown): Trace {\n return reportToTrace(report, rootError, this.options);\n }\n\n public async collect(report: BaseReport, rootError?: unknown): Promise<void> {\n const trace = this.toTrace(report, rootError);\n\n publishTrace(trace);\n await this.dispatch(trace);\n }\n\n public async flush(): Promise<void> {\n await this.settleAll((exporter) => exporter.flush?.());\n }\n\n public async shutdown(): Promise<void> {\n await this.flush();\n\n await this.settleAll((exporter) => exporter.shutdown?.());\n\n this.exporters.clear();\n }\n\n /**\n * Fan one trace out to every exporter and, when an exporter advertises\n * the per-span hook, deliver every span in the finalized tree to it as\n * well. `exportSpan` is a post-completion per-span hook (not a live /\n * streaming feed — the trace is already finalized): we walk the tree in\n * pre-order with {@link walkSpans} so the exporter sees the root and\n * every descendant exactly once. Every invocation is isolated so a\n * throwing exporter can't abort the dispatch to its siblings or escape\n * into the originating run.\n */\n private async dispatch(trace: Trace): Promise<void> {\n await this.settleAll(async (exporter) => {\n await exporter.export(trace);\n\n if (exporter.exportSpan !== undefined) {\n for (const span of walkSpans(trace.root)) {\n await exporter.exportSpan(span);\n }\n }\n });\n }\n\n /**\n * Run `task` against every registered exporter and wait for all of\n * them to settle, swallowing individual rejections. `Promise.allSettled`\n * guarantees one failure neither rejects the batch nor blocks the\n * others — the contract's failure-isolation requirement.\n */\n private async settleAll(\n task: (exporter: ExporterContract) => void | Promise<void>,\n ): Promise<void> {\n const runs = [...this.exporters.entries()].map(([name, exporter]) =>\n Promise.resolve()\n .then(() => task(exporter))\n .catch((error: unknown) => this.reportExporterError(name, error)),\n );\n\n await Promise.allSettled(runs);\n }\n\n /**\n * Surface an isolated exporter failure. The originating run never sees it\n * (the isolation guarantee holds), but a silent failure is the wrong\n * default for a config error — e.g. a missing optional peer like\n * `langfuse` would otherwise drop every trace with no signal. The\n * supplied `onError` is called, or — by default — a `console.warn` is\n * emitted ONCE per exporter so the cause is visible without spamming.\n */\n private reportExporterError(name: string, error: unknown): void {\n if (this.options.onError) {\n try {\n this.options.onError(name, error);\n } catch {\n // Never let the error handler itself escape into the run.\n }\n return;\n }\n\n if (this.warnedExporters.has(name)) {\n return;\n }\n\n this.warnedExporters.add(name);\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[panoptic] exporter \"${name}\" failed and was isolated: ${message}`);\n }\n}\n\n/**\n * Create a Panoptic collector — the single integration point an app\n * wires into its agents/workflows (typically via the `onComplete`\n * report hook). Register exporters with `use`, then feed finalized root\n * reports to `collect`.\n *\n * @example\n * const collector = createCollector().use(otelExporter).use(langfuseExporter);\n * agent.on(\"onComplete\", ({ result }) => collector.collect(result.report));\n * // on shutdown:\n * await collector.shutdown();\n */\nexport function createCollector(options: CollectorOptions = {}): CollectorContract {\n return new Collector(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,YAAN,MAA6C;CAmBP;;;;;;CAbpC,AAAiB,4BAAY,IAAI,IAA8B;;;;;CAM/D,AAAiB,kCAAkB,IAAI,IAAY;;;;;;CAOnD,AAAO,YAAY,AAAiB,UAA4B,CAAC,GAAG;EAAhC;CAAiC;CAErE,AAAO,IAAI,UAAkC;EAC3C,IAAI,CAAC,KAAK,UAAU,IAAI,SAAS,IAAI,GACnC,KAAK,UAAU,IAAI,SAAS,MAAM,QAAQ;EAG5C,OAAO;CACT;CAEA,AAAO,QAAQ,QAAoB,WAA4B;EAC7D,OAAO,cAAc,QAAQ,WAAW,KAAK,OAAO;CACtD;CAEA,MAAa,QAAQ,QAAoB,WAAoC;EAC3E,MAAM,QAAQ,KAAK,QAAQ,QAAQ,SAAS;EAE5C,aAAa,KAAK;EAClB,MAAM,KAAK,SAAS,KAAK;CAC3B;CAEA,MAAa,QAAuB;EAClC,MAAM,KAAK,WAAW,aAAa,SAAS,QAAQ,CAAC;CACvD;CAEA,MAAa,WAA0B;EACrC,MAAM,KAAK,MAAM;EAEjB,MAAM,KAAK,WAAW,aAAa,SAAS,WAAW,CAAC;EAExD,KAAK,UAAU,MAAM;CACvB;;;;;;;;;;;CAYA,MAAc,SAAS,OAA6B;EAClD,MAAM,KAAK,UAAU,OAAO,aAAa;GACvC,MAAM,SAAS,OAAO,KAAK;GAE3B,IAAI,SAAS,eAAe,QAC1B,KAAK,MAAM,QAAQ,UAAU,MAAM,IAAI,GACrC,MAAM,SAAS,WAAW,IAAI;EAGpC,CAAC;CACH;;;;;;;CAQA,MAAc,UACZ,MACe;EACf,MAAM,OAAO,CAAC,GAAG,KAAK,UAAU,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,cACrD,QAAQ,QAAQ,CAAC,CACd,WAAW,KAAK,QAAQ,CAAC,CAAC,CAC1B,OAAO,UAAmB,KAAK,oBAAoB,MAAM,KAAK,CAAC,CACpE;EAEA,MAAM,QAAQ,WAAW,IAAI;CAC/B;;;;;;;;;CAUA,AAAQ,oBAAoB,MAAc,OAAsB;EAC9D,IAAI,KAAK,QAAQ,SAAS;GACxB,IAAI;IACF,KAAK,QAAQ,QAAQ,MAAM,KAAK;GAClC,QAAQ,CAER;GACA;EACF;EAEA,IAAI,KAAK,gBAAgB,IAAI,IAAI,GAC/B;EAGF,KAAK,gBAAgB,IAAI,IAAI;EAC7B,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,QAAQ,KAAK,wBAAwB,KAAK,6BAA6B,SAAS;CAClF;AACF;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,UAA4B,CAAC,GAAsB;CACjF,OAAO,IAAI,UAAU,OAAO;AAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract-span-attributes.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/extract-span-attributes.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,sBAAsB,QAAyD;CAC7F,MAAM,aAAa;CACnB,MAAM,aAAsC,CAAC;CAE7C,IAAI,OAAO,aAAa,UAAa,OAAO,SAAS,SAAS,GAAG;EAC/D,WAAW,aAAa,OAAO,SAAS;EACxC,WAAW,oBAAoB,OAAO,SAAS,KAAK,aAAa;GAC/D,OAAO,QAAQ;GACf,WAAW,QAAQ;GACnB,SAAS,QAAQ;GACjB,UAAU,QAAQ;GAClB,QAAQ,QAAQ;EAClB,EAAE;CACJ;CAEA,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I,WAAW,OAAO,aAAa,QACjC,WAAW,0BAA0B,WAAW,MAAM;CAOxD,IAAI,WAAW,eAAe,QAC5B,WAAW,sBAAsB,WAAW;CAG9C,IAAI,WAAW,kBAAkB,QAC/B,WAAW,yBAAyB,WAAW;AAEnD;AAEA,SAAS,sBACP,YACA,YACM;CACN,IAAI,WAAW,iBAAiB,QAC9B,WAAW,mBAAmB,WAAW;CAG3C,IAAI,WAAW,cAAc,QAC3B,WAAW,wBAAwB,WAAW;CAGhD,IAAI,WAAW,UAAU,QACvB,WAAW,oBAAoB,OAAO,KAAK,WAAW,KAAK,CAAC,CAAC;AAEjE;AAEA,SAAS,wBACP,YACA,YACM;CACN,IAAI,WAAW,mBAAmB,QAChC,WAAW,qBAAqB,WAAW;CAG7C,IAAI,WAAW,iBAAiB,QAC9B,WAAW,6BAA6B,WAAW;CAGrD,IAAI,WAAW,eAAe,QAC5B,WAAW,2BAA2B,WAAW;AAErD;AAEA,SAAS,0BACP,YACA,YACM;CACN,IAAI,WAAW,cAAc,QAC3B,WAAW,4BAA4B,WAAW;CAGpD,IAAI,WAAW,cAAc,QAC3B,WAAW,4BAA4B,WAAW;CAGpD,IAAI,MAAM,QAAQ,WAAW,KAAK,GAChC,WAAW,wBAAwB,WAAW,MAAM;AAExD;AAEA,SAAS,kBACP,YACA,YACM;CACN,IAAI,WAAW,cAAc,QAC3B,WAAW,oBAAoB,WAAW;CAG5C,IAAI,WAAW,WAAW,QACxB,WAAW,iBAAiB,WAAW;CAGzC,IAAI,WAAW,kBAAkB,QAC/B,WAAW,wBAAwB,WAAW;AAElD"}
|
|
1
|
+
{"version":3,"file":"extract-span-attributes.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/extract-span-attributes.ts"],"sourcesContent":["import type { AgentCompactionRecord, BaseReport, LLMTrip } from \"@warlock.js/ai\";\n\n/**\n * Per-primitive `BaseReport` extension fields the collector surfaces as\n * span attributes. Declared as a structural superset (every field\n * optional) so a single reader can pull whatever the concrete report\n * carried without narrowing on `type` first — a `BaseReport` widened to\n * this shape exposes `undefined` for the fields its primitive doesn't\n * set, and the extractor simply skips those.\n *\n * Mirrors the public per-primitive report types in `@warlock.js/ai`\n * (`AgentReport`, `WorkflowReport`, `SupervisorReport`,\n * `OrchestratorReport`, `ToolCall`) — kept structural rather than a\n * union import so adding a new optional report field upstream is a\n * non-breaking read here.\n */\ntype ReportExtensions = {\n model?: { name?: string; provider?: string };\n trips?: LLMTrip[];\n compactions?: AgentCompactionRecord[];\n promptName?: string;\n promptVersion?: string;\n workflowName?: string;\n supervisorName?: string;\n signature?: string;\n terminatedBy?: string;\n iterations?: number;\n steps?: Record<string, unknown>;\n turns?: unknown[];\n turnIndex?: number;\n tripIndex?: number;\n callId?: string;\n recoveredFrom?: string;\n};\n\n/**\n * Build the free-form `TraceSpan.attributes` bag for one report node.\n *\n * The collector keeps the first-class span fields (identity, timing,\n * status, usage, error) on the span itself and routes everything\n * primitive-specific here — trip/step/iteration counts, the model\n * identity an agent ran against, the tool's originating trip index, a\n * supervisor's termination reason. Exporters forward this verbatim as\n * backend span attributes (OTel attributes, Langfuse metadata).\n *\n * Only populated keys are emitted; the function returns `undefined`\n * when the node carried no extra detail, so the optional\n * `TraceSpan.attributes` field stays absent rather than holding an\n * empty object (matches the contract's \"absent when empty\" note).\n *\n * Retry count is surfaced from the shared `BaseReport.attempts` for\n * every primitive so cost dashboards see the real call count.\n *\n * @example\n * const attributes = extractSpanAttributes(agentReport);\n * // { \"agent.trips\": 3, \"agent.model.name\": \"gpt-4o\", \"agent.model.provider\": \"openai\" }\n */\nexport function extractSpanAttributes(report: BaseReport): Record<string, unknown> | undefined {\n const extensions = report as BaseReport & ReportExtensions;\n const attributes: Record<string, unknown> = {};\n\n if (report.attempts !== undefined && report.attempts.length > 0) {\n attributes[\"retries\"] = report.attempts.length;\n attributes[\"retry.attempts\"] = report.attempts.map((attempt) => ({\n index: attempt.index,\n startedAt: attempt.startedAt,\n endedAt: attempt.endedAt,\n duration: attempt.duration,\n status: attempt.status,\n }));\n }\n\n switch (report.type) {\n case \"agent\": {\n addAgentAttributes(attributes, extensions);\n break;\n }\n\n case \"workflow\": {\n addWorkflowAttributes(attributes, extensions);\n break;\n }\n\n case \"supervisor\":\n case \"team\": {\n // ai.team reuses the supervisor engine, so a team report carries the\n // same supervisorName / terminatedBy / iterations fields.\n addSupervisorAttributes(attributes, extensions);\n break;\n }\n\n case \"orchestrator\": {\n addOrchestratorAttributes(attributes, extensions);\n break;\n }\n\n case \"tool\": {\n addToolAttributes(attributes, extensions);\n break;\n }\n\n default: {\n break;\n }\n }\n\n if (Object.keys(attributes).length === 0) {\n return undefined;\n }\n\n return attributes;\n}\n\nfunction addAgentAttributes(\n attributes: Record<string, unknown>,\n extensions: ReportExtensions,\n): void {\n if (Array.isArray(extensions.trips)) {\n attributes[\"agent.trips\"] = extensions.trips.length;\n // Reported provider cache reads only. Zero-token synthetic responses do\n // not identify semantic-cache hits in the core report contract.\n if (extensions.trips.some((trip) => trip.usage?.cachedTokens !== undefined)) {\n attributes[\"agent.cacheHits\"] = extensions.trips.filter(\n (trip) => (trip.usage?.cachedTokens ?? 0) > 0,\n ).length;\n }\n const truncatedTrips = extensions.trips.filter(\n (trip) => trip.finishReason === \"length\" || trip.finishReason === \"context_exceeded\",\n ).length;\n if (truncatedTrips > 0) attributes[\"agent.truncatedTrips\"] = truncatedTrips;\n const providerCompactions = extensions.trips.reduce(\n (count, trip) =>\n count + (trip.blocks?.filter((block) => block.type === \"compaction\").length ?? 0),\n 0,\n );\n if (providerCompactions > 0) attributes[\"agent.providerCompactions\"] = providerCompactions;\n }\n\n if (extensions.compactions?.length) {\n // Do not copy summary text, callback errors or raw conversation content.\n attributes[\"agent.compactions\"] = extensions.compactions.map((record) => ({\n type: record.type,\n tripIndex: record.tripIndex,\n inputTokens: record.inputTokens,\n counting: record.counting,\n reason: record.reason,\n ...(record.compaction\n ? {\n replacesFromIndex: record.compaction.replacesFromIndex,\n replacesToIndex: record.compaction.replacesToIndex,\n }\n : {}),\n }));\n }\n\n if (extensions.model?.name !== undefined) {\n attributes[\"agent.model.name\"] = extensions.model.name;\n }\n\n if (extensions.model?.provider !== undefined) {\n attributes[\"agent.model.provider\"] = extensions.model.provider;\n }\n\n // Prompt-version linkage (core `AgentReport.promptName` / `promptVersion`).\n // Present only when the agent ran against a *named* `ai.prompts` builder;\n // surfaced so the dashboard can group / filter runs by `name@version` and\n // attribute behavior shifts to a specific prompt revision.\n if (extensions.promptName !== undefined) {\n attributes[\"agent.promptName\"] = extensions.promptName;\n }\n\n if (extensions.promptVersion !== undefined) {\n attributes[\"agent.promptVersion\"] = extensions.promptVersion;\n }\n}\n\nfunction addWorkflowAttributes(\n attributes: Record<string, unknown>,\n extensions: ReportExtensions,\n): void {\n if (extensions.workflowName !== undefined) {\n attributes[\"workflow.name\"] = extensions.workflowName;\n }\n\n if (extensions.signature !== undefined) {\n attributes[\"workflow.signature\"] = extensions.signature;\n }\n\n if (extensions.steps !== undefined) {\n attributes[\"workflow.steps\"] = Object.keys(extensions.steps).length;\n }\n}\n\nfunction addSupervisorAttributes(\n attributes: Record<string, unknown>,\n extensions: ReportExtensions,\n): void {\n if (extensions.supervisorName !== undefined) {\n attributes[\"supervisor.name\"] = extensions.supervisorName;\n }\n\n if (extensions.terminatedBy !== undefined) {\n attributes[\"supervisor.terminatedBy\"] = extensions.terminatedBy;\n }\n\n if (extensions.iterations !== undefined) {\n attributes[\"supervisor.iterations\"] = extensions.iterations;\n }\n}\n\nfunction addOrchestratorAttributes(\n attributes: Record<string, unknown>,\n extensions: ReportExtensions,\n): void {\n if (extensions.turnIndex !== undefined) {\n attributes[\"orchestrator.turnIndex\"] = extensions.turnIndex;\n }\n\n if (extensions.signature !== undefined) {\n attributes[\"orchestrator.signature\"] = extensions.signature;\n }\n\n if (Array.isArray(extensions.turns)) {\n attributes[\"orchestrator.turns\"] = extensions.turns.length;\n }\n}\n\nfunction addToolAttributes(\n attributes: Record<string, unknown>,\n extensions: ReportExtensions,\n): void {\n if (extensions.tripIndex !== undefined) {\n attributes[\"tool.tripIndex\"] = extensions.tripIndex;\n }\n\n if (extensions.callId !== undefined) {\n attributes[\"tool.callId\"] = extensions.callId;\n }\n\n if (extensions.recoveredFrom !== undefined) {\n attributes[\"tool.recoveredFrom\"] = extensions.recoveredFrom;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,sBAAsB,QAAyD;CAC7F,MAAM,aAAa;CACnB,MAAM,aAAsC,CAAC;CAE7C,IAAI,OAAO,aAAa,UAAa,OAAO,SAAS,SAAS,GAAG;EAC/D,WAAW,aAAa,OAAO,SAAS;EACxC,WAAW,oBAAoB,OAAO,SAAS,KAAK,aAAa;GAC/D,OAAO,QAAQ;GACf,WAAW,QAAQ;GACnB,SAAS,QAAQ;GACjB,UAAU,QAAQ;GAClB,QAAQ,QAAQ;EAClB,EAAE;CACJ;CAEA,QAAQ,OAAO,MAAf;EACE,KAAK;GACH,mBAAmB,YAAY,UAAU;GACzC;EAGF,KAAK;GACH,sBAAsB,YAAY,UAAU;GAC5C;EAGF,KAAK;EACL,KAAK;GAGH,wBAAwB,YAAY,UAAU;GAC9C;EAGF,KAAK;GACH,0BAA0B,YAAY,UAAU;GAChD;EAGF,KAAK,QACH,kBAAkB,YAAY,UAAU;CAO5C;CAEA,IAAI,OAAO,KAAK,UAAU,CAAC,CAAC,WAAW,GACrC;CAGF,OAAO;AACT;AAEA,SAAS,mBACP,YACA,YACM;CACN,IAAI,MAAM,QAAQ,WAAW,KAAK,GAAG;EACnC,WAAW,iBAAiB,WAAW,MAAM;EAG7C,IAAI,WAAW,MAAM,MAAM,SAAS,KAAK,OAAO,iBAAiB,MAAS,GACxE,WAAW,qBAAqB,WAAW,MAAM,QAC9C,UAAU,KAAK,OAAO,gBAAgB,KAAK,CAC9C,CAAC,CAAC;EAEJ,MAAM,iBAAiB,WAAW,MAAM,QACrC,SAAS,KAAK,iBAAiB,YAAY,KAAK,iB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4B,WAAW;CAGpD,IAAI,WAAW,cAAc,QAC3B,WAAW,4BAA4B,WAAW;CAGpD,IAAI,MAAM,QAAQ,WAAW,KAAK,GAChC,WAAW,wBAAwB,WAAW,MAAM;AAExD;AAEA,SAAS,kBACP,YACA,YACM;CACN,IAAI,WAAW,cAAc,QAC3B,WAAW,oBAAoB,WAAW;CAG5C,IAAI,WAAW,WAAW,QACxB,WAAW,iBAAiB,WAAW;CAGzC,IAAI,WAAW,kBAAkB,QAC/B,WAAW,wBAAwB,WAAW;AAElD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize-error.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/normalize-error.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,OAA4C;CACzE,IAAI,UAAU,UAAa,UAAU,MACnC;CAGF,IAAI,OAAO,UAAU,UACnB,OAAO;EACL,MAAM;EACN,SAAS,aAAa,OAAO,KAAK,CAAC;CACrC;CAGF,MAAM,YAAY;CAQlB,MAAM,OAAO,WAAW,UAAU,IAAI,KAAK,WAAW,UAAU,IAAI,KAAK;CACzE,MAAM,UAAU,WAAW,UAAU,OAAO,KAAK;CACjD,MAAM,QAAQ,WAAW,UAAU,KAAK;CAKxC,MAAM,aAA6B;EACjC;EACA,SAAS,aAAa,OAAO;CAC/B;CAEA,IAAI,UAAU,QACZ,WAAW,QAAQ,aAAa,KAAK;CAGvC,IAAI,UAAU,UAAU,UAAa,UAAU,UAAU,MACvD,WAAW,QACT,OAAO,UAAU,UAAU,WACvB,OAAO,UAAU,KAAK,IACtB,aAAa,OAAO,UAAU,KAAK,CAAC;CAG5C,OAAO;AACT;;;;;AAMA,SAAS,WAAW,OAAoC;CACtD,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC9C,OAAO;AAIX"}
|
|
1
|
+
{"version":3,"file":"normalize-error.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/normalize-error.ts"],"sourcesContent":["import { redact, scrubSecrets } from \"@warlock.js/ai\";\nimport type { TraceSpanError } from \"../contracts/trace.type\";\n\n/**\n * Project a captured execution error onto the structural\n * {@link TraceSpanError} shape used on a failed / cancelled span.\n *\n * Source errors are typically `AIError` instances (every error surfaced\n * by `@warlock.js/ai` is one), but the collector never depends on the\n * concrete class — it reads only the structural surface (`name` / `code`\n * / `message` / `stack`) so a plain `Error`, an `AIError`, or any\n * thrown value all normalize identically. The result is a JSON-safe\n * plain object so it survives serialization to a backend collector\n * unchanged.\n *\n * The error `type` prefers the stable `code` (e.g. `\"RATE_LIMIT\"`) over\n * the class `name`, falling back to `name` and finally to the generic\n * `\"Error\"` so the field is always populated.\n *\n * @example\n * const spanError = normalizeError(report.error);\n * // { type: \"RATE_LIMIT\", message: \"429 Too Many Requests\", stack: \"...\" }\n */\nexport function normalizeError(error: unknown): TraceSpanError | undefined {\n if (error === undefined || error === null) {\n return undefined;\n }\n\n if (typeof error !== \"object\") {\n return {\n type: \"Error\",\n message: scrubSecrets(String(error)),\n };\n }\n\n const candidate = error as {\n code?: unknown;\n name?: unknown;\n message?: unknown;\n stack?: unknown;\n cause?: unknown;\n };\n\n const type = pickString(candidate.code) ?? pickString(candidate.name) ?? \"Error\";\n const message = pickString(candidate.message) ?? \"\";\n const stack = pickString(candidate.stack);\n\n // Scrub free-text secrets (Bearer tokens, api keys) from the message and\n // stack, and deep-redact the cause (a raw provider SDK error can carry\n // auth/cookie headers) before either is stored or exported (S4).\n const normalized: TraceSpanError = {\n type,\n message: scrubSecrets(message),\n };\n\n if (stack !== undefined) {\n normalized.stack = scrubSecrets(stack);\n }\n\n if (candidate.cause !== undefined && candidate.cause !== null) {\n normalized.cause =\n typeof candidate.cause === \"object\"\n ? redact(candidate.cause)\n : scrubSecrets(String(candidate.cause));\n }\n\n return normalized;\n}\n\n/**\n * Return the value when it is a non-empty string, otherwise `undefined`.\n * Keeps `normalizeError` from promoting empty / non-string fields.\n */\nfunction pickString(value: unknown): string | undefined {\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,OAA4C;CACzE,IAAI,UAAU,UAAa,UAAU,MACnC;CAGF,IAAI,OAAO,UAAU,UACnB,OAAO;EACL,MAAM;EACN,SAAS,aAAa,OAAO,KAAK,CAAC;CACrC;CAGF,MAAM,YAAY;CAQlB,MAAM,OAAO,WAAW,UAAU,IAAI,KAAK,WAAW,UAAU,IAAI,KAAK;CACzE,MAAM,UAAU,WAAW,UAAU,OAAO,KAAK;CACjD,MAAM,QAAQ,WAAW,UAAU,KAAK;CAKxC,MAAM,aAA6B;EACjC;EACA,SAAS,aAAa,OAAO;CAC/B;CAEA,IAAI,UAAU,QACZ,WAAW,QAAQ,aAAa,KAAK;CAGvC,IAAI,UAAU,UAAU,UAAa,UAAU,UAAU,MACvD,WAAW,QACT,OAAO,UAAU,UAAU,WACvB,OAAO,UAAU,KAAK,IACtB,aAAa,OAAO,UAAU,KAAK,CAAC;CAG5C,OAAO;AACT;;;;;AAMA,SAAS,WAAW,OAAoC;CACtD,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC9C,OAAO;AAIX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"report-to-span.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/report-to-span.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,aAAa,QAAoB,SAA4C;CAC3F,MAAM,OAAkB;EACtB,QAAQ,OAAO;EACf,SAAS,OAAO;EAChB,MAAM,OAAO;EACb,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,SAAS,OAAO;EAChB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,UAAU,OAAO,SAAS,KAAK,UAAU,aAAa,OAAO,OAAO,CAAC;CACvE;CAEA,IAAI,OAAO,gBAAg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xB,MAAM,QAAQ,SACV,OAAO,QAAQ;GAAE,MAAM,KAAK;GAAM,MAAM,KAAK;GAAM,OAAO;EAAS,CAAC,IACpE;EACJ,IAAI,UAAU,QACZ,KAAK,SAAS;CAElB;AACF;;;;;;;;;AAUA,SAAS,mBAAmB,OAA6C;CACvE,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK,GAAG;EAC7C,MAAM,MAAM,MAAM,EAAE,EAAE;EAGtB,IAFgB,OAAO,QAAQ,WAAW,IAAI,SAAS,IAAI,QAAQ,QAGjE,OAAO;CAEX;AAGF"}
|
|
1
|
+
{"version":3,"file":"report-to-span.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/report-to-span.ts"],"sourcesContent":["import type { BaseReport } from \"@warlock.js/ai\";\nimport type { TraceSpan } from \"../contracts/trace.type\";\nimport type { ContentCaptureOptions } from \"./content-capture.type\";\nimport { extractSpanAttributes } from \"./extract-span-attributes\";\nimport { normalizeError } from \"./normalize-error\";\n\n/**\n * Project one {@link BaseReport} node — and its entire subtree — into a\n * {@link TraceSpan}. Pure and recursive: identity, timing, status, and\n * the rolled-up `usage` map across 1:1 from the report; lineage maps\n * `runId → spanId`, `parentRunId → parentSpanId`, `rootRunId → traceId`;\n * children recurse in invocation order so the span tree mirrors the\n * report tree exactly.\n *\n * The error is normalized to the JSON-safe {@link\n * import(\"../contracts/trace.type\").TraceSpanError} shape only when the\n * node carried one (failed / cancelled). Primitive-specific detail that\n * has no first-class span field (trip / step / iteration counts, model\n * identity, tool trip index) is routed into the optional `attributes`\n * bag via {@link extractSpanAttributes}.\n *\n * When {@link ContentCaptureOptions.captureContent} is set, the raw\n * prompt/response (agents) and args/result (tools) are additionally\n * copied onto `span.input` / `span.output` — off by default because\n * payloads are large and often sensitive. A {@link ContentRedactor} can\n * mask each value first.\n *\n * No external lookup is needed — a `BaseReport` already carries\n * everything a span requires, so a collector can flatten a tree without\n * consulting any other source.\n *\n * @example\n * const root = reportToSpan(result.report);\n * console.log(root.spanId, root.traceId, root.children.length);\n */\nexport function reportToSpan(report: BaseReport, options?: ContentCaptureOptions): TraceSpan {\n const span: TraceSpan = {\n spanId: report.runId,\n traceId: report.rootRunId,\n name: report.name,\n type: report.type,\n status: report.status,\n startedAt: report.startedAt,\n endedAt: report.endedAt,\n duration: report.duration,\n usage: report.usage,\n children: report.children.map((child) => reportToSpan(child, options)),\n };\n\n if (report.parentRunId !== undefined) {\n span.parentSpanId = report.parentRunId;\n }\n\n if (report.sessionId !== undefined) {\n span.sessionId = report.sessionId;\n }\n\n if (report.version !== undefined) {\n span.version = report.version;\n }\n\n const error = normalizeError((report as { error?: unknown }).error);\n if (error !== undefined) {\n span.error = error;\n }\n\n const attributes = extractSpanAttributes(report);\n if (attributes !== undefined) {\n span.attributes = attributes;\n }\n\n if (options?.captureContent) {\n captureContent(span, report, options);\n }\n\n return span;\n}\n\n/** Per-primitive content fields read off a widened report node. */\ntype ContentReport = {\n input?: unknown;\n output?: unknown;\n systemPrompt?: string;\n trips?: Array<{ input?: unknown; output?: unknown }>;\n /**\n * The full assembled conversation an agent run captured when its\n * `captureMessages` option was set (core `AgentReport.messages`).\n * Present only on opted-in agent runs; absent otherwise.\n */\n messages?: unknown;\n};\n\n/**\n * Copy the node's raw content onto `span.input` / `span.output`.\n *\n * - Tools carry the call arguments + return value directly on the report\n * (`ToolCall.input` / `ToolCall.output`).\n * - Agents carry a `trips[]` history plus the resolved `systemPrompt`. The\n * input is emitted as a `[system, user]` chat array — so backends like\n * Langfuse render the full prompt as sent — or the bare user string when\n * there's no system prompt. The output is the last NON-EMPTY trip\n * `output` (the final response text); a failed / max-trips run can end on\n * a trip whose `output` is `\"\"` or tool-call-only, so we scan back for the\n * last one that carried text. Intermediate trips store a `\"[tool results]\"`\n * placeholder upstream.\n * - When {@link ContentCaptureOptions.fullHistory} is on AND the agent run\n * opted into `captureMessages` (so the report carries a `messages`\n * array), the *whole* `CapturedMessage[]` is emitted as `span.input`\n * instead of the `[system, user]` first-trip array — every role, every\n * trip. The output stays the last non-empty trip output. When `messages`\n * is absent the branch falls back to today's first-trip logic, so a run\n * that didn't opt in degrades gracefully.\n *\n * Each value is passed through the optional {@link ContentRedactor};\n * a redactor returning `undefined` drops the field. Under `fullHistory`\n * the redactor receives the full array as a single value.\n */\nfunction captureContent(span: TraceSpan, report: BaseReport, options: ContentCaptureOptions): void {\n const node = report as BaseReport & ContentReport;\n const redact = options.redactContent;\n\n let input: unknown;\n let output: unknown;\n\n if (report.type === \"tool\") {\n input = node.input;\n output = node.output;\n } else if (options.fullHistory && Array.isArray(node.messages) && node.messages.length > 0) {\n // Full-history capture: the entire assembled conversation as a single\n // input value. Output remains the agent's final response text.\n input = node.messages;\n output = Array.isArray(node.trips) ? lastNonEmptyOutput(node.trips) : undefined;\n } else if (Array.isArray(node.trips) && node.trips.length > 0) {\n const userInput = node.trips[0]?.input;\n // Emit a [system, user] chat array when the agent carried a system\n // prompt, so backends (Langfuse) render the full prompt as sent;\n // otherwise keep the bare user string.\n input =\n typeof node.systemPrompt === \"string\" && node.systemPrompt.length > 0\n ? [\n { role: \"system\", content: node.systemPrompt },\n { role: \"user\", content: userInput },\n ]\n : userInput;\n output = lastNonEmptyOutput(node.trips);\n }\n\n if (input !== undefined) {\n const value = redact\n ? redact(input, { name: span.name, type: span.type, field: \"input\" })\n : input;\n if (value !== undefined) {\n span.input = value;\n }\n }\n\n if (output !== undefined) {\n const value = redact\n ? redact(output, { name: span.name, type: span.type, field: \"output\" })\n : output;\n if (value !== undefined) {\n span.output = value;\n }\n }\n}\n\n/**\n * The last trip output that actually carries text — the agent's final\n * response on the happy path. A failed or max-trips run can end on a trip\n * whose `output` is `\"\"` or tool-call-only, so we scan backwards for the\n * last trip that produced text rather than blindly taking the final trip\n * (which would surface an empty string). Returns `undefined` when no trip\n * produced any output.\n */\nfunction lastNonEmptyOutput(trips: Array<{ output?: unknown }>): unknown {\n for (let i = trips.length - 1; i >= 0; i -= 1) {\n const out = trips[i]?.output;\n const hasText = typeof out === \"string\" ? out.length > 0 : out !== undefined;\n\n if (hasText) {\n return out;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,aAAa,QAAoB,SAA4C;CAC3F,MAAM,OAAkB;EACtB,QAAQ,OAAO;EACf,SAAS,OAAO;EAChB,MAAM,OAAO;EACb,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB,SAAS,OAAO;EAChB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,UAAU,OAAO,SAAS,KAAK,UAAU,aAAa,OAAO,OAAO,CAAC;CACvE;CAEA,IAAI,OAAO,gBAAgB,QACzB,KAAK,eAAe,OAAO;CAG7B,IAAI,OAAO,cAAc,QACvB,KAAK,YAAY,OAAO;CAG1B,IAAI,OAAO,YAAY,QACrB,KAAK,UAAU,OAAO;CAGxB,MAAM,QAAQ,eAAgB,OAA+B,KAAK;CAClE,IAAI,UAAU,QACZ,KAAK,QAAQ;CAGf,MAAM,aAAa,sBAAsB,MAAM;CAC/C,IAAI,eAAe,QACjB,KAAK,aAAa;CAGpB,IAAI,SAAS,gBACX,eAAe,MAAM,QAAQ,OAAO;CAGtC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAS,eAAe,MAAiB,QAAoB,SAAsC;CACjG,MAAM,OAAO;CACb,MAAM,SAAS,QAAQ;CAEvB,IAAI;CACJ,IAAI;CAEJ,IAAI,OAAO,SAAS,QAAQ;EAC1B,QAAQ,KAAK;EACb,SAAS,KAAK;CAChB,OAAO,IAAI,QAAQ,eAAe,MAAM,QAAQ,KAAK,QAAQ,KAAK,KAAK,SAAS,SAAS,GAAG;EAG1F,QAAQ,KAAK;EACb,SAAS,MAAM,QAAQ,KAAK,KAAK,IAAI,mBAAmB,KAAK,KAAK,IAAI;CACxE,OAAO,IAAI,MAAM,QAAQ,KAAK,KAAK,KAAK,KAAK,M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KAAK;EACd,UAAU,KAAK;EACf,OAAO,KAAK;CACd;CAEA,IAAI,KAAK,cAAc,QACrB,MAAM,YAAY,KAAK;CAGzB,IAAI,OAAO,wBAAwB,QACjC,MAAM,sBAAsB,OAAO;CAGrC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"report-to-trace.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/report-to-trace.ts"],"sourcesContent":["import type { BaseReport } from \"@warlock.js/ai\";\nimport type { Trace } from \"../contracts/trace.type\";\nimport type { ContentCaptureOptions } from \"./content-capture.type\";\nimport { normalizeError } from \"./normalize-error\";\nimport { reportToSpan } from \"./report-to-span\";\n\n/**\n * Project an outermost {@link BaseReport} (one whole `.execute()` /\n * `.invoke()` run) into a {@link Trace} — the root {@link\n * import(\"../contracts/trace.type\").TraceSpan} plus the trace-wide\n * rollups exporters need without re-walking the tree.\n *\n * The trace-level identity and rollups all read off the root span the\n * projection already built (`traceId`, `usage`, timing), so the trace\n * envelope never disagrees with its own root. `reportSchemaVersion` is\n * mirrored from the root report when present (it is stamped only on\n * root nodes upstream) so exporters can branch on the source shape.\n *\n * Pure — the same input always yields the same trace. The collector\n * exposes this as `toTrace` so callers can inspect the normalized shape\n * without dispatching to exporters.\n *\n * The optional `rootError` threads the failing run's envelope error\n * (`BaseResult.error`) onto the root span — a fallback for callers that\n * hold the result envelope (the `attach`/middleware path). Root primitives\n * now also stamp their terminal error onto the report itself\n * (`BaseReport.error`), so the observe path — which delivers only the\n * report, never the envelope — still surfaces a failed root's error.\n * `rootError` is applied only when the projected root span carries none of\n * its own; the subtree projection stays pure (each child surfaces its own\n * report-level error, if any).\n *\n * @example\n * const trace = reportToTrace(result.report, result.error);\n * console.log(trace.traceId, trace.usage.total, trace.duration);\n */\nexport function reportToTrace(\n report: BaseReport,\n rootError?: unknown,\n options?: ContentCaptureOptions,\n): Trace {\n const root = reportToSpan(report, options);\n\n if (root.error === undefined) {\n const error = normalizeError(rootError);\n\n if (error !== undefined) {\n root.error = error;\n }\n }\n\n const trace: Trace = {\n traceId: root.traceId,\n root,\n startedAt: root.startedAt,\n endedAt: root.endedAt,\n duration: root.duration,\n usage: root.usage,\n };\n\n if (root.sessionId !== undefined) {\n trace.sessionId = root.sessionId;\n }\n\n if (report.reportSchemaVersion !== undefined) {\n trace.reportSchemaVersion = report.reportSchemaVersion;\n }\n\n return trace;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,cACd,QACA,WACA,SACO;CACP,MAAM,OAAO,aAAa,QAAQ,OAAO;CAEzC,IAAI,KAAK,UAAU,QAAW;EAC5B,MAAM,QAAQ,eAAe,SAAS;EAEtC,IAAI,UAAU,QACZ,KAAK,QAAQ;CAEjB;CAEA,MAAM,QAAe;EACnB,SAAS,KAAK;EACd;EACA,WAAW,KAAK;EAChB,SAAS,KAAK;EACd,UAAU,KAAK;EACf,OAAO,KAAK;CACd;CAEA,IAAI,KAAK,cAAc,QACrB,MAAM,YAAY,KAAK;CAGzB,IAAI,OAAO,wBAAwB,QACjC,MAAM,sBAAsB,OAAO;CAGrC,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trace-subscriptions.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/trace-subscriptions.ts"],"mappings":";AAKA,MAAM,4BAAY,IAAI,IAAmB;;;;;;;;AASzC,SAAgB,gBAAgB,UAAqC;CACnE,MAAM,gBAA+B,UAAU,SAAS,KAAK;CAC7D,UAAU,IAAI,YAAY;CAC1B,aAAa;EACX,UAAU,OAAO,YAAY;CAC/B;AACF;;AAGA,SAAgB,aAAa,OAAoB;CAC/C,KAAK,MAAM,YAAY,WACrB,IAAI;EACF,AAAK,QAAQ,QAAQ,SAAS,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CACtD,QAAQ,CAER;AAEJ"}
|
|
1
|
+
{"version":3,"file":"trace-subscriptions.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/collector/trace-subscriptions.ts"],"sourcesContent":["import type { Trace } from \"../contracts/trace.type\";\n\n/** Receives a finalized trace in the collecting call's async context. Treat it as read-only. */\nexport type TraceListener = (trace: Trace) => void | Promise<void>;\n\nconst listeners = new Set<TraceListener>();\n\n/**\n * Subscribe to traces from every built-in collector in this process, including\n * collectors created before subscribing. No replay or retention. Called before\n * exporter dispatch, so adapters can read request-local context synchronously.\n * Listener failures are isolated; async listeners are not awaited. The returned\n * disposer removes only this subscription. Does not enable flow observation.\n */\nexport function subscribeTraces(listener: TraceListener): () => void {\n const subscription: TraceListener = (trace) => listener(trace);\n listeners.add(subscription);\n return () => {\n listeners.delete(subscription);\n };\n}\n\n/** Internal collector notification; pure toTrace projections never publish. */\nexport function publishTrace(trace: Trace): void {\n for (const listener of listeners) {\n try {\n void Promise.resolve(listener(trace)).catch(() => {});\n } catch {\n // A dashboard or adapter must never fail the originating AI run.\n }\n }\n}\n"],"mappings":";AAKA,MAAM,4BAAY,IAAI,IAAmB;;;;;;;;AASzC,SAAgB,gBAAgB,UAAqC;CACnE,MAAM,gBAA+B,UAAU,SAAS,KAAK;CAC7D,UAAU,IAAI,YAAY;CAC1B,aAAa;EACX,UAAU,OAAO,YAAY;CAC/B;AACF;;AAGA,SAAgB,aAAa,OAAoB;CAC/C,KAAK,MAAM,YAAY,WACrB,IAAI;EACF,AAAK,QAAQ,QAAQ,SAAS,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CACtD,QAAQ,CAER;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply-panoptic-config.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/config/apply-panoptic-config.ts"],"mappings":";;;;;;;;AA2BA,IAAI;;AAGJ,MAAa,mCAAmC;;;;;;;;;;;;;;;;;;;;;AAsBhD,SAAgB,oBAAoB,QAA+B;CACjE,IAAI,WAAW,QACb;CAIF,cAAc,QAAQ,OAAO,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,OAFiB,OAAO,oBAAoB,WAAW,kBAAkB,CAAC,CAE5D;AACjC"}
|
|
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 = type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AExB,CAAC;EACD,MAAM,MAAM;CACd,CAAC,CAAC,CACD,YAAY,CAEb,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"dashboard.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/dashboard.ts"],"sourcesContent":["import { createServer } from \"node:http\";\nimport type { TraceStoreContract } from \"../store/trace-store.contract\";\nimport type { DashboardHandle, DashboardOptions } from \"./dashboard.type\";\nimport { createRequestHandler } from \"./serve\";\n\nconst DEFAULT_PORT = 4319;\nconst DEFAULT_HOST = \"127.0.0.1\";\nconst DEFAULT_TITLE = \"Panoptic\";\n\n/**\n * Start the local Panoptic dashboard over a {@link TraceStoreContract} —\n * a zero-dependency `node:http` server that serves a read-only JSON API\n * and one self-contained HTML page polling it. The store is the live\n * object the collector fills, so each poll reflects the latest completed\n * traces with no extra wiring.\n *\n * This is a low-level building block. The documented path is\n * `ai.config({ panoptic: { dashboard } })`, which constructs (or reuses)\n * the store and calls this for you. Use it directly only when you manage\n * the store yourself.\n *\n * Binds loopback-only by default (`127.0.0.1`) so prompt content is never\n * exposed to the LAN. Pass `port: 0` for an ephemeral port — the resolved\n * port comes back on the handle. A port already in use rejects with a\n * clear, actionable `Error` rather than the raw `EADDRINUSE`.\n *\n * @example\n * const store = createInMemoryTraceStore();\n * const handle = await dashboard(store, { port: 4319, open: true });\n * console.log(handle.url); // http://127.0.0.1:4319/\n * // ...later:\n * await handle.close();\n */\nexport function dashboard(\n store: TraceStoreContract,\n options: DashboardOptions = {},\n): Promise<DashboardHandle> {\n const port = options.port ?? DEFAULT_PORT;\n const host = options.host ?? DEFAULT_HOST;\n const title = options.title ?? DEFAULT_TITLE;\n const basePath = normalizeBasePath(options.basePath);\n\n // Secure-by-default off loopback (S4): a non-loopback bind without an\n // auth token would expose raw prompt content to the network, so refuse\n // to start rather than silently exposing it.\n if (!isLoopbackHost(host) && !options.authToken) {\n return Promise.reject(\n new Error(\n `Panoptic dashboard: binding to a non-loopback host (\"${host}\") requires an \\`authToken\\` ` +\n \"(the dashboard exposes raw prompt content). Pass `authToken`, or bind to 127.0.0.1.\",\n ),\n );\n }\n\n const allowedHosts = (options.allowedHosts ?? defaultAllowedHosts(host)).map((h) =>\n h.toLowerCase(),\n );\n\n const handler = createRequestHandler(store, {\n basePath,\n title,\n authToken: options.authToken,\n allowedHosts,\n evaluate: options.evaluate,\n });\n const server = createServer(handler);\n\n return new Promise<DashboardHandle>((resolve, reject) => {\n const onError = (error: NodeJS.ErrnoException): void => {\n server.off(\"error\", onError);\n\n if (error.code === \"EADDRINUSE\") {\n reject(\n new Error(\n `Panoptic dashboard: port ${port} in use; pass { port: 0 } for an ephemeral port`,\n ),\n );\n\n return;\n }\n\n reject(error);\n };\n\n server.on(\"error\", onError);\n\n server.listen(port, host, () => {\n server.off(\"error\", onError);\n\n const address = server.address();\n const resolvedPort = typeof address === \"object\" && address !== null ? address.port : port;\n const url = `http://${host}:${resolvedPort}${basePath}`;\n\n if (options.open) {\n openBrowser(url);\n }\n\n resolve({\n url,\n port: resolvedPort,\n close(): Promise<void> {\n return new Promise<void>((closeResolve, closeReject) => {\n server.close((closeError) => {\n if (closeError) {\n closeReject(closeError);\n\n return;\n }\n\n closeResolve();\n });\n });\n },\n });\n });\n });\n}\n\n/** Loopback hosts the dashboard may bind without an auth token. */\nfunction isLoopbackHost(host: string): boolean {\n const h = host.toLowerCase();\n return h === \"127.0.0.1\" || h === \"::1\" || h === \"[::1]\" || h === \"localhost\";\n}\n\n/**\n * Default `Host` allowlist for a given bind host. A loopback bind accepts\n * the loopback names a browser would send; a non-loopback bind defaults to\n * just the bound host (callers can widen via `allowedHosts`).\n */\nfunction defaultAllowedHosts(host: string): string[] {\n if (isLoopbackHost(host)) {\n return [\"localhost\", \"127.0.0.1\", \"[::1]\", \"::1\"];\n }\n return [host];\n}\n\n/**\n * Normalize a caller `basePath` to a leading-and-trailing-slash form the\n * router can prefix routes with. `undefined` / `\"\"` → `\"/\"`.\n */\nfunction normalizeBasePath(basePath?: string): string {\n if (basePath === undefined || basePath.length === 0 || basePath === \"/\") {\n return \"/\";\n }\n\n const withLeading = basePath.startsWith(\"/\") ? basePath : `/${basePath}`;\n\n return withLeading.endsWith(\"/\") ? withLeading : `${withLeading}/`;\n}\n\n/**\n * Best-effort open of the default browser at `url`. Fire-and-forget and\n * fully swallowed — failing to open a browser must never reject the\n * dashboard start. Uses the platform's native opener via a lazy\n * `node:child_process` import so the dependency is paid only when\n * `open: true`.\n */\nfunction openBrowser(url: string): void {\n void import(\"node:child_process\")\n .then(({ spawn }) => {\n const command =\n process.platform === \"win32\" ? \"cmd\" : process.platform === \"darwin\" ? \"open\" : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n\n const child = spawn(command, args, { stdio: \"ignore\", detached: true });\n child.on(\"error\", () => {\n // Swallow — opening a browser is best-effort.\n });\n child.unref();\n })\n .catch(() => {\n // Swallow — opening a browser is best-effort.\n });\n}\n"],"mappings":";;;;AAKA,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;AA0BtB,SAAgB,UACd,OACA,UAA4B,CAAC,GACH;CAC1B,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,WAAW,kBAAkB,QAAQ,QAAQ;CAKnD,IAAI,CAAC,eAAe,IAAI,KAAK,CAAC,QAAQ,WACpC,OAAO,QAAQ,uBACb,IAAI,MACF,wDAAwD,KAAK,mHAE/D,CACF;CAGF,MAAM,gBAAgB,QAAQ,gBAAgB,oBAAoB,IAAI,EAAC,CAAE,KAAK,MAC5E,EAAE,YAAY,CAChB;CAEA,MAAM,UAAU,qBAAqB,OAAO;EAC1C;EACA;EACA,WAAW,QAAQ;EACnB;EACA,UAAU,QAAQ;CACpB,CAAC;CACD,MAAM,SAAS,aAAa,OAAO;CAEnC,OAAO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I,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"}
|
|
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,Q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
+
{"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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K,MAAM,SAAS,KAAK,UAAU;EACjC,MAAM,WAAW,YAAY,KAAK;EAClC,IAAI,WAAW,KACb,MAAM;CAEV;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"trace-filter.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/trace-filter.ts"],"sourcesContent":["import type { ReportStatus, ReportType } from \"@warlock.js/ai\";\nimport type { Trace, TraceSpan } from \"../contracts/trace.type\";\n\n/**\n * Client-side trace-list filter criteria. The dashboard polls the full\n * trace list every 2s and narrows it in the browser with these — search\n * box, filter chips, and the errors-only header toggle all feed one\n * {@link TraceFilter}. Kept as a pure, framework-free module so the exact\n * matching rules are unit-tested here and the inlined dashboard JS in\n * {@link import(\"./ui.html\").dashboardHtml} mirrors them 1:1.\n *\n * Every field is optional — an absent field is \"don't care\". An empty\n * filter therefore matches every trace.\n */\nexport type TraceFilter = {\n /**\n * Free-text needle matched case-insensitively against a trace's root\n * span name and session id. Whitespace-trimmed; an empty/blank string\n * is treated as absent.\n */\n text?: string;\n /**\n * Restrict to these terminal statuses (root span status). Empty array\n * is treated as \"don't care\" (matches every status).\n */\n statuses?: ReportStatus[];\n /**\n * Restrict to these executable types (root span type). Empty array is\n * treated as \"don't care\".\n */\n types?: ReportType[];\n /**\n * Exact session-id chip. When set, only traces whose `sessionId`\n * equals this value match. Distinct from {@link TraceFilter.text},\n * which is a fuzzy substring across name + session.\n */\n sessionId?: string;\n /**\n * Exact prompt chip — a `name@version` key (see {@link tracePromptKey}).\n * When set, only traces whose root span resolved that exact named prompt\n * version match. Mirrors {@link TraceFilter.sessionId} but over the\n * prompt-version-linkage attributes the collector stamps on agent spans.\n */\n promptKey?: string;\n /**\n * Errors-only header toggle. When `true`, only `failed` / `cancelled`\n * traces match — independent of (and intersected with) `statuses`.\n */\n errorsOnly?: boolean;\n};\n\n/** Statuses the errors-only toggle keeps. */\nconst ERROR_STATUSES: readonly ReportStatus[] = [\"failed\", \"cancelled\"] as const;\n\n/**\n * Span-attribute keys the collector stamps with prompt-version linkage when\n * an agent ran against a *named* `ai.prompts` builder. Read here (not\n * imported) so this pure module stays decoupled from the collector.\n */\nconst PROMPT_NAME_ATTR = \"agent.promptName\";\nconst PROMPT_VERSION_ATTR = \"agent.promptVersion\";\n\n/**\n * The `name@version` prompt key a trace falls under, read from its root\n * span's prompt-version-linkage attributes (`agent.promptName` /\n * `agent.promptVersion`). Returns `undefined` when the run carried no named\n * prompt (raw-string / anonymous / no prompt), so callers can bucket those\n * under a synthetic \"no prompt\" key or skip them.\n *\n * The version is included so two runs of the same prompt name at different\n * versions are distinct keys — that is the whole point of the linkage: to\n * group / filter by the *exact* prompt revision that produced a run.\n */\nexport function tracePromptKey(trace: Trace): string | undefined {\n const attributes = trace.root.attributes;\n\n if (attributes === undefined) {\n return undefined;\n }\n\n const name = attributes[PROMPT_NAME_ATTR];\n\n if (typeof name !== \"string\" || name.length === 0) {\n return undefined;\n }\n\n const version = attributes[PROMPT_VERSION_ATTR];\n const versionLabel = typeof version === \"string\" && version.length > 0 ? version : \"1\";\n\n return `${name}@${versionLabel}`;\n}\n\n/**\n * Does a single trace pass the given filter? Pure predicate — all\n * conditions are ANDed; an unset field never excludes. Used by\n * {@link filterTraces} and mirrored by the dashboard's inlined JS.\n */\nexport function matchesFilter(trace: Trace, filter: TraceFilter): boolean {\n const root = trace.root;\n\n if (filter.errorsOnly === true && !ERROR_STATUSES.includes(root.status)) {\n return false;\n }\n\n if (filter.statuses !== undefined && filter.statuses.length > 0) {\n if (!filter.statuses.includes(root.status)) {\n return false;\n }\n }\n\n if (filter.types !== undefined && filter.types.length > 0) {\n if (!filter.types.includes(root.type)) {\n return false;\n }\n }\n\n if (filter.sessionId !== undefined && filter.sessionId.length > 0) {\n if (trace.sessionId !== filter.sessionId) {\n return false;\n }\n }\n\n if (filter.promptKey !== undefined && filter.promptKey.length > 0) {\n if (tracePromptKey(trace) !== filter.promptKey) {\n return false;\n }\n }\n\n const text = filter.text?.trim().toLowerCase();\n if (text !== undefined && text.length > 0) {\n const haystack = `${root.name} ${trace.sessionId ?? \"\"}`.toLowerCase();\n if (!haystack.includes(text)) {\n return false;\n }\n }\n\n return true;\n}\n\n/** Narrow a trace list to those matching the filter, order preserved. */\nexport function filterTraces(traces: Trace[], filter: TraceFilter): Trace[] {\n return traces.filter((trace) => matchesFilter(trace, filter));\n}\n\n/**\n * The grouping key a trace falls under when the list is grouped by\n * session. Traces without a `sessionId` collapse into one synthetic\n * \"(no session)\" bucket so they remain visible.\n */\nexport const NO_SESSION_KEY = \"(no session)\";\n\n/** One session bucket — its key plus the traces under it, order preserved. */\nexport type SessionGroup = {\n /** The `sessionId`, or {@link NO_SESSION_KEY} for sessionless traces. */\n sessionId: string;\n /** Traces in this group, in the order they appeared in the input. */\n traces: Trace[];\n};\n\n/**\n * Group an (already filtered, newest-first) trace list by session id,\n * preserving first-seen order of both the groups and the traces within\n * each. Sessionless traces bucket under {@link NO_SESSION_KEY}.\n */\nexport function groupBySession(traces: Trace[]): SessionGroup[] {\n const order: string[] = [];\n const byKey = new Map<string, Trace[]>();\n\n for (const trace of traces) {\n const key = trace.sessionId ?? NO_SESSION_KEY;\n let bucket = byKey.get(key);\n\n if (bucket === undefined) {\n bucket = [];\n byKey.set(key, bucket);\n order.push(key);\n }\n\n bucket.push(trace);\n }\n\n return order.map((sessionId) => ({ sessionId, traces: byKey.get(sessionId) ?? [] }));\n}\n\n/**\n * The grouping key a trace falls under when the list is grouped by prompt\n * version. Runs that resolved no named prompt collapse into one synthetic\n * \"(no prompt)\" bucket so they remain visible.\n */\nexport const NO_PROMPT_KEY = \"(no prompt)\";\n\n/** One prompt-version bucket — its `name@version` key plus its traces. */\nexport type PromptGroup = {\n /** The `name@version` key, or {@link NO_PROMPT_KEY} for unlinked traces. */\n promptKey: string;\n /** Traces in this group, in the order they appeared in the input. */\n traces: Trace[];\n};\n\n/**\n * Group an (already filtered, newest-first) trace list by prompt version —\n * the `name@version` key {@link tracePromptKey} derives from each run's\n * prompt-version-linkage attributes. Preserves first-seen order of both the\n * groups and the traces within each. Runs with no named prompt bucket under\n * {@link NO_PROMPT_KEY}.\n *\n * The dashboard offers this as a second group-by dimension beside session,\n * so a reviewer can see every run of \"support@2\" together and compare its\n * cost / failure rate against \"support@3\".\n */\nexport function groupByPrompt(traces: Trace[]): PromptGroup[] {\n const order: string[] = [];\n const byKey = new Map<string, Trace[]>();\n\n for (const trace of traces) {\n const key = tracePromptKey(trace) ?? NO_PROMPT_KEY;\n let bucket = byKey.get(key);\n\n if (bucket === undefined) {\n bucket = [];\n byKey.set(key, bucket);\n order.push(key);\n }\n\n bucket.push(trace);\n }\n\n return order.map((promptKey) => ({ promptKey, traces: byKey.get(promptKey) ?? [] }));\n}\n\n/**\n * The grouping key a trace falls under when the list is grouped by root\n * type. `root.type` is always present, so this is only a defensive\n * fallback for a malformed trace with no typed root.\n */\nexport const NO_TYPE_KEY = \"(no type)\";\n\n/** One root-type bucket — its type discriminator plus its traces. */\nexport type TypeGroup = {\n /** The root span's `type` (e.g. `agent` / `workflow` / `planner`), or {@link NO_TYPE_KEY}. */\n type: string;\n /** Traces in this group, in the order they appeared in the input. */\n traces: Trace[];\n};\n\n/**\n * Group an (already filtered, newest-first) trace list by root type —\n * the `agent` / `workflow` / `supervisor` / `orchestrator` / `planner` /\n * `tool` / `batch` / `callback` discriminator on each trace's root span.\n * Preserves first-seen order of both the groups and the traces within each.\n *\n * The dashboard offers this as the coarsest group-by dimension beside\n * session and prompt: when a benchmark floods the flat list with hundreds\n * of one primitive (e.g. standalone `agent` runs), this collapses them\n * behind a per-type header so the structural primitives (the lone planner,\n * the team, the supervisors) are one click away instead of a scroll past.\n */\nexport function groupByType(traces: Trace[]): TypeGroup[] {\n const order: string[] = [];\n const byKey = new Map<string, Trace[]>();\n\n for (const trace of traces) {\n const key = trace.root.type || NO_TYPE_KEY;\n let bucket = byKey.get(key);\n\n if (bucket === undefined) {\n bucket = [];\n byKey.set(key, bucket);\n order.push(key);\n }\n\n bucket.push(trace);\n }\n\n return order.map((type) => ({ type, traces: byKey.get(type) ?? [] }));\n}\n\n/** One row of the per-type aggregate-stats panel. */\nexport type TypeStat = {\n /** Root type discriminator, or {@link NO_TYPE_KEY}. */\n type: string;\n /** Number of traces of this type. */\n count: number;\n /** Traces whose status is `failed` / `cancelled`. */\n failed: number;\n /** `failed / count` in `[0, 1]`. */\n failRate: number;\n /** Median (p50) root duration in ms. */\n p50: number;\n /** p95 root duration in ms. */\n p95: number;\n /** Summed `usage.total` tokens across the bucket. */\n tokens: number;\n /** Summed per-trace USD cost across the bucket. */\n cost: number;\n};\n\n/**\n * Nearest-rank percentile of `values` at `p` (0–100). Returns 0 for an\n * empty input and sorts a copy so the caller's array is left untouched.\n */\nexport function percentile(values: number[], p: number): number {\n if (values.length === 0) {\n return 0;\n }\n\n const sorted = values.slice().sort((a, b) => a - b);\n const rank = Math.ceil((p / 100) * sorted.length) - 1;\n const index = Math.min(Math.max(rank, 0), sorted.length - 1);\n\n return sorted[index];\n}\n\n/**\n * One trace's total USD cost: its explicit root-usage cost when priced,\n * else the rollup of its subtree. Mirrors the dashboard's `traceCost` so the\n * stats panel and the trace rows agree to the cent.\n */\nexport function traceCost(trace: Trace): number {\n const own = costSumObj(trace.usage.cost);\n return own > 0 ? own : rollupCost(trace.root);\n}\n\n/**\n * Aggregate an (already filtered) trace list into one {@link TypeStat} row\n * per root type — count, failure rate, p50/p95 latency, total tokens, total\n * cost — preserving first-seen type order. Powers the dashboard's per-type\n * stats panel; computed over the same filtered list the trace view shows, so\n * the panel always reflects the active filters.\n */\nexport function aggregateByType(traces: Trace[]): TypeStat[] {\n const order: string[] = [];\n const byKey = new Map<string, Trace[]>();\n\n for (const trace of traces) {\n const key = trace.root.type || NO_TYPE_KEY;\n let bucket = byKey.get(key);\n\n if (bucket === undefined) {\n bucket = [];\n byKey.set(key, bucket);\n order.push(key);\n }\n\n bucket.push(trace);\n }\n\n return order.map((type) => {\n const bucket = byKey.get(type) ?? [];\n const durations = bucket.map((trace) => trace.duration);\n let failed = 0;\n let tokens = 0;\n let cost = 0;\n\n for (const trace of bucket) {\n if (ERROR_STATUSES.includes(trace.root.status)) {\n failed += 1;\n }\n\n tokens += trace.usage.total ?? 0;\n cost += traceCost(trace);\n }\n\n return {\n type,\n count: bucket.length,\n failed,\n failRate: bucket.length > 0 ? failed / bucket.length : 0,\n p50: percentile(durations, 50),\n p95: percentile(durations, 95),\n tokens,\n cost,\n };\n });\n}\n\n/**\n * Sum every priced lane of a usage cost object into one USD number.\n * Mirrors the dashboard's `costSumObj` so heatmap intensities computed\n * here match what the page renders.\n */\nfunction costSumObj(cost: TraceSpan[\"usage\"][\"cost\"]): number {\n if (cost === undefined) {\n return 0;\n }\n\n return (\n (cost.input ?? 0) +\n (cost.output ?? 0) +\n (cost.cachedInput ?? 0) +\n (cost.cacheWrite ?? 0) +\n (cost.cachedOutput ?? 0) +\n (cost.reasoning ?? 0)\n );\n}\n\n/**\n * Rollup-aware subtree cost: a node's own cost when it carries one\n * (it already rolls up its trips), otherwise the sum of its children.\n * Avoids double-counting wrapper nodes (workflow/supervisor roots carry\n * tokens but no cost). Mirrors the dashboard's `rollupCost`.\n */\nexport function rollupCost(span: TraceSpan): number {\n const own = costSumObj(span.usage.cost);\n if (own > 0) {\n return own;\n }\n\n let sum = 0;\n for (const child of span.children) {\n sum += rollupCost(child);\n }\n\n return sum;\n}\n\n/**\n * Heatmap intensity in `[0, 1]` for a node's `rollupCost` relative to the\n * trace's most-expensive node. The dashboard tints each tree node's left\n * accent by this. `max <= 0` (a free trace) yields `0` for every node so\n * the heatmap simply stays cold rather than dividing by zero.\n */\nexport function heatIntensity(nodeCost: number, maxCost: number): number {\n if (maxCost <= 0 || nodeCost <= 0) {\n return 0;\n }\n\n const ratio = nodeCost / maxCost;\n\n return ratio > 1 ? 1 : ratio;\n}\n\n/**\n * The largest single-node {@link rollupCost} anywhere in a span tree —\n * the denominator for {@link heatIntensity}. Walks the whole subtree.\n */\nexport function maxNodeCost(root: TraceSpan): number {\n let max = rollupCost(root);\n\n for (const child of root.children) {\n const childMax = maxNodeCost(child);\n if (childMax > max) {\n max = childMax;\n }\n }\n\n return max;\n}\n"],"mappings":";;AAoDA,MAAM,iBAA0C,CAAC,UAAU,WAAW;;;;;;AAOtE,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;;;;;;;;;;;;AAa5B,SAAgB,eAAe,OAAkC;CAC/D,MAAM,aAAa,MAAM,KAAK;CAE9B,IAAI,eAAe,QACjB;CAGF,MAAM,OAAO,WAAW;CAExB,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAC9C;CAGF,MAAM,UAAU,WAAW;CAG3B,OAAO,GAAG,KAAK,GAFM,OAAO,YAAY,YAAY,QAAQ,SAAS,IAAI,UAAU;AAGrF;;;;;;AAOA,SAAgB,cAAc,OAAc,QAA8B;CACxE,MAAM,OAAO,MAAM;CAEnB,IAAI,OAAO,eAAe,QAAQ,CAAC,eAAe,SAAS,KAAK,MAAM,GACpE,OAAO;CAGT,IAAI,OAAO,aAAa,UAAa,OAAO,SAAS,SAAS,GAC5D;MAAI,CAAC,OAAO,SAAS,SAAS,KAAK,MAAM,GACvC,OAAO;CACT;CAGF,IAAI,OAAO,UAAU,UAAa,OAAO,MAAM,SAAS,GACtD;MAAI,CAAC,OAAO,MAAM,SAAS,KAAK,IAAI,GAClC,OAAO;CACT;CAGF,IAAI,OAAO,cAAc,UAAa,OAAO,UAAU,SAAS,GAC9D;MAAI,MAAM,cAAc,OAAO,WAC7B,OAAO;CACT;CAGF,IAAI,OAAO,cAAc,UAAa,OAAO,UAAU,SAAS,GAC9D;MAAI,eAAe,KAAK,MAAM,OAAO,WACnC,OAAO;CACT;CAGF,MAAM,OAAO,OAAO,MAAM,KAAK,CAAC,CAAC,YAAY;CAC7C,IAAI,SAAS,UAAa,KAAK,SAAS,GAEtC;MAAI,CADa,GAAG,KAAK,KAAK,GAAG,MAAM,aAAa,KAAK,YAC7C,CAAC,CAAC,S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;GAC1B,IAAI,eAAe,SAAS,MAAM,KAAK,MAAM,GAC3C,UAAU;GAGZ,UAAU,MAAM,MAAM,SAAS;GAC/B,QAAQ,UAAU,KAAK;EACzB;EAEA,OAAO;GACL;GACA,OAAO,OAAO;GACd;GACA,UAAU,OAAO,SAAS,IAAI,SAAS,OAAO,SAAS;GACvD,KAAK,WAAW,WAAW,EAAE;GAC7B,KAAK,WAAW,WAAW,EAAE;GAC7B;GACA;EACF;CACF,CAAC;AACH;;;;;;AAOA,SAAS,WAAW,MAA0C;CAC5D,IAAI,SAAS,QACX,OAAO;CAGT,QACG,KAAK,SAAS,MACd,KAAK,UAAU,MACf,KAAK,eAAe,MACpB,KAAK,cAAc,MACnB,KAAK,gBAAgB,MACrB,KAAK,aAAa;AAEvB;;;;;;;AAQA,SAAgB,WAAW,MAAyB;CAClD,MAAM,MAAM,WAAW,KAAK,MAAM,IAAI;CACtC,IAAI,MAAM,GACR,OAAO;CAGT,IAAI,MAAM;CACV,KAAK,MAAM,SAAS,KAAK,UACvB,OAAO,WAAW,KAAK;CAGzB,OAAO;AACT;;;;;;;AAQA,SAAgB,cAAc,UAAkB,SAAyB;CACvE,IAAI,WAAW,KAAK,YAAY,GAC9B,OAAO;CAGT,MAAM,QAAQ,WAAW;CAEzB,OAAO,QAAQ,IAAI,IAAI;AACzB;;;;;AAMA,SAAgB,YAAY,MAAyB;CACnD,IAAI,MAAM,WAAW,IAAI;CAEzB,KAAK,MAAM,SAAS,KAAK,UAAU;EACjC,MAAM,WAAW,YAAY,KAAK;EAClC,IAAI,WAAW,KACb,MAAM;CAEV;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trace-summary.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/trace-summary.ts"],"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"}
|
|
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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ui.html.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/ui.html.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,cACd,UACA,OACA,kBAA2B,OAC3B,8BAAsC,IAC9B;CACR,MAAM,UAAU,GAAG,SAAS;CAC5B,MAAM,YAAY,WAAW,KAAK;CAElC,OAAO;;;;;SAKA,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BA+MQ,sBAAsB;QACzC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAwCJ,KAAK,UAAU,OAAO,EAAE;2BACX,KAAK,UAAU,eAAe,EAAE;;wCAEnB,sBAAsB,2BAA2B,EAAE;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0rC3F;;AAGA,SAAS,WAAW,OAAuB;CACzC,OAAO,MACJ,QAAQ,MAAM,OAAO,CAAC,CACtB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,QAAQ,CAAC,CACvB,QAAQ,MAAM,OAAO;AAC1B;;;;;;;;;;;;;;AAeA,SAAS,sBAAsB,OAAuB;CACpD,OAAO,MACJ,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,KAAK,UAAU,IAAI,CAAC,CAAC,CACnC,KAAK,UAAU;AACpB"}
|
|
1
|
+
{"version":3,"file":"ui.html.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/dashboard/ui.html.ts"],"sourcesContent":["import { WARLOCK_LOGO_DATA_URI } from \"./warlock-logo\";\n\n/**\n * Build the single self-contained dashboard HTML page. No external\n * assets, no bundler, no framework — one inlined string that polls the\n * read-only JSON API (`{basePath}api/aggregate`, `{basePath}api/traces`,\n * `{basePath}api/traces/:id`) and renders:\n *\n * - the {@link TraceAggregate} headline counts (traces / completed /\n * failed / cancelled / tokens in·out·total / cost);\n * - a newest-first trace list as clickable master rows, each led by a\n * colour-coded, title-cased type label (Supervisor / Agent / Tool / …);\n * - a two-pane drawer: a collapsible call tree on the left (the nested\n * span hierarchy) and the selected node's detail on the right — rich\n * input/output, token breakdown, and a metadata panel (session id,\n * ids, version, attributes).\n *\n * Span input/output is rendered structurally (chat bubbles / key-value /\n * Markdown), durations in seconds, tokens as ↓input · ↑output · total.\n * Theme is light / dark / system (persisted to localStorage). All UI\n * state — selected trace, selected span, collapsed nodes — lives in JS,\n * NOT the DOM, so the 2s poll never disturbs an open drawer.\n *\n * The 2s poll reads the newest trace summaries (`api/traces`: no span\n * tree, no captured content); opening a trace fetches its full tree from\n * `api/traces/:id` and re-fetches it only when its summary changes.\n *\n * The list is filterable entirely client-side over the polled traces: a\n * free-text search (name + session), status / type / session filter\n * chips, an \"errors only\" header toggle, and an optional group-by-session\n * view with collapsible headers. Each tree node and trace row carries a\n * cost heatmap accent scaled to the trace's most expensive node, with a\n * small legend. The drawer's left pane toggles between the nested call\n * TREE and a Gantt TIMELINE (span offset from root start + duration,\n * critical path highlighted). The selected trace and span are reflected\n * in the URL hash (`#trace=&span=`) and re-opened from it on load — so a\n * drawer view is shareable/bookmarkable. A live socket tail is a noted\n * follow-up; this pass stays on the 2s poll.\n *\n * `basePath` and `title` are baked in at serve time. The page is\n * intentionally dependency-free vanilla JS so it works offline.\n *\n * @param basePath Normalized mount path ending in `/` (e.g. `\"/\"`).\n * @param title Header title shown in the page.\n */\nexport function dashboardHtml(\n basePath: string,\n title: string,\n evaluateEnabled: boolean = false,\n evaluateDefaultInstructions: string = \"\",\n): string {\n const apiBase = `${basePath}api`;\n const safeTitle = escapeHtml(title);\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${safeTitle}</title>\n<script>\n(function () {\n try {\n var m = localStorage.getItem(\"panoptic-theme\") || \"system\";\n var light = m === \"light\" || (m === \"system\" && window.matchMedia && window.matchMedia(\"(prefers-color-scheme: light)\").matches);\n document.documentElement.setAttribute(\"data-theme\", light ? \"light\" : \"dark\");\n } catch (e) {}\n})();\n</script>\n<style>\n :root {\n color-scheme: dark;\n --bg: #0b0d10; --surface: #101317; --surface2: #14171c; --panel: #0d1014;\n --border: #23272e; --border2: #2d333b;\n --text: #e6e8eb; --text2: #adbac7; --dim: #8b949e;\n --sel-bg: #0f1722; --sel-border: #316dca;\n --ty-agent: #539bf5; --ty-tool: #c297ff; --ty-model: #4cc2b0; --ty-prim: #e3b341; --ty-other: #adbac7;\n --tok-in: #58a6ff; --tok-out: #3fb950; --tok-total: #b899ff; --cost: #e3b341;\n --ok: #56d364; --ok-bg: #0f2e1d; --fail: #f85149; --fail-bg: #3a1416; --cancel: #d29922; --cancel-bg: #332701; --other: #8b949e; --other-bg: #1c2128;\n --code-bg: #0b0d10; --inline-bg: #1c2128; --link: #539bf5;\n }\n :root[data-theme=\"light\"] {\n color-scheme: light;\n --bg: #ffffff; --surface: #f6f8fa; --surface2: #eef1f4; --panel: #ffffff;\n --border: #d0d7de; --border2: #afb8c1;\n --text: #1f2328; --text2: #3b4350; --dim: #636c76;\n --sel-bg: #ddf4ff; --sel-border: #0969da;\n --ty-agent: #0969da; --ty-tool: #8250df; --ty-model: #0f7d6b; --ty-prim: #9a6700; --ty-other: #57606a;\n --tok-in: #0969da; --tok-out: #1a7f37; --tok-total: #8250df; --cost: #9a6700;\n --ok: #1a7f37; --ok-bg: #dafbe1; --fail: #cf222e; --fail-bg: #ffebe9; --cancel: #9a6700; --cancel-bg: #fff8c5; --other: #57606a; --other-bg: #eaeef2;\n --code-bg: #f6f8fa; --inline-bg: #eaeef2; --link: #0969da;\n }\n * { box-sizing: border-box; }\n body { margin: 0; font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; background: var(--bg); color: var(--text); }\n header { padding: 14px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; }\n header img.logo { height: 26px; width: 26px; display: block; flex: none; }\n header h1 { font-size: 16px; margin: 0; font-weight: 600; }\n header .meta { color: var(--dim); font-size: 12px; }\n .theme { margin-left: auto; display: flex; gap: 2px; border: 1px solid var(--border); border-radius: 8px; padding: 2px; }\n .theme button { background: transparent; border: none; color: var(--dim); cursor: pointer; font-size: 14px; line-height: 1; padding: 4px 8px; border-radius: 6px; }\n .theme button:hover { color: var(--text); }\n .theme button.active { background: var(--surface2); color: var(--text); }\n .stats { display: flex; flex-wrap: wrap; gap: 10px; padding: 14px 20px; border-bottom: 1px solid var(--border); }\n .stat { background: var(--surface2); border: 1px solid var(--border); border-radius: 8px; padding: 8px 12px; min-width: 84px; }\n .stat .label { color: var(--dim); font-size: 11px; text-transform: uppercase; letter-spacing: .04em; }\n .stat .value { font-size: 18px; font-weight: 600; }\n main { padding: 12px 20px 40px; }\n\n .trace-row { border: 1px solid var(--border); border-radius: 8px; margin-bottom: 8px; background: var(--surface); padding: 9px 12px; display: flex; align-items: center; gap: 9px; cursor: pointer; transition: background .12s ease, border-color .12s ease; }\n .trace-row:hover { background: var(--surface2); border-color: var(--border2); }\n .trace-row.selected { border-color: var(--sel-border); background: var(--sel-bg); }\n .rname { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .rprompt { font-size: 11px; color: var(--ty-agent); border: 1px solid var(--border2); border-radius: 6px; padding: 1px 6px; white-space: nowrap; }\n .rright { margin-left: auto; display: flex; align-items: center; gap: 6px; white-space: nowrap; }\n .chev { color: var(--dim); font-size: 16px; font-style: normal; }\n\n .tylabel { font-weight: 600; flex: none; }\n .ty-agent { color: var(--ty-agent); } .ty-tool { color: var(--ty-tool); } .ty-model { color: var(--ty-model); } .ty-prim { color: var(--ty-prim); } .ty-other { color: var(--ty-other); }\n .badge { font-size: 11px; padding: 2px 8px; border-radius: 999px; font-weight: 600; flex: none; }\n .badge.completed { background: var(--ok-bg); color: var(--ok); }\n .badge.failed { background: var(--fail-bg); color: var(--fail); }\n .badge.cancelled { background: var(--cancel-bg); color: var(--cancel); }\n .badge.other { background: var(--other-bg); color: var(--other); }\n .sdot { width: 7px; height: 7px; border-radius: 999px; display: inline-block; flex: none; }\n .sdot-completed { background: var(--ok); } .sdot-failed { background: var(--fail); } .sdot-cancelled { background: var(--cancel); } .sdot-other { background: var(--other); }\n .dim { color: var(--dim); font-size: 12px; }\n .tok { white-space: nowrap; font-size: 12px; }\n .tok-in { color: var(--tok-in); } .tok-out { color: var(--tok-out); } .tok-total { color: var(--tok-total); }\n .cost { color: var(--cost); font-weight: 600; font-size: 12px; white-space: nowrap; }\n\n .io-body { margin-bottom: 6px; }\n .piol { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; margin: 11px 0 3px; }\n .messages { display: flex; flex-direction: column; gap: 8px; }\n .msg-collapse { border: 1px solid var(--border); border-radius: 8px; background: var(--surface); }\n .msg-collapse > summary { cursor: pointer; padding: 7px 10px; list-style: none; font-size: 12px; display: flex; align-items: center; gap: 6px; }\n .msg-collapse > summary::-webkit-details-marker { display: none; }\n .msg-collapse > summary::before { content: \"\\\\25B8\"; color: var(--dim); }\n .msg-collapse[open] > summary::before { content: \"\\\\25BE\"; }\n .msg-collapse[open] > summary { border-bottom: 1px solid var(--border); }\n .msg-collapse .messages { padding: 8px; }\n .msg-collapse .msg-count { font-weight: 600; color: var(--text2); }\n .msg { border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: var(--surface); }\n .msg-role { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .05em; padding: 4px 10px; color: var(--text2); background: var(--surface2); border-bottom: 1px solid var(--border); }\n .msg-role.role-system { color: var(--cancel); } .msg-role.role-user { color: var(--ty-agent); } .msg-role.role-assistant { color: var(--ok); } .msg-role.role-tool { color: var(--ty-tool); }\n .msg-content { padding: 8px 10px; }\n .kv { display: grid; grid-template-columns: max-content 1fr; gap: 2px 12px; align-items: start; }\n .kv-row { display: contents; }\n .kv-k { color: var(--dim); font-family: ui-monospace, monospace; font-size: 12px; padding: 2px 0; white-space: nowrap; }\n .kv-v { font-size: 13px; min-width: 0; overflow: auto; padding: 1px 0; word-break: break-word; }\n .part { border-left: 2px solid var(--border2); padding-left: 8px; margin: 4px 0; }\n .part-label { font-size: 11px; text-transform: uppercase; color: var(--dim); margin-bottom: 2px; }\n .md-h { font-weight: 700; margin: 8px 0 4px; }\n .md-h1 { font-size: 16px; } .md-h2 { font-size: 14px; } .md-h3 { font-size: 13px; color: var(--text2); } .md-h4 { font-size: 12px; color: var(--dim); }\n .md-p { margin: 4px 0; white-space: pre-wrap; word-break: break-word; }\n .io-body ul, .msg-content ul { margin: 4px 0; padding-left: 18px; }\n pre.code { background: var(--code-bg); border: 1px solid var(--border); border-radius: 6px; padding: 8px; overflow: auto; max-height: 320px; font-size: 12px; white-space: pre; margin: 6px 0; }\n pre.mini { background: var(--code-bg); border: 1px solid var(--border); border-radius: 6px; padding: 6px 8px; overflow: auto; max-height: 200px; font-size: 12px; margin: 0; }\n code { background: var(--inline-bg); border-radius: 4px; padding: 1px 4px; font-family: ui-monospace, monospace; font-size: 12px; }\n a { color: var(--link); }\n .empty { color: var(--dim); padding: 30px; text-align: center; }\n\n .backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.5); opacity: 0; pointer-events: none; transition: opacity .18s ease; z-index: 40; }\n .backdrop.open { opacity: 1; pointer-events: auto; }\n .drawer { position: fixed; top: 0; right: 0; bottom: 0; width: min(760px, 96vw); background: var(--panel); border-left: 1px solid var(--border); transform: translateX(100%); transition: transform .18s ease; z-index: 50; display: flex; flex-direction: column; box-shadow: -16px 0 40px rgba(0,0,0,.4); }\n .drawer.open { transform: translateX(0); }\n .drawer-head { padding: 12px 14px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 9px; flex-wrap: wrap; }\n .drawer-close { margin-left: auto; background: transparent; border: 1px solid var(--border); color: var(--dim); border-radius: 6px; cursor: pointer; font-size: 13px; line-height: 1; padding: 5px 9px; }\n .drawer-close:hover { color: var(--text); border-color: var(--border2); }\n .drawer-body { flex: 1; overflow: hidden; }\n .dsplit { display: flex; height: 100%; }\n .dtree { flex: 0 0 44%; overflow: auto; padding: 8px 6px; border-right: 1px solid var(--border); }\n .ddetail { flex: 1; overflow: auto; padding: 10px 14px; min-width: 0; }\n .tnode { display: flex; align-items: center; gap: 7px; padding: 5px 7px; border-radius: 6px; cursor: pointer; font-size: 13px; border: 1px solid transparent; }\n .tnode:hover { background: var(--surface); }\n .tnode.selected { background: var(--sel-bg); border-color: var(--sel-border); }\n .tname { color: var(--text2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .tmeta { margin-left: auto; color: var(--dim); font-size: 12px; white-space: nowrap; }\n .twisty { color: var(--dim); font-size: 11px; width: 12px; text-align: center; flex: none; }\n .tkids { margin-left: 10px; padding-left: 9px; border-left: 1px solid var(--border); }\n .crumb { font-size: 12px; color: var(--dim); margin-bottom: 6px; word-break: break-all; }\n .crumb .sep { color: var(--border2); }\n .dhead-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 4px; }\n .meta-sec { margin-top: 14px; border-top: 1px solid var(--border); padding-top: 8px; }\n .meta-title { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; color: var(--dim); margin-bottom: 6px; }\n\n /* Toolbar: search box + filter chips over the trace list. */\n .toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 20px; border-bottom: 1px solid var(--border); }\n .search { flex: 1 1 220px; min-width: 160px; background: var(--surface2); border: 1px solid var(--border); color: var(--text); border-radius: 8px; padding: 7px 10px; font: inherit; }\n .search:focus { outline: none; border-color: var(--sel-border); }\n .chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }\n .chip { background: var(--surface2); border: 1px solid var(--border); color: var(--text2); border-radius: 999px; padding: 4px 11px; font-size: 12px; font-weight: 600; cursor: pointer; transition: background .12s ease, border-color .12s ease, color .12s ease; }\n .chip:hover { color: var(--text); border-color: var(--border2); }\n .chip.active { background: var(--sel-bg); border-color: var(--sel-border); color: var(--text); }\n .chip-clear { color: var(--dim); border-style: dashed; }\n .chip-group { display: inline-flex; gap: 6px; align-items: center; }\n .chip-group .gl { font-size: 11px; text-transform: uppercase; letter-spacing: .04em; color: var(--dim); }\n .toggle { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; font-size: 12px; color: var(--text2); user-select: none; }\n .toggle input { accent-color: var(--sel-border); }\n .toggle select { background: var(--surface2); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 2px 6px; font-size: 12px; cursor: pointer; }\n .toggle select:hover { border-color: var(--border2); }\n\n /* Session grouping headers. */\n .sgroup { margin-bottom: 10px; }\n .sgroup-head { display: flex; align-items: center; gap: 8px; padding: 6px 10px; border-radius: 8px; background: var(--surface2); border: 1px solid var(--border); cursor: pointer; margin-bottom: 6px; }\n .sgroup-head:hover { border-color: var(--border2); }\n .sgroup-tw { color: var(--dim); font-size: 11px; width: 12px; text-align: center; flex: none; }\n .sgroup-id { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .sgroup-count { margin-left: auto; color: var(--dim); font-size: 12px; }\n .sgroup-body { padding-left: 6px; }\n\n /* Per-type aggregate stats panel (a CSS-grid table above the trace list). */\n .stats-table { margin: 0 0 14px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; font-size: 12px; }\n .strow { display: grid; grid-template-columns: 1.5fr 0.7fr 1fr 0.8fr 0.8fr 1fr 1fr; gap: 10px; align-items: center; padding: 6px 12px; border-bottom: 1px solid var(--border); }\n .strow:last-child { border-bottom: none; }\n .strow.sthead { background: var(--surface2); color: var(--dim); font-weight: 600; }\n .strow > span { text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .strow > .stc-type { text-align: left; }\n .stc-fail.fail { color: var(--fail); }\n\n /* Cost heatmap: a left accent bar tinted by relative rollup cost. */\n .trace-row { position: relative; }\n .tnode { position: relative; }\n .heat { position: absolute; left: 0; top: 3px; bottom: 3px; width: 3px; border-radius: 2px; background: var(--cost); }\n\n /* Timeline / waterfall view in the drawer. */\n .dview { display: flex; gap: 4px; padding: 6px 8px; border-bottom: 1px solid var(--border); }\n .dview button { background: transparent; border: 1px solid var(--border); color: var(--dim); cursor: pointer; font-size: 12px; padding: 4px 10px; border-radius: 6px; }\n .dview button:hover { color: var(--text); }\n .dview button.active { background: var(--surface2); color: var(--text); border-color: var(--border2); }\n .legend { margin-left: auto; display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--dim); }\n .legend .grad { width: 64px; height: 8px; border-radius: 4px; background: linear-gradient(90deg, var(--surface2), var(--cost)); border: 1px solid var(--border); }\n .gantt { padding: 8px 10px; }\n\n /* Evaluate — the drawer's one write action (config-gated). */\n .eval-btn { background: transparent; border: 1px solid var(--border); color: var(--text2); cursor: pointer; font-size: 12px; padding: 4px 10px; border-radius: 6px; margin: 10px 0 0; }\n .eval-btn:hover:not(:disabled) { color: var(--text); border-color: var(--border2); }\n .eval-btn:disabled { opacity: .6; cursor: default; }\n .eval-panel { margin-top: 8px; padding: 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface2); }\n .eval-panel textarea { width: 100%; min-height: 64px; background: var(--panel); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 8px; font: 12px/1.5 ui-sans-serif, system-ui, sans-serif; resize: vertical; }\n .eval-actions { display: flex; align-items: center; gap: 8px; margin-top: 8px; }\n .eval-error { color: var(--fail); font-size: 12px; }\n .eval-result { margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border); font-size: 12px; }\n .eval-score { font-weight: 600; }\n .eval-issues { margin: 6px 0 0; padding-left: 18px; }\n .grow { display: flex; align-items: center; gap: 8px; padding: 2px 0; font-size: 12px; cursor: pointer; border-radius: 4px; }\n .grow:hover { background: var(--surface); }\n .grow.selected { background: var(--sel-bg); }\n .glabel { flex: 0 0 38%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text2); }\n .gtrack { position: relative; flex: 1; height: 14px; background: var(--surface2); border-radius: 4px; overflow: hidden; }\n .gbar { position: absolute; top: 2px; bottom: 2px; border-radius: 3px; background: var(--ty-agent); min-width: 2px; }\n .gbar.crit { background: var(--fail); }\n .gbar.bar-completed { background: var(--ty-agent); } .gbar.bar-failed { background: var(--fail); } .gbar.bar-cancelled { background: var(--cancel); } .gbar.bar-other { background: var(--other); }\n .gdur { flex: 0 0 auto; color: var(--dim); white-space: nowrap; min-width: 44px; text-align: right; }\n .gantt-legend { display: flex; gap: 14px; margin-top: 8px; font-size: 11px; color: var(--dim); }\n .gantt-legend .ck { display: inline-flex; align-items: center; gap: 5px; }\n .gantt-legend .sw { width: 12px; height: 8px; border-radius: 2px; display: inline-block; }\n\n @media (max-width: 560px) {\n .dsplit { flex-direction: column; }\n .dtree { flex: none; max-height: 42vh; border-right: none; border-bottom: 1px solid var(--border); }\n .glabel { flex-basis: 30%; }\n }\n</style>\n</head>\n<body>\n<header>\n <img class=\"logo\" src=\"${WARLOCK_LOGO_DATA_URI}\" alt=\"Warlock\" />\n <h1>${safeTitle}</h1>\n <span class=\"meta\" id=\"meta\">connecting…</span>\n <div class=\"theme\" id=\"theme\" role=\"group\" aria-label=\"Theme\" style=\"margin-left:auto\">\n <button type=\"button\" data-theme-set=\"light\" title=\"Light\" aria-label=\"Light theme\">☀</button>\n <button type=\"button\" data-theme-set=\"dark\" title=\"Dark\" aria-label=\"Dark theme\">☾</button>\n <button type=\"button\" data-theme-set=\"system\" title=\"System\" aria-label=\"System theme\">◐</button>\n </div>\n</header>\n<div class=\"stats\" id=\"stats\"></div>\n<div class=\"toolbar\" id=\"toolbar\">\n <input class=\"search\" id=\"search\" type=\"search\" placeholder=\"Search name or session…\" aria-label=\"Search traces\" autocomplete=\"off\" />\n <div class=\"chips\" id=\"status-chips\" role=\"group\" aria-label=\"Filter by status\"></div>\n <div class=\"chips\" id=\"type-chips\" role=\"group\" aria-label=\"Filter by type\"></div>\n <div class=\"chips\" id=\"session-chips\" role=\"group\" aria-label=\"Filter by session\"></div>\n <div class=\"chips\" id=\"prompt-chips\" role=\"group\" aria-label=\"Filter by prompt version\"></div>\n <label class=\"toggle\" id=\"group-wrap\" title=\"Group the trace list (mutually exclusive)\">\n Group\n <select id=\"group-by\" aria-label=\"Group the trace list\">\n <option value=\"\">None</option>\n <option value=\"session\">Session</option>\n <option value=\"prompt\">Prompt</option>\n <option value=\"type\">Type</option>\n </select>\n </label>\n <label class=\"toggle\" id=\"stats-wrap\" title=\"Show a per-type aggregate stats panel (count, failure rate, p50/p95 latency, tokens, cost)\">\n <input type=\"checkbox\" id=\"show-stats\" /> Stats\n </label>\n <button class=\"chip chip-clear\" id=\"clear-filters\" type=\"button\" title=\"Clear all filters\">Clear</button>\n</div>\n<div id=\"stats-panel\"></div>\n<main id=\"traces\"><div class=\"empty\">Loading…</div></main>\n\n<div class=\"backdrop\" id=\"backdrop\"></div>\n<aside class=\"drawer\" id=\"drawer\" aria-hidden=\"true\" aria-label=\"Trace detail\">\n <div class=\"drawer-head\" id=\"drawer-head\"></div>\n <div class=\"drawer-body\" id=\"drawer-body\"></div>\n</aside>\n\n<script>\n(function () {\n var API = ${JSON.stringify(apiBase)};\n var EVALUATE_ENABLED = ${JSON.stringify(evaluateEnabled)};\n var BT = String.fromCharCode(96);\n var EVALUATE_DEFAULT_INSTRUCTIONS = ${encodeForInlineScript(evaluateDefaultInstructions)};\n\n // Carry the ?token= the page itself was loaded with onto every\n // subsequent poll as an Authorization header — otherwise the API calls\n // below inherit no auth and 401 forever once authToken is configured\n // (the initial page load is the only request the URL's query string\n // naturally reaches; the server only honors ?token= on that one route,\n // see serve.ts). The token itself is kept in its own nested closure,\n // not a plain var sitting alongside the rest of this file's top-level\n // state, so it isn't trivially reachable from other code sharing this\n // script's outer scope; only the fetchAuthed function it returns is.\n var fetchAuthed = (function () {\n var TOKEN = new URLSearchParams(window.location.search).get(\"token\");\n return function fetchAuthed(url, options) {\n var opts = options || {};\n var headers = opts.headers || {};\n if (TOKEN) headers = Object.assign({}, headers, { Authorization: \"Bearer \" + TOKEN });\n return fetch(url, Object.assign({}, opts, { headers: headers }));\n };\n })();\n\n var state = {\n traces: [], selectedId: null, selectedSpanId: null, collapsed: {}, sig: null,\n detail: null, // full trace of the open drawer (GET /traces/:id)\n loadingId: null, // trace id whose full tree is being fetched\n // Client-side filter state (search box + chips + errors-only header toggle).\n filter: { text: \"\", statuses: {}, types: {}, sessionId: null, promptKey: null, errorsOnly: false },\n groupBySession: false, // session-grouping list toggle\n groupByPrompt: false, // prompt-version-grouping list toggle\n groupByType: false, // root-type-grouping list toggle\n showStats: false, // per-type aggregate-stats panel toggle (independent of grouping)\n collapsedGroups: {}, // collapsed group headers (session, prompt, or type)\n view: \"tree\", // drawer left pane: \"tree\" | \"timeline\"\n hashApplied: false, // guards one-time deep-link open on load\n evaluate: {} // per-span evaluate UI state, keyed by spanId\n };\n\n var STATUS_FILTERS = [\"completed\", \"failed\", \"cancelled\"];\n var TYPE_FILTERS = [\"agent\", \"tool\", \"model\", \"supervisor\", \"team\", \"workflow\", \"orchestrator\", \"planner\", \"batch\", \"callback\"];\n var ERROR_STATUSES = { failed: 1, cancelled: 1, incomplete: 1 };\n var NO_SESSION_KEY = \"(no session)\";\n var NO_PROMPT_KEY = \"(no prompt)\";\n var NO_TYPE_KEY = \"(no type)\";\n\n var statusClass = function (s) {\n if (s === \"completed\" || s === \"failed\" || s === \"cancelled\") return s;\n if (s === \"incomplete\") return \"failed\";\n return \"other\";\n };\n var esc = function (v) {\n return String(v).replace(/[&<>\"']/g, function (c) {\n return { \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\", \"'\": \"'\" }[c];\n });\n };\n var num = function (n) { return (n == null ? 0 : n).toLocaleString(); };\n var fmt = function (v) {\n if (v == null) return \"\";\n if (typeof v === \"string\") return v;\n try { return JSON.stringify(v, null, 2); } catch (e) { return String(v); }\n };\n\n function dur(ms) {\n if (ms == null) return \"—\";\n if (ms >= 1000) return (ms / 1000).toFixed(1) + \"s\";\n if (ms >= 1) return Math.round(ms) + \"ms\";\n return ms.toFixed(1) + \"ms\";\n }\n\n function tokens(u) {\n if (!u) return \"\";\n var i = u.input || 0, o = u.output || 0, t = (u.total != null) ? u.total : (i + o);\n if (i === 0 && o === 0 && t === 0) return \"\"; // nothing to show — hide the row\n return '<span class=\"tok\">'\n + '<span class=\"tok-in\" title=\"input tokens\">↓ ' + num(i) + \"</span> \"\n + '<span class=\"tok-out\" title=\"output tokens\">↑ ' + num(o) + \"</span> \"\n + '<span class=\"tok-total\" title=\"total tokens\">' + num(t) + \" total</span></span>\";\n }\n\n var TYPE_LABELS = {\n agent: \"Agent\", tool: \"Tool\", model: \"Model\", supervisor: \"Supervisor\",\n workflow: \"Workflow\", orchestrator: \"Orchestrator\", team: \"Team\",\n planner: \"Planner\", prompt: \"Prompt\", guardrail: \"Guardrail\"\n };\n var PRIMITIVES = { supervisor: 1, workflow: 1, orchestrator: 1, team: 1, planner: 1 };\n function typeClass(type) {\n if (PRIMITIVES[type]) return \"ty-prim\";\n if (type === \"agent\") return \"ty-agent\";\n if (type === \"tool\") return \"ty-tool\";\n if (type === \"model\") return \"ty-model\";\n return \"ty-other\";\n }\n function typeLabel(type) {\n var t = type || \"node\";\n var label = TYPE_LABELS[t] || (t.charAt(0).toUpperCase() + t.slice(1));\n return '<span class=\"tylabel ' + typeClass(t) + '\">' + esc(label) + \"</span>\";\n }\n // Plain-text (no span wrapper) capitalized labels for bare-text sites —\n // group headers, filter-chip labels — where the colored typeLabel span is\n // not wanted. Underlying keys/classes/filter values stay raw lowercase.\n function typeText(type) {\n var t = type || \"node\";\n return TYPE_LABELS[t] || (t.charAt(0).toUpperCase() + t.slice(1));\n }\n function statusText(s) {\n return s ? String(s).charAt(0).toUpperCase() + String(s).slice(1) : s;\n }\n function statusDot(s) { return '<span class=\"sdot sdot-' + statusClass(s) + '\" title=\"' + esc(s) + '\"></span>'; }\n\n function findTrace(id) {\n for (var i = 0; i < state.traces.length; i++) if (state.traces[i].traceId === id) return state.traces[i];\n return null;\n }\n function findSpan(span, id) {\n if (span.spanId === id) return span;\n var k = span.children || [];\n for (var i = 0; i < k.length; i++) { var r = findSpan(k[i], id); if (r) return r; }\n return null;\n }\n function findPath(span, id, acc) {\n var p = (acc || []).concat([span]);\n if (span.spanId === id) return p;\n var k = span.children || [];\n for (var i = 0; i < k.length; i++) { var r = findPath(k[i], id, p); if (r) return r; }\n return null;\n }\n function countSpans(span) {\n var n = 1, k = span.children || [];\n for (var i = 0; i < k.length; i++) n += countSpans(k[i]);\n return n;\n }\n // Works on a list summary (spanCount) and on a full trace (counted).\n function traceSig(t) {\n var spans = t.spanCount != null ? t.spanCount : countSpans(t.root);\n return t.root.status + \"|\" + spans + \"|\" + t.duration + \"|\" + (t.usage && t.usage.total);\n }\n // Sum every priced lane of a cost object into one USD number.\n function costSumObj(c) {\n if (!c) return 0;\n return (c.input || 0) + (c.output || 0) + (c.cachedInput || 0) + (c.cacheWrite || 0) + (c.cachedOutput || 0) + (c.reasoning || 0);\n }\n // The cost a single span directly carries (on its rolled-up usage).\n function usageCost(usage) { return usage ? costSumObj(usage.cost) : 0; }\n // Rollup-aware subtree cost: take a node's own cost when it has one\n // (it already rolls up its trips); otherwise sum the children. This\n // avoids double-counting on wrapper nodes (workflow/supervisor roots\n // carry tokens but no cost, so we descend to the priced agent/model).\n function rollupCost(span) {\n var own = usageCost(span.usage);\n if (own > 0) return own;\n var sum = 0;\n (span.children || []).forEach(function (c) { sum += rollupCost(c); });\n return sum;\n }\n function traceCost(t) {\n if (typeof t.totalCost === \"number\") return t.totalCost; // list summary: computed server-side\n var explicit = costSumObj(t.cost);\n return explicit > 0 ? explicit : rollupCost(t.root);\n }\n // Format a USD amount; tiny per-node costs need more decimals to read.\n function money(n) {\n if (!n) return \"$0\";\n return \"$\" + (n < 0.01 ? n.toFixed(6) : n.toFixed(4));\n }\n\n // --- Client-side filtering / grouping / heatmap ----------------------\n // These mirror the pure, unit-tested helpers in trace-filter.ts. Keep\n // the two in sync: trace-filter.ts is the spec, this is its inlined twin.\n function anySelected(map) {\n for (var k in map) { if (map[k]) return true; }\n return false;\n }\n function matchesFilter(t) {\n var f = state.filter, root = t.root;\n if (f.errorsOnly && !ERROR_STATUSES[root.status]) return false;\n if (anySelected(f.statuses) && !f.statuses[root.status]) return false;\n if (anySelected(f.types) && !f.types[root.type]) return false;\n if (f.sessionId && t.sessionId !== f.sessionId) return false;\n if (f.promptKey && tracePromptKey(t) !== f.promptKey) return false;\n var text = (f.text || \"\").trim().toLowerCase();\n if (text) {\n var hay = (String(root.name) + \" \" + (t.sessionId || \"\")).toLowerCase();\n if (hay.indexOf(text) === -1) return false;\n }\n return true;\n }\n function filteredTraces() {\n var out = [];\n for (var i = 0; i < state.traces.length; i++) if (matchesFilter(state.traces[i])) out.push(state.traces[i]);\n return out;\n }\n function groupBySession(list) {\n var order = [], byKey = {};\n for (var i = 0; i < list.length; i++) {\n var key = list[i].sessionId || NO_SESSION_KEY;\n if (!byKey[key]) { byKey[key] = []; order.push(key); }\n byKey[key].push(list[i]);\n }\n return order.map(function (k) { return { sessionId: k, traces: byKey[k] }; });\n }\n // Group by prompt version (name@version) — the second group-by dimension\n // beside session. Mirrors groupByPrompt in trace-filter.ts. Unlinked runs\n // bucket under NO_PROMPT_KEY so they stay visible.\n function groupByPrompt(list) {\n var order = [], byKey = {};\n for (var i = 0; i < list.length; i++) {\n var key = tracePromptKey(list[i]) || NO_PROMPT_KEY;\n if (!byKey[key]) { byKey[key] = []; order.push(key); }\n byKey[key].push(list[i]);\n }\n return order.map(function (k) { return { groupKey: k, traces: byKey[k] }; });\n }\n // Group by root type (agent/workflow/supervisor/planner/…) — the coarsest\n // group-by dimension. Mirrors groupByType in trace-filter.ts. root.type is\n // always present, so the NO_TYPE_KEY bucket is only a defensive fallback.\n function typeGroups(list) {\n var order = [], byKey = {};\n for (var i = 0; i < list.length; i++) {\n var key = (list[i].root && list[i].root.type) || NO_TYPE_KEY;\n if (!byKey[key]) { byKey[key] = []; order.push(key); }\n byKey[key].push(list[i]);\n }\n return order.map(function (k) { return { groupKey: k, traces: byKey[k] }; });\n }\n // Inlined twins of percentile + aggregateByType in trace-filter.ts (the\n // spec). Power the per-type stats panel from the same filtered list the\n // trace view renders, so the panel honors active filters with no API call.\n function percentile(values, p) {\n if (!values.length) return 0;\n var sorted = values.slice().sort(function (a, b) { return a - b; });\n var rank = Math.ceil((p / 100) * sorted.length) - 1;\n var index = Math.min(Math.max(rank, 0), sorted.length - 1);\n return sorted[index];\n }\n function aggregateByType(list) {\n var order = [], byKey = {};\n for (var i = 0; i < list.length; i++) {\n var key = (list[i].root && list[i].root.type) || NO_TYPE_KEY;\n if (!byKey[key]) { byKey[key] = []; order.push(key); }\n byKey[key].push(list[i]);\n }\n return order.map(function (k) {\n var bucket = byKey[k];\n var durations = [], failed = 0, tokens = 0, cost = 0;\n for (var j = 0; j < bucket.length; j++) {\n var t = bucket[j];\n durations.push(t.duration);\n if (ERROR_STATUSES[t.root.status]) failed += 1;\n tokens += (t.usage && t.usage.total) || 0;\n cost += traceCost(t);\n }\n return {\n type: k, count: bucket.length, failed: failed,\n failRate: bucket.length ? failed / bucket.length : 0,\n p50: percentile(durations, 50), p95: percentile(durations, 95),\n tokens: tokens, cost: cost\n };\n });\n }\n // Per-type aggregate panel above the trace list. Honors the active filters\n // (computed over filteredTraces) and re-renders on every poll/filter tick.\n function renderStatsPanel() {\n var host = document.getElementById(\"stats-panel\");\n if (!host) return;\n var stats = state.showStats ? aggregateByType(filteredTraces()) : [];\n if (!stats.length) { host.innerHTML = \"\"; return; }\n var head = '<div class=\"strow sthead\">'\n + '<span class=\"stc-type\">Type</span><span>Count</span><span>Failed</span>'\n + '<span>p50</span><span>p95</span><span>Tokens</span><span>Cost</span></div>';\n var rows = stats.map(function (s) {\n var failTxt = s.failed\n ? s.failed + \" (\" + Math.round(s.failRate * 100) + \"%)\"\n : \"0\";\n return '<div class=\"strow\">'\n + '<span class=\"stc-type\">' + typeLabel(s.type) + \"</span>\"\n + '<span>' + num(s.count) + \"</span>\"\n + '<span class=\"stc-fail' + (s.failed ? \" fail\" : \"\") + '\">' + failTxt + \"</span>\"\n + '<span class=\"dim\">' + dur(s.p50) + \"</span>\"\n + '<span class=\"dim\">' + dur(s.p95) + \"</span>\"\n + '<span>' + num(s.tokens) + \"</span>\"\n + '<span class=\"cost\">' + money(s.cost) + \"</span>\"\n + \"</div>\";\n }).join(\"\");\n host.innerHTML = '<div class=\"stats-table\">' + head + rows + \"</div>\";\n }\n // Largest single-node rollup cost in a subtree — heatmap denominator.\n function maxNodeCost(span) {\n var max = rollupCost(span);\n (span.children || []).forEach(function (c) { var m = maxNodeCost(c); if (m > max) max = m; });\n return max;\n }\n // Intensity in [0,1] of a node's cost vs the trace max. Free trace → 0.\n function heatIntensity(nodeCost, maxCost) {\n if (maxCost <= 0 || nodeCost <= 0) return 0;\n var r = nodeCost / maxCost;\n return r > 1 ? 1 : r;\n }\n // The distinct sessionIds present across the polled traces, first-seen\n // order, capped so the chip row never overflows the toolbar.\n function presentSessions() {\n var seen = {}, out = [];\n for (var i = 0; i < state.traces.length && out.length < 12; i++) {\n var s = state.traces[i].sessionId;\n if (s && !seen[s]) { seen[s] = 1; out.push(s); }\n }\n return out;\n }\n // The root types actually present in the polled traces — so the type filter\n // chips show only what exists (no dead \"Tool\"/\"Model\"/\"Batch\"/… chips), in\n // canonical TYPE_FILTERS order. An active-but-aged-out selection stays so\n // the filter is never stranded with no chip to clear it.\n function presentTypes() {\n var seen = {};\n for (var i = 0; i < state.traces.length; i++) {\n var t = state.traces[i].root && state.traces[i].root.type;\n if (t) seen[t] = 1;\n }\n for (var k in state.filter.types) { if (state.filter.types[k]) seen[k] = 1; }\n var out = [];\n for (var j = 0; j < TYPE_FILTERS.length; j++) {\n if (seen[TYPE_FILTERS[j]]) { out.push(TYPE_FILTERS[j]); delete seen[TYPE_FILTERS[j]]; }\n }\n for (var x in seen) { out.push(x); }\n return out;\n }\n // The distinct prompt name@version keys present across the polled traces,\n // first-seen order, capped so the chip row never overflows the toolbar.\n function presentPrompts() {\n var seen = {}, out = [];\n for (var i = 0; i < state.traces.length && out.length < 12; i++) {\n var p = tracePromptKey(state.traces[i]);\n if (p && !seen[p]) { seen[p] = 1; out.push(p); }\n }\n return out;\n }\n\n // (S5) Markdown link URLs come from captured prompt/tool text — attacker-\n // influenced content — so only http:, https:, mailto: and relative/anchor\n // URLs may become an href; javascript:, data:, vbscript:, etc. must not.\n // The check runs on the URL as the browser will act on it: undo the\n // entities esc() introduced (the HTML parser decodes them exactly once in\n // the attribute), strip the control chars / whitespace browsers ignore\n // when parsing a scheme (java\\\\tscript:), and lowercase. Returns the\n // original (still-escaped) URL when safe, or null to drop the link.\n function sanitizeHref(url) {\n var probe = url.replace(/&(amp|lt|gt|quot|#39);/g, function (m, name) {\n return { amp: \"&\", lt: \"<\", gt: \">\", quot: '\"', \"#39\": \"'\" }[name];\n });\n probe = probe.replace(/[\\\\u0000-\\\\u0020\\\\u007f]+/g, \"\").toLowerCase();\n if (/^[a-z][a-z0-9+.-]*:/.test(probe)) {\n return /^(https?|mailto):/.test(probe) ? url : null;\n }\n if (/^[\\\\/\\\\\\\\]{2}/.test(probe)) return null; // scheme-relative smuggles a foreign host\n return url;\n }\n function mdInline(s) {\n s = s.replace(/\\\\*\\\\*([^*]+)\\\\*\\\\*/g, \"<strong>$1</strong>\");\n var codeRe = new RegExp(BT + \"([^\" + BT + \"]+)\" + BT, \"g\");\n s = s.replace(codeRe, \"<code>$1</code>\");\n s = s.replace(/\\\\[([^\\\\]]+)\\\\]\\\\(([^)]+)\\\\)/g, function (m, label, url) {\n var href = sanitizeHref(url);\n if (href === null) return label; // unsafe scheme: label as plain text, no <a>\n return '<a href=\"' + href + '\" target=\"_blank\" rel=\"noopener\">' + label + \"</a>\";\n });\n return s;\n }\n function mdToHtml(raw) {\n var src = esc(String(raw));\n var fence = BT + BT + BT;\n var html = \"\", idx = 0;\n while (true) {\n var start = src.indexOf(fence, idx);\n if (start === -1) { html += mdBlocks(src.slice(idx)); break; }\n html += mdBlocks(src.slice(idx, start));\n var nl = src.indexOf(\"\\\\n\", start + 3);\n var bodyStart = (nl === -1) ? start + 3 : nl + 1;\n var end = src.indexOf(fence, bodyStart);\n if (end === -1) { html += mdBlocks(src.slice(start)); break; }\n html += '<pre class=\"code\">' + src.slice(bodyStart, end).replace(/\\\\n$/, \"\") + \"</pre>\";\n idx = end + 3;\n }\n return html;\n }\n function mdBlocks(src) {\n var lines = src.split(\"\\\\n\"), html = \"\", inList = false;\n function closeList() { if (inList) { html += \"</ul>\"; inList = false; } }\n for (var i = 0; i < lines.length; i++) {\n var ln = lines[i];\n var h = ln.match(/^(#{1,4})\\\\s+(.*)$/);\n if (h) { closeList(); html += '<div class=\"md-h md-h' + h[1].length + '\">' + mdInline(h[2]) + \"</div>\"; continue; }\n var li = ln.match(/^\\\\s*[-*]\\\\s+(.*)$/);\n if (li) { if (!inList) { html += \"<ul>\"; inList = true; } html += \"<li>\" + mdInline(li[1]) + \"</li>\"; continue; }\n if (ln.trim() === \"\") { closeList(); continue; }\n closeList();\n html += '<div class=\"md-p\">' + mdInline(ln) + \"</div>\";\n }\n closeList();\n return html;\n }\n function renderKv(obj) {\n var keys = Object.keys(obj);\n if (!keys.length) return '<span class=\"dim\">{}</span>';\n return '<div class=\"kv\">' + keys.map(function (k) {\n var v = obj[k], vs;\n if (v === null || v === undefined) vs = '<span class=\"dim\">null</span>';\n else if (typeof v === \"object\") vs = '<pre class=\"mini\">' + esc(fmt(v)) + \"</pre>\";\n else vs = esc(String(v));\n return '<div class=\"kv-row\"><span class=\"kv-k\">' + esc(k) + '</span><span class=\"kv-v\">' + vs + \"</span></div>\";\n }).join(\"\") + \"</div>\";\n }\n function isMessageArray(v) {\n return Array.isArray(v) && v.length > 0 && v.every(function (m) { return m && typeof m === \"object\" && typeof m.role === \"string\"; });\n }\n function renderContent(c) {\n if (c == null) return '<span class=\"dim\">—</span>';\n if (typeof c === \"string\") return mdToHtml(c);\n if (Array.isArray(c)) return c.map(renderPart).join(\"\");\n if (typeof c === \"object\") return renderKv(c);\n return esc(String(c));\n }\n function renderPart(p) {\n if (p == null) return \"\";\n if (typeof p === \"string\") return mdToHtml(p);\n if (p.type === \"text\" && typeof p.text === \"string\") return mdToHtml(p.text);\n return '<div class=\"part\"><div class=\"part-label\">' + esc(p.type || \"part\") + \"</div>\" + renderKv(p) + \"</div>\";\n }\n function previewText(c) {\n if (c == null) return \"\";\n if (typeof c === \"string\") return c.replace(/\\\\s+/g, \" \").slice(0, 70);\n if (Array.isArray(c)) {\n for (var i = 0; i < c.length; i++) {\n var p = c[i];\n if (typeof p === \"string\") return p.slice(0, 70);\n if (p && p.type === \"text\" && p.text) return String(p.text).slice(0, 70);\n }\n return \"\";\n }\n try { return JSON.stringify(c).slice(0, 70); } catch (e) { return \"\"; }\n }\n function renderMsg(m) {\n var role = m.role || \"msg\";\n var body = (m.content !== undefined) ? renderContent(m.content) : renderKv(m);\n return '<div class=\"msg\"><div class=\"msg-role role-' + esc(role) + '\">' + esc(role) + '</div><div class=\"msg-content\">' + body + \"</div></div>\";\n }\n function renderMessages(arr) {\n var inner = '<div class=\"messages\">' + arr.map(renderMsg).join(\"\") + \"</div>\";\n // Short threads render inline; a long history (10-15+ messages) collapses\n // behind a <details> so it doesn't blow up the detail pane — the summary\n // shows the count + a preview of the latest message; click to expand.\n if (arr.length <= 6) return inner;\n var last = arr[arr.length - 1] || {};\n var preview = (last.role ? last.role + \": \" : \"\") + previewText(last.content);\n return '<details class=\"msg-collapse\"><summary><span class=\"msg-count\">' + arr.length\n + ' messages</span> <span class=\"dim\">' + esc(preview) + \"</span></summary>\" + inner + \"</details>\";\n }\n function smartValue(v) {\n if (v === null || v === undefined) return '<span class=\"dim\">—</span>';\n if (typeof v === \"string\") {\n var t = v.trim();\n if (t.charAt(0) === \"{\" || t.charAt(0) === \"[\") { try { return smartValue(JSON.parse(t)); } catch (e) {} }\n return mdToHtml(v);\n }\n if (isMessageArray(v)) return renderMessages(v);\n if (Array.isArray(v)) {\n return '<div class=\"kv\">' + v.map(function (item, i) {\n var vs = (item && typeof item === \"object\") ? renderKv(item) : esc(String(item));\n return '<div class=\"kv-row\"><span class=\"kv-k\">' + i + '</span><span class=\"kv-v\">' + vs + \"</span></div>\";\n }).join(\"\") + \"</div>\";\n }\n if (typeof v === \"object\") return renderKv(v);\n return esc(String(v));\n }\n\n function renderStats(a) {\n var cost = a.cost ? (((a.cost.input || 0) + (a.cost.output || 0) + (a.cost.cachedInput || 0) + (a.cost.cacheWrite || 0) + (a.cost.cachedOutput || 0) + (a.cost.reasoning || 0)).toFixed(4)) : \"—\";\n var u = a.usage || {};\n var cells = [\n [\"traces\", num(a.traces), null],\n [\"completed\", num(a.completed), null],\n [\"failed\", num(a.failed), null],\n [\"cancelled\", num(a.cancelled), null],\n [\"↓ tokens in\", num(u.input), \"var(--tok-in)\"],\n [\"↑ tokens out\", num(u.output), \"var(--tok-out)\"],\n [\"tokens total\", num(u.total), \"var(--tok-total)\"],\n [\"cost (usd)\", cost, null]\n ];\n document.getElementById(\"stats\").innerHTML = cells.map(function (c) {\n var st = c[2] ? ' style=\"color:' + c[2] + '\"' : \"\";\n return '<div class=\"stat\"><div class=\"label\"' + st + \">\" + c[0] + '</div><div class=\"value\"' + st + \">\" + esc(c[1]) + \"</div></div>\";\n }).join(\"\");\n }\n\n // Per-row heat accent: tint the left edge by the trace's own cost\n // relative to the most expensive trace currently in the (filtered) list.\n function heatStyle(intensity) {\n if (intensity <= 0) return \"\";\n var op = (0.12 + intensity * 0.88).toFixed(3);\n return ' style=\"--heat-op:' + op + '\"';\n }\n function heatBar(intensity) {\n if (intensity <= 0) return \"\";\n var op = (0.12 + intensity * 0.88).toFixed(3);\n return '<span class=\"heat\" style=\"opacity:' + op + '\" title=\"relative cost\"></span>';\n }\n function renderRow(t, maxTraceCost) {\n var sel = t.traceId === state.selectedId ? \" selected\" : \"\";\n var intensity = heatIntensity(traceCost(t), maxTraceCost);\n var pk = tracePromptKey(t);\n return '<div class=\"trace-row' + sel + '\" data-id=\"' + esc(t.traceId) + '\">'\n + heatBar(intensity)\n + typeLabel(t.root.type)\n + '<span class=\"badge ' + statusClass(t.root.status) + '\">' + esc(statusText(t.root.status)) + \"</span>\"\n + '<span class=\"rname\">' + esc(t.root.name) + \"</span>\"\n + (pk ? '<span class=\"rprompt\" title=\"prompt version\">' + esc(pk) + \"</span>\" : \"\")\n + (t.sessionId ? '<span class=\"dim\">' + esc(t.sessionId) + \"</span>\" : \"\")\n + '<span class=\"rright\">' + tokens(t.usage) + '<span class=\"dim\">· ' + dur(t.duration) + \"</span></span>\"\n + '<i class=\"chev\">›</i>'\n + \"</div>\";\n }\n function maxTraceCostOf(list) {\n var max = 0;\n for (var i = 0; i < list.length; i++) { var c = traceCost(list[i]); if (c > max) max = c; }\n return max;\n }\n // Render grouped buckets. \"groups\" is the normalized list each group-by\n // dimension produces — a groupKey + its traces. Shared by session, prompt,\n // and type. Optional \"labelFn\" maps the raw groupKey to a display label and\n // switches the header to the compact \"Label (N)\" form (used by type, whose\n // keys are friendly enums); session/prompt omit it and keep their raw id\n // plus the right-aligned \"N trace(s)\" count. data-group stays the RAW key\n // so collapse state keys consistently regardless of the display label.\n function renderGroups(groups, maxTraceCost, labelFn) {\n return groups.map(function (g) {\n var collapsed = !!state.collapsedGroups[g.groupKey];\n var idAndCount = labelFn\n ? '<span class=\"sgroup-id\">' + esc(labelFn(g.groupKey)) + \" (\" + g.traces.length + \")</span>\"\n : '<span class=\"sgroup-id\">' + esc(g.groupKey) + \"</span>\"\n + '<span class=\"sgroup-count\">' + g.traces.length + \" trace(s)</span>\";\n var head = '<div class=\"sgroup-head\" data-group=\"' + esc(g.groupKey) + '\">'\n + '<span class=\"sgroup-tw\">' + (collapsed ? \"▸\" : \"▾\") + \"</span>\"\n + idAndCount + \"</div>\";\n var body = collapsed ? \"\" : '<div class=\"sgroup-body\">'\n + g.traces.map(function (t) { return renderRow(t, maxTraceCost); }).join(\"\") + \"</div>\";\n return '<div class=\"sgroup\">' + head + body + \"</div>\";\n }).join(\"\");\n }\n // Normalize a session group ({sessionId,…}) to the shared {groupKey,…} shape.\n function sessionGroups(list) {\n return groupBySession(list).map(function (g) { return { groupKey: g.sessionId, traces: g.traces }; });\n }\n function renderList() {\n var list = filteredTraces();\n // Keep the per-type stats panel in sync — runs on every poll + filter\n // change, before the empty-state early return below.\n renderStatsPanel();\n var host = document.getElementById(\"traces\");\n if (!list.length) {\n host.innerHTML = state.traces.length\n ? '<div class=\"empty\">No traces match the current filters.</div>'\n : '<div class=\"empty\">No traces yet. Run an observed flow and they will appear here.</div>';\n return;\n }\n var maxTraceCost = maxTraceCostOf(list);\n // One grouping dimension renders at a time. The toggles are kept mutually\n // exclusive in their change handlers, so this precedence chain (most\n // specific → coarsest: prompt → session → type) only ever matches one.\n var html;\n if (state.groupByPrompt) html = renderGroups(groupByPrompt(list), maxTraceCost);\n else if (state.groupBySession) html = renderGroups(sessionGroups(list), maxTraceCost);\n else if (state.groupByType) html = renderGroups(typeGroups(list), maxTraceCost, typeText);\n else html = list.map(function (t) { return renderRow(t, maxTraceCost); }).join(\"\");\n host.innerHTML = html;\n document.getElementById(\"meta\").textContent = list.length + \" of \" + state.traces.length + \" trace(s) · live\";\n }\n\n // --- Filter UI rendering ---------------------------------------------\n function renderChips() {\n var f = state.filter;\n document.getElementById(\"status-chips\").innerHTML =\n '<span class=\"chip-group\"><span class=\"gl\">status</span>'\n + STATUS_FILTERS.map(function (s) {\n return '<button type=\"button\" class=\"chip' + (f.statuses[s] ? \" active\" : \"\") + '\" data-status=\"' + esc(s) + '\">' + esc(statusText(s)) + \"</button>\";\n }).join(\"\")\n + '<button type=\"button\" class=\"chip' + (f.errorsOnly ? \" active\" : \"\") + '\" data-errors=\"1\" title=\"Show only failed / cancelled traces\">Errors only</button>'\n + \"</span>\";\n var types = presentTypes();\n document.getElementById(\"type-chips\").innerHTML = types.length\n ? '<span class=\"chip-group\"><span class=\"gl\">type</span>'\n + types.map(function (ty) {\n return '<button type=\"button\" class=\"chip' + (f.types[ty] ? \" active\" : \"\") + '\" data-type=\"' + esc(ty) + '\">' + esc(typeText(ty)) + \"</button>\";\n }).join(\"\") + \"</span>\"\n : \"\";\n var sessions = presentSessions();\n document.getElementById(\"session-chips\").innerHTML = sessions.length\n ? '<span class=\"chip-group\"><span class=\"gl\">session</span>'\n + sessions.map(function (s) {\n return '<button type=\"button\" class=\"chip' + (f.sessionId === s ? \" active\" : \"\") + '\" data-session=\"' + esc(s) + '\">' + esc(s) + \"</button>\";\n }).join(\"\") + \"</span>\"\n : \"\";\n // Prompt-version filter chips — one per distinct name@version seen.\n // Hidden entirely until a named-prompt run shows up, so the toolbar stays\n // clean for projects that don't use the ai.prompts registry.\n var prompts = presentPrompts();\n document.getElementById(\"prompt-chips\").innerHTML = prompts.length\n ? '<span class=\"chip-group\"><span class=\"gl\">prompt</span>'\n + prompts.map(function (p) {\n return '<button type=\"button\" class=\"chip' + (f.promptKey === p ? \" active\" : \"\") + '\" data-prompt=\"' + esc(p) + '\">' + esc(p) + \"</button>\";\n }).join(\"\") + \"</span>\"\n : \"\";\n }\n\n // Heatmap denominator for the currently rendered trace tree. Set by\n // renderDrawer before each renderTree pass so node accents are scaled\n // against the most expensive node in this trace.\n var currentTreeMax = 0;\n function renderTree(span) {\n var hasKids = span.children && span.children.length;\n var collapsed = !!state.collapsed[span.spanId];\n var sel = span.spanId === state.selectedSpanId ? \" selected\" : \"\";\n var tw = hasKids ? (collapsed ? \"▸\" : \"▾\") : \"·\";\n var node = '<div class=\"tnode' + sel + '\" data-span=\"' + esc(span.spanId) + '\">'\n + heatBar(heatIntensity(rollupCost(span), currentTreeMax))\n + '<span class=\"twisty\"' + (hasKids ? ' data-toggle=\"' + esc(span.spanId) + '\"' : \"\") + \">\" + tw + \"</span>\"\n + typeLabel(span.type)\n + '<span class=\"tname\">' + esc(span.name) + \"</span>\"\n + statusDot(span.status)\n + '<span class=\"tmeta\">' + dur(span.duration) + \"</span>\"\n + \"</div>\";\n var kids = (hasKids && !collapsed) ? '<div class=\"tkids\">' + span.children.map(renderTree).join(\"\") + \"</div>\" : \"\";\n return node + kids;\n }\n\n // --- Timeline / waterfall (Gantt) ------------------------------------\n // Flatten the span tree to a depth-first ordered list, each entry\n // carrying its offset (ms from root start) + duration, so we can lay\n // out concurrency without re-walking. parseTs tolerates a missing/bad\n // startedAt by falling back to 0 so a bad clock never NaNs the bars.\n function parseTs(s) { var n = Date.parse(s); return isNaN(n) ? 0 : n; }\n // Render an ISO timestamp for the detail drawer as a readable, locale-\n // unambiguous local time — \"28 Jun 2026 03:16 PM\" (named month so there is\n // no M/D vs D/M confusion; minute precision). Falls back to the raw string\n // on a bad clock.\n var MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n function pad2(n) { return (n < 10 ? \"0\" : \"\") + n; }\n function fmtTs(iso) {\n if (!iso) return \"—\";\n var d = new Date(iso);\n if (isNaN(d.getTime())) return String(iso);\n var h = d.getHours();\n var ampm = h >= 12 ? \"PM\" : \"AM\";\n var h12 = h % 12;\n if (h12 === 0) h12 = 12;\n return d.getDate() + \" \" + MONTHS[d.getMonth()] + \" \" + d.getFullYear()\n + \" \" + pad2(h12) + \":\" + pad2(d.getMinutes()) + \" \" + ampm;\n }\n function flattenSpans(root) {\n var base = parseTs(root.startedAt);\n var rows = [];\n (function walk(span, depth) {\n var start = parseTs(span.startedAt) - base;\n if (start < 0) start = 0;\n var d = (span.duration != null) ? span.duration : 0;\n rows.push({ span: span, depth: depth, offset: start, duration: d, end: start + d });\n (span.children || []).forEach(function (c) { walk(c, depth + 1); });\n })(root, 0);\n return rows;\n }\n // Critical path: from the root, repeatedly step into the child whose\n // end time is latest (the one that pushed the parent's finish). Marks\n // the spans that determine total wall-clock time.\n function criticalPath(root) {\n var crit = {};\n (function walk(span) {\n crit[span.spanId] = 1;\n var kids = span.children || [];\n if (!kids.length) return;\n var pick = null, pe = -1;\n for (var i = 0; i < kids.length; i++) {\n var e = parseTs(kids[i].startedAt) + ((kids[i].duration != null) ? kids[i].duration : 0);\n if (e > pe) { pe = e; pick = kids[i]; }\n }\n if (pick) walk(pick);\n })(root);\n return crit;\n }\n function renderGantt(root) {\n var rows = flattenSpans(root);\n var span0 = rows.length ? rows[0] : null;\n var total = 0;\n rows.forEach(function (r) { if (r.end > total) total = r.end; });\n if (total <= 0) total = (span0 && span0.duration) || 1;\n var crit = criticalPath(root);\n var body = rows.map(function (r) {\n var leftPct = (r.offset / total) * 100;\n var widthPct = Math.max((r.duration / total) * 100, 0.6);\n var sel = r.span.spanId === state.selectedSpanId ? \" selected\" : \"\";\n var isCrit = crit[r.span.spanId] ? \" crit\" : \"\";\n var barClass = \"gbar bar-\" + statusClass(r.span.status) + (isCrit ? \" crit\" : \"\");\n var pad = \"padding-left:\" + (r.depth * 10) + \"px\";\n return '<div class=\"grow' + sel + '\" data-span=\"' + esc(r.span.spanId) + '\">'\n + '<span class=\"glabel\" style=\"' + pad + '\" title=\"' + esc(r.span.name) + '\">' + esc(r.span.name) + \"</span>\"\n + '<span class=\"gtrack\"><span class=\"' + barClass + '\" style=\"left:' + leftPct.toFixed(2) + \"%;width:\" + widthPct.toFixed(2) + '%\"></span></span>'\n + '<span class=\"gdur\">' + dur(r.duration) + \"</span>\"\n + \"</div>\";\n }).join(\"\");\n var legend = '<div class=\"gantt-legend\">'\n + '<span class=\"ck\"><span class=\"sw\" style=\"background:var(--fail)\"></span> critical path</span>'\n + '<span class=\"ck\"><span class=\"sw\" style=\"background:var(--ty-agent)\"></span> span (offset + duration)</span>'\n + \"</div>\";\n return '<div class=\"gantt\">' + (body || '<div class=\"dim\">No spans.</div>') + legend + \"</div>\";\n }\n\n // The name@version of the named prompt this span's run resolved, read\n // from the collector's prompt-version-linkage attributes. Returns null when\n // the run carried no named prompt. Mirrors tracePromptKey in trace-filter.ts.\n function spanPromptKey(span) {\n var a = span && span.attributes;\n if (!a || typeof a !== \"object\") return null;\n var name = a[\"agent.promptName\"];\n if (typeof name !== \"string\" || !name.length) return null;\n var ver = a[\"agent.promptVersion\"];\n var vl = (typeof ver === \"string\" && ver.length) ? ver : \"1\";\n return name + \"@\" + vl;\n }\n function tracePromptKey(t) { return spanPromptKey(t.root); }\n\n // Humanize a metadata key for display: split dot.notation + camelCase,\n // Title-case each word, upcase \"id\". e.g. \"supervisor.terminatedBy\" →\n // \"Supervisor Terminated By\", \"span id\" → \"Span ID\", \"agent.trips\" →\n // \"Agent Trips\". Underlying attribute keys are untouched.\n // NB: this whole script is a template literal — regex backslash classes\n // MUST be double-escaped (\\\\s) so the rendered script retains its backslash.\n function humanizeKey(key) {\n return String(key).split(/[.\\\\s]+/).map(function (seg) {\n return seg.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").split(/\\\\s+/).map(function (w) {\n if (!w) return w;\n if (w.toLowerCase() === \"id\") return \"ID\";\n return w.charAt(0).toUpperCase() + w.slice(1);\n }).join(\" \");\n }).join(\" \");\n }\n\n function renderMeta(span, trace) {\n var rows = [];\n // Absolute wall-clock span — the head shows only the elapsed duration, so\n // surface when this node actually started/ended for log correlation.\n rows.push([\"started\", fmtTs(span.startedAt)]);\n rows.push([\"ended\", fmtTs(span.endedAt)]);\n var sid = span.sessionId || trace.sessionId;\n if (sid) rows.push([\"session\", sid]);\n // Prompt-version linkage: surface the resolved named prompt as one clean\n // name@version row right under session, so the panel reads it as a\n // first-class dimension rather than two raw attribute keys.\n var pk = spanPromptKey(span);\n if (pk) rows.push([\"prompt\", pk]);\n if (span.version) rows.push([\"version\", span.version]);\n rows.push([\"span id\", span.spanId]);\n if (span.parentSpanId) rows.push([\"parent\", span.parentSpanId]);\n rows.push([\"trace id\", span.traceId || trace.traceId]);\n var attrs = span.attributes;\n // Skip the two raw prompt keys — already shown as the clean prompt row.\n if (attrs && typeof attrs === \"object\") Object.keys(attrs).forEach(function (k) {\n if (k === \"agent.promptName\" || k === \"agent.promptVersion\") return;\n rows.push([k, attrs[k]]);\n });\n var kv = rows.map(function (r) {\n var v = r[1];\n var vs = (v && typeof v === \"object\") ? '<pre class=\"mini\">' + esc(fmt(v)) + \"</pre>\" : esc(String(v));\n return '<div class=\"kv-row\"><span class=\"kv-k\">' + esc(humanizeKey(r[0])) + '</span><span class=\"kv-v\">' + vs + \"</span></div>\";\n }).join(\"\");\n return '<div class=\"meta-sec\"><div class=\"meta-title\">metadata</div><div class=\"kv\">' + kv + \"</div></div>\";\n }\n\n // --- Evaluate: grade a span's last captured system prompt -------------\n // Config-gated (EVALUATE_ENABLED) — the drawer's only write action, POSTing\n // to a route that itself only exists when the server was configured with\n // evaluate. UI state lives in state.evaluate, keyed by spanId, so it\n // survives a re-render (e.g. switching to a sibling span and back).\n function extractLastSystemPrompt(span) {\n if (!Array.isArray(span.input)) return null;\n for (var i = span.input.length - 1; i >= 0; i--) {\n var m = span.input[i];\n if (m && typeof m === \"object\" && m.role === \"system\" && typeof m.content === \"string\") return m.content;\n }\n return null;\n }\n function evalState(spanId) {\n return state.evaluate[spanId] || (state.evaluate[spanId] = {\n open: false, instructions: EVALUATE_DEFAULT_INSTRUCTIONS, status: \"idle\", result: null, error: null\n });\n }\n function evalResultHtml(result) {\n var score = typeof result.score === \"number\" ? Math.round(result.score * 100) + \"%\" : \"n/a\";\n var issues = (result.issues || []).map(function (i) { return \"<li>\" + esc(i) + \"</li>\"; }).join(\"\");\n return '<div class=\"eval-result\"><span class=\"eval-score\">Score: ' + score + \"</span>\"\n + (issues ? '<ul class=\"eval-issues\">' + issues + \"</ul>\" : \"\") + \"</div>\";\n }\n function evalSectionHtml(span) {\n if (!EVALUATE_ENABLED) return \"\";\n var sysPrompt = extractLastSystemPrompt(span);\n if (!sysPrompt) return \"\";\n var st = evalState(span.spanId);\n var btn = '<button type=\"button\" class=\"eval-btn\" data-evaluate-toggle=\"' + esc(span.spanId) + '\">'\n + (st.open ? \"Hide evaluate\" : \"Evaluate system prompt\") + \"</button>\";\n if (!st.open) return btn;\n var running = st.status === \"running\";\n return btn + '<div class=\"eval-panel\">'\n + '<textarea id=\"eval-instructions\" placeholder=\"Grading instructions (optional — falls back to the configured default)\"' + (running ? \" disabled\" : \"\") + \">\" + esc(st.instructions || \"\") + \"</textarea>\"\n + '<div class=\"eval-actions\">'\n + '<button type=\"button\" class=\"eval-btn\" data-evaluate-run=\"' + esc(span.spanId) + '\"' + (running ? \" disabled\" : \"\") + \">\" + (running ? \"Evaluating…\" : \"Run\") + \"</button>\"\n + (st.error ? '<span class=\"eval-error\">' + esc(st.error) + \"</span>\" : \"\")\n + \"</div>\"\n + (st.result ? evalResultHtml(st.result) : \"\")\n + \"</div>\";\n }\n // The full trace of the open drawer, once it has loaded.\n function openDetail() {\n return state.detail && state.detail.traceId === state.selectedId ? state.detail : null;\n }\n function rerenderDetail() {\n var t = openDetail();\n if (!t) return;\n var sel = findSpan(t.root, state.selectedSpanId) || t.root;\n document.getElementById(\"drawer-detail\").innerHTML = renderDetail(sel, t);\n }\n function toggleEvalPanel(spanId) {\n evalState(spanId).open = !evalState(spanId).open;\n rerenderDetail();\n }\n function runEvaluate(traceId, spanId) {\n var st = evalState(spanId);\n var textarea = document.getElementById(\"eval-instructions\");\n if (textarea) st.instructions = textarea.value;\n st.status = \"running\"; st.error = null;\n rerenderDetail();\n fetchAuthed(API + \"/traces/\" + encodeURIComponent(traceId) + \"/spans/\" + encodeURIComponent(spanId) + \"/evaluate\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ instructions: st.instructions })\n }).then(function (r) {\n return r.json().then(function (data) { return { ok: r.ok, data: data }; });\n }).then(function (res) {\n if (res.ok) { st.status = \"done\"; st.result = res.data; st.error = null; }\n else { st.status = \"error\"; st.error = (res.data && (res.data.message || res.data.error)) || \"evaluate failed\"; st.result = null; }\n rerenderDetail();\n }).catch(function () {\n st.status = \"error\"; st.error = \"network error\"; st.result = null;\n rerenderDetail();\n });\n }\n\n function renderDetail(span, trace) {\n var path = findPath(trace.root, span.spanId) || [span];\n var crumb = path.map(function (p, i) { return (i ? '<span class=\"sep\"> › </span>' : \"\") + \"<span>\" + esc(p.name) + \"</span>\"; }).join(\"\");\n var io = \"\";\n if (span.input !== undefined) io += '<div class=\"piol\" style=\"color:var(--tok-in)\">input</div><div class=\"io-body\">' + smartValue(span.input) + \"</div>\";\n if (span.output !== undefined) io += '<div class=\"piol\" style=\"color:var(--tok-out)\">output</div><div class=\"io-body\">' + smartValue(span.output) + \"</div>\";\n if (span.error) io += '<div class=\"piol\" style=\"color:var(--fail)\">error</div><div class=\"io-body\">' + smartValue(span.error) + \"</div>\";\n\n // Tokens + cost line — omitted entirely when the node has neither\n // (e.g. a free tool with zero usage), so the panel stays uncluttered.\n var tk = tokens(span.usage);\n var c = rollupCost(span);\n var metaLine = (tk || c > 0)\n ? '<div style=\"margin-bottom:4px\">' + tk + (c > 0 ? '<span class=\"cost\">' + (tk ? \" · \" : \"\") + money(c) + \"</span>\" : \"\") + \"</div>\"\n : \"\";\n\n return '<div class=\"crumb\">' + crumb + \"</div>\"\n + '<div class=\"dhead-row\">' + typeLabel(span.type) + '<span style=\"font-weight:600\">' + esc(span.name) + \"</span>\"\n + '<span class=\"badge ' + statusClass(span.status) + '\">' + esc(statusText(span.status)) + \"</span>\"\n + '<span class=\"dim\">· ' + dur(span.duration) + \"</span></div>\"\n + metaLine\n + io\n + evalSectionHtml(span, trace)\n + renderMeta(span, trace);\n }\n\n function headHtml(t) {\n var cost = traceCost(t);\n return typeLabel(t.root.type)\n + '<span class=\"badge ' + statusClass(t.root.status) + '\">' + esc(statusText(t.root.status)) + \"</span>\"\n + '<span style=\"font-weight:600\">' + esc(t.root.name) + \"</span>\"\n + '<span class=\"dim\">· ' + dur(t.duration) + \"</span>\"\n + tokens(t.usage)\n + (cost > 0 ? '<span class=\"cost\">· ' + money(cost) + \"</span>\" : \"\")\n + '<button class=\"drawer-close\" type=\"button\" title=\"Close (Esc)\">✕ Close</button>';\n }\n\n function viewSwitcher() {\n var tree = state.view === \"tree\" ? \" active\" : \"\";\n var tl = state.view === \"timeline\" ? \" active\" : \"\";\n return '<div class=\"dview\" id=\"drawer-view\">'\n + '<button type=\"button\" class=\"' + tree.trim() + '\" data-view=\"tree\">Tree</button>'\n + '<button type=\"button\" class=\"' + tl.trim() + '\" data-view=\"timeline\">Timeline</button>'\n + '<span class=\"legend\" title=\"Node colour = relative cost\"><span>cost</span><span class=\"grad\"></span></span>'\n + \"</div>\";\n }\n function leftPaneHtml(t) {\n if (state.view === \"timeline\") return renderGantt(t.root);\n currentTreeMax = maxNodeCost(t.root);\n return renderTree(t.root);\n }\n function renderDrawer(t) {\n document.getElementById(\"drawer-head\").innerHTML = headHtml(t);\n var sel = findSpan(t.root, state.selectedSpanId) || t.root;\n document.getElementById(\"drawer-body\").innerHTML =\n '<div class=\"dsplit\"><div class=\"dtree\" id=\"drawer-tree\">' + viewSwitcher() + leftPaneHtml(t) + \"</div>\"\n + '<div class=\"ddetail\" id=\"drawer-detail\">' + renderDetail(sel, t) + \"</div></div>\";\n }\n // Re-render only the left pane (after a view switch) without disturbing\n // the detail panel or scroll position of the detail side.\n function renderLeftPane() {\n var t = openDetail();\n if (!t) return;\n document.getElementById(\"drawer-tree\").innerHTML = viewSwitcher() + leftPaneHtml(t);\n }\n\n function selectSpan(id) {\n state.selectedSpanId = id;\n var t = openDetail();\n if (!t) return;\n document.getElementById(\"drawer-detail\").innerHTML = renderDetail(findSpan(t.root, id) || t.root, t);\n // Highlight in whichever left pane is active (tree nodes or Gantt rows).\n var nodes = document.querySelectorAll(\".tnode[data-span], .grow[data-span]\");\n for (var i = 0; i < nodes.length; i++) {\n if (nodes[i].getAttribute(\"data-span\") === id) nodes[i].classList.add(\"selected\");\n else nodes[i].classList.remove(\"selected\");\n }\n writeHash();\n }\n function toggleSpan(id) {\n state.collapsed[id] = !state.collapsed[id];\n var t = openDetail();\n if (t) renderLeftPane();\n }\n function setView(v) {\n if (state.view === v) return;\n state.view = v;\n renderLeftPane();\n }\n\n // Drawer placeholder while the full trace loads, or when it cannot.\n function renderDrawerMessage(text) {\n document.getElementById(\"drawer-head\").innerHTML =\n '<button class=\"drawer-close\" type=\"button\" title=\"Close (Esc)\">✕ Close</button>';\n document.getElementById(\"drawer-body\").innerHTML = '<div class=\"empty\">' + esc(text) + \"</div>\";\n }\n // Fetch the full trace (span tree + captured content) for the drawer.\n // The list only carries summaries, so the drawer always reads this.\n function loadDetail(id, spanId) {\n state.loadingId = id;\n fetchAuthed(API + \"/traces/\" + encodeURIComponent(id)).then(function (r) {\n return r.json().then(function (data) { return { ok: r.ok, status: r.status, data: data }; });\n }).then(function (res) {\n if (state.loadingId === id) state.loadingId = null;\n if (state.selectedId !== id) return;\n if (!res.ok) {\n var code = res.data && res.data.error;\n renderDrawerMessage(res.status === 404\n ? \"This trace is no longer in the store: older traces are dropped once the store reaches its capacity. Close this panel and pick a recent trace.\"\n : \"Could not load this trace (\" + (code || (\"HTTP \" + res.status)) + \"). Close this panel and try again.\");\n return;\n }\n var t = res.data;\n var wanted = spanId || state.selectedSpanId;\n state.detail = t;\n state.selectedSpanId = (wanted && findSpan(t.root, wanted)) ? wanted : t.root.spanId;\n state.sig = traceSig(t);\n renderDrawer(t);\n writeHash();\n }).catch(function () {\n if (state.loadingId === id) state.loadingId = null;\n if (state.selectedId !== id) return;\n renderDrawerMessage(\"Could not reach the dashboard server to load this trace. Check that the app is still running, then reopen the trace.\");\n });\n }\n function openTrace(id, spanId) {\n state.selectedId = id;\n state.selectedSpanId = spanId || null;\n state.collapsed = {};\n state.detail = null;\n state.sig = null;\n renderDrawerMessage(\"Loading trace…\");\n loadDetail(id, spanId);\n document.getElementById(\"drawer\").classList.add(\"open\");\n document.getElementById(\"drawer\").setAttribute(\"aria-hidden\", \"false\");\n document.getElementById(\"backdrop\").classList.add(\"open\");\n markSelectedRow();\n writeHash();\n }\n function closeDrawer() {\n state.selectedId = null; state.selectedSpanId = null; state.sig = null; state.detail = null;\n document.getElementById(\"drawer\").classList.remove(\"open\");\n document.getElementById(\"drawer\").setAttribute(\"aria-hidden\", \"true\");\n document.getElementById(\"backdrop\").classList.remove(\"open\");\n markSelectedRow();\n writeHash();\n }\n\n // --- Deep-links: reflect the open trace + span in the URL hash -------\n // #trace=<id>&span=<id>. Written on open/close/select; read on load and\n // on manual hash edits (back/forward). A guard flag stops writeHash from\n // re-triggering our own hashchange handler in a loop.\n var suppressHash = false;\n function writeHash() {\n var h = \"\";\n if (state.selectedId) {\n h = \"#trace=\" + encodeURIComponent(state.selectedId);\n if (state.selectedSpanId && state.selectedSpanId !== state.selectedId) {\n h += \"&span=\" + encodeURIComponent(state.selectedSpanId);\n }\n }\n suppressHash = true;\n try {\n if (history && history.replaceState) history.replaceState(null, \"\", h || (location.pathname + location.search));\n else location.hash = h;\n } catch (e) { location.hash = h; }\n suppressHash = false;\n }\n function readHash() {\n var raw = (location.hash || \"\").replace(/^#/, \"\");\n var out = { trace: null, span: null };\n raw.split(\"&\").forEach(function (kv) {\n var i = kv.indexOf(\"=\");\n if (i === -1) return;\n var k = kv.slice(0, i), v = decodeURIComponent(kv.slice(i + 1));\n if (k === \"trace\") out.trace = v;\n else if (k === \"span\") out.span = v;\n });\n return out;\n }\n // Open whatever the hash points at. The drawer fetches the trace by id,\n // so a deep link works even when the trace is past the polled list.\n // Returns true when it acted so the caller can mark the one-time load as done.\n function applyHash() {\n var h = readHash();\n if (!h.trace) {\n if (state.selectedId) closeDrawer();\n return true;\n }\n openTrace(h.trace, h.span || undefined);\n return true;\n }\n function markSelectedRow() {\n var rows = document.querySelectorAll(\".trace-row\");\n for (var i = 0; i < rows.length; i++) {\n if (rows[i].getAttribute(\"data-id\") === state.selectedId) rows[i].classList.add(\"selected\");\n else rows[i].classList.remove(\"selected\");\n }\n }\n\n document.getElementById(\"traces\").addEventListener(\"click\", function (e) {\n var head = e.target.closest ? e.target.closest(\".sgroup-head\") : null;\n if (head) {\n var g = head.getAttribute(\"data-group\");\n state.collapsedGroups[g] = !state.collapsedGroups[g];\n renderList();\n return;\n }\n var row = e.target.closest ? e.target.closest(\".trace-row\") : null;\n if (row) openTrace(row.getAttribute(\"data-id\"));\n });\n document.getElementById(\"drawer-head\").addEventListener(\"click\", function (e) {\n if (e.target.closest && e.target.closest(\".drawer-close\")) closeDrawer();\n });\n document.getElementById(\"drawer-body\").addEventListener(\"click\", function (e) {\n var vb = e.target.closest ? e.target.closest(\"[data-view]\") : null;\n if (vb) { setView(vb.getAttribute(\"data-view\")); return; }\n var tog = e.target.closest ? e.target.closest(\"[data-toggle]\") : null;\n if (tog) { toggleSpan(tog.getAttribute(\"data-toggle\")); return; }\n var evalToggle = e.target.closest ? e.target.closest(\"[data-evaluate-toggle]\") : null;\n if (evalToggle) { toggleEvalPanel(evalToggle.getAttribute(\"data-evaluate-toggle\")); return; }\n var evalRun = e.target.closest ? e.target.closest(\"[data-evaluate-run]\") : null;\n if (evalRun && state.selectedId) { runEvaluate(state.selectedId, evalRun.getAttribute(\"data-evaluate-run\")); return; }\n var node = e.target.closest ? e.target.closest(\".tnode[data-span], .grow[data-span]\") : null;\n if (node) selectSpan(node.getAttribute(\"data-span\"));\n });\n // Track the instructions textarea live (no re-render on keystroke, so\n // typing never loses focus/cursor position).\n document.getElementById(\"drawer-body\").addEventListener(\"input\", function (e) {\n if (e.target && e.target.id === \"eval-instructions\" && state.selectedSpanId) {\n evalState(state.selectedSpanId).instructions = e.target.value;\n }\n });\n document.getElementById(\"backdrop\").addEventListener(\"click\", closeDrawer);\n document.addEventListener(\"keydown\", function (e) { if (e.key === \"Escape\" || e.keyCode === 27) closeDrawer(); });\n\n // --- Filter / toolbar wiring -----------------------------------------\n function toggleMapKey(map, key) { if (map[key]) delete map[key]; else map[key] = 1; }\n document.getElementById(\"status-chips\").addEventListener(\"click\", function (e) {\n if (!e.target.closest) return;\n // The \"Errors only\" shortcut chip lives in the status group now.\n if (e.target.closest(\"[data-errors]\")) {\n state.filter.errorsOnly = !state.filter.errorsOnly;\n renderChips(); renderList();\n return;\n }\n var b = e.target.closest(\"[data-status]\");\n if (!b) return;\n toggleMapKey(state.filter.statuses, b.getAttribute(\"data-status\"));\n renderChips(); renderList();\n });\n document.getElementById(\"type-chips\").addEventListener(\"click\", function (e) {\n var b = e.target.closest ? e.target.closest(\"[data-type]\") : null;\n if (!b) return;\n toggleMapKey(state.filter.types, b.getAttribute(\"data-type\"));\n renderChips(); renderList();\n });\n document.getElementById(\"session-chips\").addEventListener(\"click\", function (e) {\n var b = e.target.closest ? e.target.closest(\"[data-session]\") : null;\n if (!b) return;\n var s = b.getAttribute(\"data-session\");\n state.filter.sessionId = (state.filter.sessionId === s) ? null : s;\n renderChips(); renderList();\n });\n document.getElementById(\"prompt-chips\").addEventListener(\"click\", function (e) {\n var b = e.target.closest ? e.target.closest(\"[data-prompt]\") : null;\n if (!b) return;\n var p = b.getAttribute(\"data-prompt\");\n state.filter.promptKey = (state.filter.promptKey === p) ? null : p;\n renderChips(); renderList();\n });\n document.getElementById(\"search\").addEventListener(\"input\", function (e) {\n state.filter.text = e.target.value || \"\";\n renderList();\n });\n // One mutually-exclusive grouping dimension, chosen from the Group dropdown.\n // \"\" = no grouping; renderList's precedence chain only ever matches one.\n // Switching dimensions drops stale collapsed-header keys.\n function setGrouping(dim) {\n state.groupBySession = dim === \"session\";\n state.groupByPrompt = dim === \"prompt\";\n state.groupByType = dim === \"type\";\n state.collapsedGroups = {};\n renderList();\n }\n document.getElementById(\"group-by\").addEventListener(\"change\", function (e) {\n setGrouping(e.target.value);\n });\n document.getElementById(\"show-stats\").addEventListener(\"change\", function (e) {\n state.showStats = !!e.target.checked;\n renderStatsPanel();\n });\n document.getElementById(\"clear-filters\").addEventListener(\"click\", function () {\n state.filter = { text: \"\", statuses: {}, types: {}, sessionId: null, promptKey: null, errorsOnly: false };\n document.getElementById(\"search\").value = \"\";\n renderChips(); renderList();\n });\n\n // Back/forward or a manual hash edit re-syncs the open trace/span.\n window.addEventListener(\"hashchange\", function () {\n if (suppressHash) return;\n applyHash();\n });\n\n var THEME_KEY = \"panoptic-theme\";\n var mql = window.matchMedia ? window.matchMedia(\"(prefers-color-scheme: light)\") : null;\n function applyTheme(mode) {\n try { localStorage.setItem(THEME_KEY, mode); } catch (e) {}\n var light = mode === \"light\" || (mode === \"system\" && mql && mql.matches);\n document.documentElement.setAttribute(\"data-theme\", light ? \"light\" : \"dark\");\n var btns = document.querySelectorAll(\"[data-theme-set]\");\n for (var i = 0; i < btns.length; i++) btns[i].classList.toggle(\"active\", btns[i].getAttribute(\"data-theme-set\") === mode);\n }\n document.getElementById(\"theme\").addEventListener(\"click\", function (e) {\n var b = e.target.closest ? e.target.closest(\"[data-theme-set]\") : null;\n if (b) applyTheme(b.getAttribute(\"data-theme-set\"));\n });\n if (mql && mql.addEventListener) mql.addEventListener(\"change\", function () {\n var cur = \"system\";\n try { cur = localStorage.getItem(THEME_KEY) || \"system\"; } catch (e) {}\n if (cur === \"system\") applyTheme(\"system\");\n });\n var savedTheme = \"system\";\n try { savedTheme = localStorage.getItem(THEME_KEY) || \"system\"; } catch (e) {}\n applyTheme(savedTheme);\n\n function poll() {\n Promise.all([\n fetchAuthed(API + \"/aggregate\").then(function (r) { return r.json(); }),\n fetchAuthed(API + \"/traces\").then(function (r) { return r.json(); })\n ]).then(function (res) {\n renderStats(res[0]);\n state.traces = res[1] || [];\n document.getElementById(\"meta\").textContent = state.traces.length + \" trace(s) · live\";\n renderChips();\n renderList();\n // Open whatever the URL hash deep-links to, once the target trace\n // has actually arrived in a poll (it may not be in the first batch).\n if (!state.hashApplied) {\n if (applyHash()) state.hashApplied = true;\n } else if (state.selectedId && openDetail() && state.loadingId === null) {\n // Re-fetch the open trace only when its summary changed.\n var t = findTrace(state.selectedId);\n if (t && traceSig(t) !== state.sig) loadDetail(state.selectedId);\n }\n }).catch(function (e) {\n document.getElementById(\"meta\").textContent = \"disconnected\";\n });\n }\n\n // FOLLOW-UP: a live socket tail (SSE / WebSocket push) is out of scope\n // for this pass; the dashboard stays on the 2s JSON poll below. When\n // added, it should reuse renderList/renderDrawer and keep the poll as a\n // reconnect fallback.\n poll();\n setInterval(poll, 2000);\n})();\n</script>\n</body>\n</html>`;\n}\n\n/** Escape a string for safe interpolation into static HTML text. */\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n/**\n * Encode free-form text (e.g. `evaluate.instructions`, which an operator\n * could type anything into) as a JS EXPRESSION that reconstructs it at\n * runtime, WITHOUT ever emitting a literal backtick into the served page —\n * the client script is itself built from a TS template literal, so a raw\n * backtick in the output would be a real syntax hazard (see the `BT =\n * String.fromCharCode(96)` construction already in the client script for\n * the same reason). `JSON.stringify` alone doesn't escape backticks (they\n * aren't JSON-significant), so a value containing one is split around it\n * and rejoined with the client's own `BT` constant. No backticks in the\n * input ⇒ a single plain `JSON.stringify(value)` — no unnecessary\n * concatenation in the common case.\n */\nfunction encodeForInlineScript(value: string): string {\n return value\n .split(\"`\")\n .map((part) => JSON.stringify(part))\n .join(\" + BT + \");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,cACd,UACA,OACA,kBAA2B,OAC3B,8BAAsC,IAC9B;CACR,MAAM,UAAU,GAAG,SAAS;CAC5B,MAAM,YAAY,WAAW,KAAK;CAElC,OAAO;;;;;SAKA,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BA+MQ,sBAAsB;QACzC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAwCJ,KAAK,UAAU,OAAO,EAAE;2BACX,KAAK,UAAU,eAAe,EAAE;;wCAEnB,sBAAsB,2BAA2B,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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