@warlock.js/ai-panoptic 5.52.0 → 5.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/cjs/index.cjs +592 -424
- 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.d.mts.map +1 -1
- package/esm/config/apply-panoptic-config.mjs +9 -3
- package/esm/config/apply-panoptic-config.mjs.map +1 -1
- package/esm/config/panoptic-config.type.d.mts +7 -0
- package/esm/config/panoptic-config.type.d.mts.map +1 -1
- package/esm/dashboard/dashboard.mjs.map +1 -1
- package/esm/dashboard/index.d.mts +1 -0
- package/esm/dashboard/index.mjs +1 -1
- package/esm/dashboard/parse-query.mjs +23 -1
- package/esm/dashboard/parse-query.mjs.map +1 -1
- package/esm/dashboard/serve.mjs +55 -10
- package/esm/dashboard/serve.mjs.map +1 -1
- package/esm/dashboard/trace-filter.mjs.map +1 -1
- package/esm/dashboard/trace-summary.d.mts +24 -0
- package/esm/dashboard/trace-summary.d.mts.map +1 -0
- package/esm/dashboard/trace-summary.mjs +27 -0
- package/esm/dashboard/trace-summary.mjs.map +1 -0
- package/esm/dashboard/ui.html.mjs +68 -18
- package/esm/dashboard/ui.html.mjs.map +1 -1
- package/esm/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/index.d.mts +2 -1
- package/esm/index.mjs +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.d.mts.map +1 -1
- package/esm/store/cache-trace-store.mjs +37 -17
- package/esm/store/cache-trace-store.mjs.map +1 -1
- package/esm/store/in-memory-trace-store.d.mts.map +1 -1
- package/esm/store/in-memory-trace-store.mjs +2 -9
- package/esm/store/in-memory-trace-store.mjs.map +1 -1
- package/esm/store/match-trace.mjs.map +1 -1
- package/esm/store/sort-newest-first.mjs +14 -0
- package/esm/store/sort-newest-first.mjs.map +1 -0
- package/esm/store/sum-usage.mjs.map +1 -1
- package/llms-full.txt +9 -9
- package/llms.txt +1 -1
- package/package.json +4 -4
- package/skills/use-local-dashboard/SKILL.md +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otel-exporter.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/otel/otel-exporter.ts"],"sourcesContent":["import type { ExporterContract, Trace, TraceSpan } from \"../../contracts\";\nimport { toGenAiAttributes, GEN_AI_ATTRIBUTES } from \"../utils\";\nimport type {\n OtelApiModule,\n OtelContext,\n OtelSpan,\n OtelSpanStatusCode,\n OtelTracer,\n} from \"./otel-api.shim.type\";\nimport type { OtelExporterOptions } from \"./otel-exporter.type\";\n\nconst EXPORTER_NAME = \"otel\";\nconst DEFAULT_TRACER_NAME = \"@warlock.js/ai-panoptic\";\n\n// ============================================================\n// Lazily-loaded @opentelemetry/api (OPTIONAL peer)\n// ============================================================\n\nlet OtelApi: OtelApiModule;\nlet isModuleExists: boolean | null = null;\nlet loadingPromise: Promise<void> | undefined;\n\nconst OTEL_INSTALL_INSTRUCTIONS = `\nThe Panoptic OpenTelemetry exporter requires the @opentelemetry/api package.\nInstall it with:\n\n npm install @opentelemetry/api\n\nOr with your preferred package manager:\n\n pnpm add @opentelemetry/api\n yarn add @opentelemetry/api\n`.trim();\n\n/**\n * Settle the lazy import of `@opentelemetry/api` once, concurrency-safe.\n * A bare `catch` flips the flag to `false`; the curated install string\n * surfaces at use time so a missing SDK never throws a raw module\n * resolution error.\n */\nfunction loadOtel(): Promise<void> {\n if (isModuleExists !== null) {\n return Promise.resolve();\n }\n\n if (loadingPromise) {\n return loadingPromise;\n }\n\n loadingPromise = (async () => {\n try {\n // Indirect specifier so TS does not statically resolve the\n // optional `@opentelemetry/api` peer at compile time (it is\n // intentionally not installed). The result is structurally the\n // `OtelApiModule` shim — the exporter only touches that surface.\n const moduleName = \"@opentelemetry/api\";\n OtelApi = (await import(moduleName)) as OtelApiModule;\n isModuleExists = true;\n } catch {\n isModuleExists = false;\n }\n })();\n\n return loadingPromise;\n}\n\n/**\n * {@link ExporterContract} that maps Panoptic traces onto OpenTelemetry\n * spans following the GenAI semantic conventions (`gen_ai.*`\n * attributes). Lazily imports `@opentelemetry/api` so it stays an\n * OPTIONAL peer — importing this module never forces the SDK to be\n * installed, and a missing SDK surfaces as a curated \"install this\"\n * error on first `export`, not a boot-time stack trace.\n *\n * The exporter emits onto a `Tracer` you supply (or fetches one from the\n * globally registered provider). It never configures the SDK — wiring a\n * `TracerProvider`, processors, and span exporters is the host app's\n * job, exactly as with any other OTel instrumentation.\n *\n * Each {@link TraceSpan} becomes one OTel span with the source span's\n * start/end times and parent relationship reconstructed, so the emitted\n * tree matches the original execution tree.\n *\n * @example\n * // app already set up @opentelemetry/sdk-trace-base + a provider\n * collector.use(otelExporter({ tracerName: \"my-app\", system: \"openai\" }));\n */\nexport function otelExporter(options: OtelExporterOptions = {}): ExporterContract {\n loadOtel();\n\n return {\n name: EXPORTER_NAME,\n async export(trace: Trace): Promise<void> {\n await loadOtel();\n\n if (!isModuleExists) {\n throw new Error(OTEL_INSTALL_INSTRUCTIONS);\n }\n\n const tracer = resolveTracer(options);\n emitSpan(tracer, trace.root, undefined, options);\n },\n };\n}\n\n/**\n * Resolve the `Tracer` spans are emitted on — the caller-supplied one,\n * or one fetched from the globally registered provider by name.\n */\nfunction resolveTracer(options: OtelExporterOptions): OtelTracer {\n if (options.tracer) {\n return options.tracer;\n }\n\n return OtelApi.trace.getTracer(options.tracerName ?? DEFAULT_TRACER_NAME, options.tracerVersion);\n}\n\n/**\n * Recreate one {@link TraceSpan} (and its subtree) as OTel spans. The\n * span is started with the source `startedAt`, parented under\n * `parentContext` so the tree is preserved, annotated with GenAI\n * attributes, given the mapped status, and ended at `endedAt`. Children\n * recurse under this span's context.\n */\nfunction emitSpan(\n tracer: OtelTracer,\n span: TraceSpan,\n parentContext: OtelContext | undefined,\n options: OtelExporterOptions,\n): void {\n const startTime = toEpochMillis(span.startedAt);\n const baseContext = parentContext ?? OtelApi.context.active();\n\n const otelSpan = tracer.startSpan(span.name, { startTime }, baseContext);\n\n applyAttributes(otelSpan, span, options);\n applyStatus(otelSpan, span);\n\n const childContext = OtelApi.trace.setSpan(baseContext, otelSpan);\n\n for (const child of span.children) {\n emitSpan(tracer, child, childContext, options);\n }\n\n otelSpan.end(toEpochMillis(span.endedAt));\n}\n\n/**\n * Set the GenAI + Warlock attributes on the OTel span, defaulting\n * `gen_ai.system` from the exporter options when the span carried none.\n */\nfunction applyAttributes(otelSpan: OtelSpan, span: TraceSpan, options: OtelExporterOptions): void {\n const attributes = toGenAiAttributes(span);\n\n if (options.system !== undefined && attributes[GEN_AI_ATTRIBUTES.system] === undefined) {\n attributes[GEN_AI_ATTRIBUTES.system] = options.system;\n }\n\n // Captured content (only present under `captureContent`) maps onto the\n // GenAI prompt/completion attributes, stringified since OTel attribute\n // values must be primitives.\n if (span.input !== undefined) {\n attributes[GEN_AI_ATTRIBUTES.prompt] = stringifyContent(span.input);\n }\n\n if (span.output !== undefined) {\n attributes[GEN_AI_ATTRIBUTES.completion] = stringifyContent(span.output);\n }\n\n otelSpan.setAttributes(attributes);\n}\n\n/**\n * Coerce a captured content value to a string OTel attribute. Strings\n * pass through; structured values are JSON-encoded (falling back to\n * `String()` if they can't be serialized).\n */\nfunction stringifyContent(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Map the Panoptic span status onto the OTel span status, recording the\n * normalized error as an exception event + ERROR status when present.\n */\nfunction applyStatus(otelSpan: OtelSpan, span: TraceSpan): void {\n const codes: OtelSpanStatusCode = OtelApi.SpanStatusCode;\n\n if (span.error) {\n otelSpan.recordException({\n name: span.error.type,\n message: span.error.message,\n stack: span.error.stack,\n });\n }\n\n // An incomplete run (the model's answer was cut off) has no usable\n // result, so it is an error like a failed one.\n if (span.status === \"failed\" || span.status === \"cancelled\" || span.status === \"incomplete\") {\n otelSpan.setStatus({\n code: codes.ERROR,\n message: span.error?.message,\n });\n return;\n }\n\n // A capped / paused run is neither a failure nor a clean success.\n // Mapping it to OK would let a hit iteration cap read as a healthy\n // run; leave the OTel status UNSET with a descriptive message so the\n // outcome is visible without being miscounted as an error.\n if (span.status === \"max-iterations\" || span.status === \"awaiting-input\") {\n otelSpan.setStatus({\n code: codes.UNSET,\n message:\n span.status === \"max-iterations\"\n ? \"Run hit the iteration cap without an explicit end\"\n : \"Run is awaiting the next input turn\",\n });\n return;\n }\n\n otelSpan.setStatus({ code: codes.OK });\n}\n\n/**\n * Convert an ISO-8601 timestamp to epoch milliseconds — the `TimeInput`\n * form OTel's `startSpan` / `Span.end` accept directly.\n */\nfunction toEpochMillis(isoTimestamp: string): number {\n return new Date(isoTimestamp).getTime();\n}\n"],"mappings":";;;;AAWA,MAAM,gBAAgB;AACtB,MAAM,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AkB,IAAI;CAEzC,IAAI,QAAQ,WAAW,UAAa,WAAW,kBAAkB,YAAY,QAC3E,WAAW,kBAAkB,UAAU,QAAQ;CAMjD,IAAI,KAAK,UAAU,QACjB,WAAW,kBAAkB,UAAU,iBAAiB,KAAK,KAAK;CAGpE,IAAI,KAAK,WAAW,QAClB,WAAW,kBAAkB,cAAc,iBAAiB,KAAK,MAAM;CAGzE,SAAS,cAAc,UAAU;AACnC;;;;;;AAOA,SAAS,iBAAiB,OAAwB;CAChD,IAAI,OAAO,UAAU,UACnB,OAAO;CAGT,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;;;;AAMA,SAAS,YAAY,UAAoB,MAAuB;CAC9D,MAAM,QAA4B,QAAQ;CAE1C,IAAI,KAAK,OACP,SAAS,gBAAgB;EACvB,MAAM,KAAK,MAAM;EACjB,SAAS,KAAK,MAAM;EACpB,OAAO,KAAK,MAAM;CACpB,CAAC;CAKH,IAAI,KAAK,WAAW,YAAY,KAAK,WAAW,eAAe,KAAK,WAAW,cAAc;EAC3F,SAAS,UAAU;GACjB,MAAM,MAAM;GACZ,SAAS,KAAK,OAAO;EACvB,CAAC;EACD;CACF;CAMA,IAAI,KAAK,WAAW,oBAAoB,KAAK,WAAW,kBAAkB;EACxE,SAAS,UAAU;GACjB,MAAM,MAAM;GACZ,SACE,KAAK,WAAW,mBACZ,sDACA;EACR,CAAC;EACD;CACF;CAEA,SAAS,UAAU,EAAE,MAAM,MAAM,GAAG,CAAC;AACvC;;;;;AAMA,SAAS,cAAc,cAA8B;CACnD,OAAO,IAAI,KAAK,YAAY,CAAC,CAAC,QAAQ;AACxC"}
|
|
1
|
+
{"version":3,"file":"otel-exporter.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/otel/otel-exporter.ts"],"mappings":";;;;AAWA,MAAM,gBAAgB;AACtB,MAAM,sBAAsB;AAM5B,I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,IAAI,QAAQ,WAAW,UAAa,WAAW,kBAAkB,YAAY,QAC3E,WAAW,kBAAkB,UAAU,QAAQ;CAMjD,IAAI,KAAK,UAAU,QACjB,WAAW,kBAAkB,UAAU,iBAAiB,KAAK,KAAK;CAGpE,IAAI,KAAK,WAAW,QAClB,WAAW,kBAAkB,cAAc,iBAAiB,KAAK,MAAM;CAGzE,SAAS,cAAc,UAAU;AACnC;;;;;;AAOA,SAAS,iBAAiB,OAAwB;CAChD,IAAI,OAAO,UAAU,UACnB,OAAO;CAGT,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC9C,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;;;;AAMA,SAAS,YAAY,UAAoB,MAAuB;CAC9D,MAAM,QAA4B,QAAQ;CAE1C,IAAI,KAAK,OACP,SAAS,gBAAgB;EACvB,MAAM,KAAK,MAAM;EACjB,SAAS,KAAK,MAAM;EACpB,OAAO,KAAK,MAAM;CACpB,CAAC;CAKH,IAAI,KAAK,WAAW,YAAY,KAAK,WAAW,eAAe,KAAK,WAAW,cAAc;EAC3F,SAAS,UAAU;GACjB,MAAM,MAAM;GACZ,SAAS,KAAK,OAAO;EACvB,CAAC;EACD;CACF;CAMA,IAAI,KAAK,WAAW,oBAAoB,KAAK,WAAW,kBAAkB;EACxE,SAAS,UAAU;GACjB,MAAM,MAAM;GACZ,SACE,KAAK,WAAW,mBACZ,sDACA;EACR,CAAC;EACD;CACF;CAEA,SAAS,UAAU,EAAE,MAAM,MAAM,GAAG,CAAC;AACvC;;;;;AAMA,SAAS,cAAc,cAA8B;CACnD,OAAO,IAAI,KAAK,YAAY,CAAC,CAAC,QAAQ;AACxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gen-ai-attributes.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/utils/gen-ai-attributes.ts"],"
|
|
1
|
+
{"version":3,"file":"gen-ai-attributes.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/utils/gen-ai-attributes.ts"],"mappings":";;;;;;;;;;;AAWA,MAAa,oBAAoB;CAC/B,eAAe;CACf,QAAQ;CACR,cAAc;CACd,eAAe;CACf,kBAAkB;CAClB,mBAAmB;CACnB,gBAAgB;;CAEhB,QAAQ;;CAER,YAAY;AACd;;;;;;AAOA,MAAa,qBAAqB;CAChC,YAAY;CACZ,SAAS;CACT,YAAY;CACZ,aAAa;CACb,cAAc;CACd,iBAAiB;CACjB,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,kBAAkB,MAAiD;CACjF,MAAM,aAA6C;GAChD,mBAAmB,aAAa,KAAK;GACrC,mBAAmB,aAAa,KAAK;GACrC,mBAAmB,cAAc,KAAK,MAAM;GAC5C,kBAAkB,mBAAmB,KAAK,MAAM;GAChD,kBAAkB,oBAAoB,KAAK,MAAM;CACpD;CAEA,IAAI,KAAK,YAAY,QACnB,WAAW,mBAAmB,WAAW,KAAK;CAGhD,IAAI,KAAK,cAAc,QACrB,WAAW,kBAAkB,kBAAkB,KAAK;CAGtD,IAAI,KAAK,MAAM,iBAAiB,QAC9B,WAAW,mBAAmB,gBAAgB,KAAK,MAAM;CAG3D,IAAI,KAAK,MAAM,oBAAoB,QACjC,WAAW,mBAAmB,mBAAmB,KAAK,MAAM;CAG9D,MAAM,OAAO,aAAa,KAAK,KAAK;CAEpC,IAAI,SAAS,QACX,WAAW,mBAAmB,WAAW;CAG3C,sBAAsB,YAAY,KAAK,UAAU;CAEjD,OAAO;AACT;;;;;;;;AASA,SAAS,sBACP,QACA,QACM;CACN,IAAI,CAAC,QACH;CAGF,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAC7E,OAAO,OAAO;AAGpB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"total-cost.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/utils/total-cost.ts"],"
|
|
1
|
+
{"version":3,"file":"total-cost.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/utils/total-cost.ts"],"mappings":";;;;;;;;;;;;;;AAaA,SAAgB,aAAa,OAAkC;CAC7D,OAAO,UAAU,MAAM,IAAI;AAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"walk-spans.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/utils/walk-spans.ts"],"
|
|
1
|
+
{"version":3,"file":"walk-spans.mjs","names":[],"sources":["../../../../../../../../../packages/ai-panoptic/src/exporters/utils/walk-spans.ts"],"mappings":";;;;;;;;;;;;;AAcA,UAAiB,UAAU,MAAuC;CAChE,MAAM;CAEN,KAAK,MAAM,SAAS,KAAK,UACvB,OAAO,UAAU,KAAK;AAE1B"}
|
package/esm/index.d.mts
CHANGED
|
@@ -45,9 +45,10 @@ import "./evaluate/index.mjs";
|
|
|
45
45
|
import { DashboardHandle, DashboardOptions } from "./dashboard/dashboard.type.mjs";
|
|
46
46
|
import { dashboard } from "./dashboard/dashboard.mjs";
|
|
47
47
|
import { NO_PROMPT_KEY, NO_SESSION_KEY, NO_TYPE_KEY, PromptGroup, SessionGroup, TraceFilter, TypeGroup, TypeStat, aggregateByType, filterTraces, groupByPrompt, groupBySession, groupByType, heatIntensity, matchesFilter, maxNodeCost, percentile, rollupCost, traceCost, tracePromptKey } from "./dashboard/trace-filter.mjs";
|
|
48
|
+
import { TraceSpanSummary, TraceSummary } from "./dashboard/trace-summary.mjs";
|
|
48
49
|
import "./dashboard/index.mjs";
|
|
49
50
|
import { PanopticConfig } from "./config/panoptic-config.type.mjs";
|
|
50
51
|
import { applyPanopticConfig } from "./config/apply-panoptic-config.mjs";
|
|
51
52
|
import "./config/index.mjs";
|
|
52
|
-
export { type AttributeValue, type CacheDriverInput, type CacheTraceStoreHandle, type CacheTraceStoreOptions, type CollectorContract, type CollectorOptions, type CompletedEventPayload, type ConsoleExporterOptions, type ConsoleLike, type ContentCaptureOptions, type ContentRedactor, type DashboardHandle, type DashboardOptions, type EvaluateConfig, type EvaluateVerdict, type ExporterContract, type ExporterErrorHandler, type FileExporterOptions, GEN_AI_ATTRIBUTES, type InMemoryTraceStoreOptions, type LangfuseClientLike, type LangfuseExporterOptions, type LangfuseObservationBody, type LangfuseObservationEndBody, type LangfuseObservationLevel, type LangfuseObservationLike, type LangfuseTraceBody, type LangfuseTraceLike, type LangfuseUsageBody, NO_PROMPT_KEY, NO_SESSION_KEY, NO_TYPE_KEY, type OtelExporterOptions, type Panoptic, type PanopticConfig, type PanopticOptions, type PanopticTarget, type PromptGroup, type SessionGroup, type Trace, type TraceAggregate, type TraceFilter, type TraceListener, type TraceQuery, type TraceRecord, type TraceSpan, type TraceSpanError, type TraceStoreContract, type TypeGroup, type TypeStat, WARLOCK_ATTRIBUTES, aggregateByType, applyPanopticConfig, consoleExporter, createCacheTraceStore, createCollector, createInMemoryTraceStore, createPanopticMiddleware, dashboard, emptyUsage, evaluateSystemPrompt, extractLastSystemPrompt, extractSpanAttributes, fileExporter, filterTraces, findSpanById, formatSpanIO, formatSpanLine, groupByPrompt, groupBySession, groupByType, heatIntensity, langfuseExporter, matchTrace, matchesFilter, maxNodeCost, normalizeError, otelExporter, panoptic, percentile, reportToSpan, reportToTrace, rollupCost, subscribeTraces, sumUsage, toGenAiAttributes, totalCostUsd, traceCost, tracePromptKey, walkSpans };
|
|
53
|
+
export { type AttributeValue, type CacheDriverInput, type CacheTraceStoreHandle, type CacheTraceStoreOptions, type CollectorContract, type CollectorOptions, type CompletedEventPayload, type ConsoleExporterOptions, type ConsoleLike, type ContentCaptureOptions, type ContentRedactor, type DashboardHandle, type DashboardOptions, type EvaluateConfig, type EvaluateVerdict, type ExporterContract, type ExporterErrorHandler, type FileExporterOptions, GEN_AI_ATTRIBUTES, type InMemoryTraceStoreOptions, type LangfuseClientLike, type LangfuseExporterOptions, type LangfuseObservationBody, type LangfuseObservationEndBody, type LangfuseObservationLevel, type LangfuseObservationLike, type LangfuseTraceBody, type LangfuseTraceLike, type LangfuseUsageBody, NO_PROMPT_KEY, NO_SESSION_KEY, NO_TYPE_KEY, type OtelExporterOptions, type Panoptic, type PanopticConfig, type PanopticOptions, type PanopticTarget, type PromptGroup, type SessionGroup, type Trace, type TraceAggregate, type TraceFilter, type TraceListener, type TraceQuery, type TraceRecord, type TraceSpan, type TraceSpanError, type TraceSpanSummary, type TraceStoreContract, type TraceSummary, type TypeGroup, type TypeStat, WARLOCK_ATTRIBUTES, aggregateByType, applyPanopticConfig, consoleExporter, createCacheTraceStore, createCollector, createInMemoryTraceStore, createPanopticMiddleware, dashboard, emptyUsage, evaluateSystemPrompt, extractLastSystemPrompt, extractSpanAttributes, fileExporter, filterTraces, findSpanById, formatSpanIO, formatSpanLine, groupByPrompt, groupBySession, groupByType, heatIntensity, langfuseExporter, matchTrace, matchesFilter, maxNodeCost, normalizeError, otelExporter, panoptic, percentile, reportToSpan, reportToTrace, rollupCost, subscribeTraces, sumUsage, toGenAiAttributes, totalCostUsd, traceCost, tracePromptKey, walkSpans };
|
|
53
54
|
import "./config/panoptic-config.type.mjs";
|
package/esm/index.mjs
CHANGED
|
@@ -27,8 +27,8 @@ import { evaluateSystemPrompt } from "./evaluate/evaluate-system-prompt.mjs";
|
|
|
27
27
|
import { extractLastSystemPrompt } from "./evaluate/extract-last-system-prompt.mjs";
|
|
28
28
|
import { findSpanById } from "./evaluate/find-span-by-id.mjs";
|
|
29
29
|
import "./evaluate/index.mjs";
|
|
30
|
-
import { dashboard } from "./dashboard/dashboard.mjs";
|
|
31
30
|
import { NO_PROMPT_KEY, NO_SESSION_KEY, NO_TYPE_KEY, aggregateByType, filterTraces, groupByPrompt, groupBySession, groupByType, heatIntensity, matchesFilter, maxNodeCost, percentile, rollupCost, traceCost, tracePromptKey } from "./dashboard/trace-filter.mjs";
|
|
31
|
+
import { dashboard } from "./dashboard/dashboard.mjs";
|
|
32
32
|
import "./dashboard/index.mjs";
|
|
33
33
|
import { applyPanopticConfig } from "./config/apply-panoptic-config.mjs";
|
|
34
34
|
import "./config/index.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"panoptic-middleware.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/panoptic/panoptic-middleware.ts"],"
|
|
1
|
+
{"version":3,"file":"panoptic-middleware.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/panoptic/panoptic-middleware.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,yBACd,WACA,OAAO,YACU;CACjB,MAAM,iBAAiB,QAAiB,cAA8B;EACpE,IAAI,CAAC,SAAS,MAAM,GAClB;EAGF,AAAK,UAAU,QAAQ,QAAQ,SAAS,CAAC,CAAC,YAAY,CAGtD,CAAC;CACH;CAEA,MAAM,YAAY,WAA0B;EAG1C,cAAe,OAAgC,QAAS,OAA+B,KAAK;CAC9F;CAEA,MAAM,WAAW,UAAyB;EAIxC,cAAe,MAA+B,QAAQ,KAAK;CAC7D;CAEA,MAAM,gBAAgB;EACpB,MAAM,MAAe,QAAiB;GACpC,SAAS,MAAM;EACjB;EACA,QAAQ,MAAe,OAAgB;GACrC,QAAQ,KAAK;EACf;CACF;CAEA,OAAO;EACL;EACA,SAAS;EACT,YAAY;CACd;AACF;;;;;;AAOA,SAAS,SAAS,OAA8D;CAC9E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA8B,UAAU,YAChD,OAAQ,MAAkC,cAAc;AAE5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"panoptic.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/panoptic/panoptic.ts"],"
|
|
1
|
+
{"version":3,"file":"panoptic.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/panoptic/panoptic.ts"],"mappings":";;;;;;;;;;;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AAY,gBAAgB,OAAO;EAEzC,AAAK,KAAK,UAAU,QAAQ,QAAQ,SAAS,CAAC,CAAC,YAAY,CAE3D,CAAC;CACH;AACF;;;;;;;AAQA,SAAS,gBAAgB,SAA2B;CAGlD,QAFgB,SAA4C,OAE9C,EAA0B;AAC1C;;;;;;;AAQA,SAAS,WAAW,SAA0C;CAE5D,MAAM,UADU,SAA4C,OACtC,EAA2B;CAEjD,IACE,OAAO,WAAW,YAClB,WAAW,QACX,OAAQ,OAA+B,UAAU,YACjD,OAAQ,OAAmC,cAAc,UAEzD,OAAO;AAIX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,SAAS,UAA2B,CAAC,GAAa;CAChE,OAAO,IAAI,mBAAmB,OAAO;AACvC"}
|
package/esm/register.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.mjs","names":[],"sources":["../../../../../../../packages/ai-panoptic/src/register.ts"],"
|
|
1
|
+
{"version":3,"file":"register.mjs","names":[],"sources":["../../../../../../../packages/ai-panoptic/src/register.ts"],"mappings":";;;;AAUA,iBAAiB,WAAW;CAC1B,oBAAoB,OAAO,QAAQ;AACrC,CAAC;AAID,oBAAoB,YAAY,CAAC,CAAC,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-trace-store.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/cache-trace-store.ts"],"mappings":";;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"cache-trace-store.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/cache-trace-store.ts"],"mappings":";;;;;;;;;;;;;;;YAqBY,mBAIR,+BAEO,wBAAwB,QAAQ;;;;YAK/B;;;;;;EAMV;;;;;;EAMA;;;;;;;;YA6ZU,wBAAwB,qBAClC;;;;;;EAME,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA8BG,sBACd,OAAO,kBACP,UAAS;EAA2B,WAAW;IAC9C"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { matchTrace } from "./match-trace.mjs";
|
|
2
|
+
import { sortNewestFirst } from "./sort-newest-first.mjs";
|
|
2
3
|
import { emptyUsage, sumUsage } from "./sum-usage.mjs";
|
|
3
4
|
|
|
4
5
|
//#region ../../packages/ai-panoptic/src/store/cache-trace-store.ts
|
|
@@ -58,6 +59,15 @@ var CacheTraceStore = class {
|
|
|
58
59
|
resolvedDriver;
|
|
59
60
|
driverPending;
|
|
60
61
|
onError;
|
|
62
|
+
/**
|
|
63
|
+
* Every cache write runs on this one chain, in `add` order, so an older
|
|
64
|
+
* index can never land after a newer one.
|
|
65
|
+
*/
|
|
66
|
+
writes = Promise.resolve();
|
|
67
|
+
/** Trace writes queued on {@link writes} and not yet finished. */
|
|
68
|
+
pendingWrites = 0;
|
|
69
|
+
/** The persisted index is behind the mirror and must be rewritten. */
|
|
70
|
+
indexDirty = false;
|
|
61
71
|
constructor(input, options = {}) {
|
|
62
72
|
this.input = input;
|
|
63
73
|
this.prefix = options.prefix ?? DEFAULT_PREFIX;
|
|
@@ -97,10 +107,11 @@ var CacheTraceStore = class {
|
|
|
97
107
|
add(trace) {
|
|
98
108
|
this.mirror.delete(trace.traceId);
|
|
99
109
|
this.mirror.set(trace.traceId, trace);
|
|
100
|
-
const addedAt = this.addCounter;
|
|
101
110
|
this.addCounter += 1;
|
|
102
111
|
const evicted = this.evictOverflow();
|
|
103
|
-
this.
|
|
112
|
+
this.indexDirty = true;
|
|
113
|
+
this.pendingWrites += 1;
|
|
114
|
+
this.enqueue(() => this.persist(trace, evicted));
|
|
104
115
|
}
|
|
105
116
|
/**
|
|
106
117
|
* `ExporterContract.export` — a collector dispatches a completed trace
|
|
@@ -115,7 +126,7 @@ var CacheTraceStore = class {
|
|
|
115
126
|
query(filter) {
|
|
116
127
|
const matched = [];
|
|
117
128
|
for (const trace of this.mirror.values()) if (matchTrace(trace, filter)) matched.push(trace);
|
|
118
|
-
return
|
|
129
|
+
return sortNewestFirst(matched);
|
|
119
130
|
}
|
|
120
131
|
aggregate(filter) {
|
|
121
132
|
const aggregate = {
|
|
@@ -139,20 +150,36 @@ var CacheTraceStore = class {
|
|
|
139
150
|
clear() {
|
|
140
151
|
const ids = [...this.mirror.keys()];
|
|
141
152
|
this.mirror.clear();
|
|
142
|
-
this.
|
|
153
|
+
this.indexDirty = false;
|
|
154
|
+
this.enqueue(() => this.purge(ids));
|
|
155
|
+
}
|
|
156
|
+
/** Append one write to the serial write chain. */
|
|
157
|
+
enqueue(write) {
|
|
158
|
+
this.writes = this.writes.then(write);
|
|
143
159
|
}
|
|
144
160
|
/**
|
|
145
|
-
* Persist one trace
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
*
|
|
161
|
+
* Persist one trace to the cache, optionally removing a trace evicted by
|
|
162
|
+
* the capacity cap, then — when no later trace write is queued — the
|
|
163
|
+
* index rebuilt from the mirror. A burst of adds therefore writes the
|
|
164
|
+
* index once, after every trace in the burst. Best-effort: any cache
|
|
165
|
+
* failure is routed to `onError`, never thrown — the mirror already
|
|
166
|
+
* reflects the write so runtime reads are unaffected.
|
|
149
167
|
*/
|
|
150
|
-
async persist(trace,
|
|
168
|
+
async persist(trace, evictedId) {
|
|
169
|
+
this.pendingWrites -= 1;
|
|
151
170
|
try {
|
|
152
171
|
const driver = await this.resolveDriver();
|
|
153
172
|
await driver.set(this.traceKey(trace.traceId), trace);
|
|
154
173
|
if (evictedId !== void 0) await driver.remove(this.traceKey(evictedId));
|
|
155
|
-
|
|
174
|
+
if (this.pendingWrites === 0 && this.indexDirty) {
|
|
175
|
+
this.indexDirty = false;
|
|
176
|
+
try {
|
|
177
|
+
await driver.set(this.indexKey(), this.buildIndex(this.addCounter - 1));
|
|
178
|
+
} catch (error) {
|
|
179
|
+
this.indexDirty = true;
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
156
183
|
} catch (error) {
|
|
157
184
|
this.reportError(error);
|
|
158
185
|
}
|
|
@@ -228,13 +255,6 @@ var CacheTraceStore = class {
|
|
|
228
255
|
}
|
|
229
256
|
}
|
|
230
257
|
/**
|
|
231
|
-
* Sort matched traces newest-started first. A copy is sorted so the
|
|
232
|
-
* mirror's insertion order (which eviction depends on) is never disturbed.
|
|
233
|
-
*/
|
|
234
|
-
sortNewestFirst(traces) {
|
|
235
|
-
return traces.sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt));
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
258
|
* Evict oldest-inserted traces from the mirror until within `capacity`.
|
|
239
259
|
* Returns the id of the single evicted trace (the common case — one `add`
|
|
240
260
|
* pushes at most one over the cap) so the caller can remove it from the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-trace-store.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/cache-trace-store.ts"],"sourcesContent":["import type { CacheDriver } from \"@warlock.js/cache\";\nimport type { ExporterContract } from \"../contracts/exporter.contract\";\nimport type { Trace } from \"../contracts/trace.type\";\nimport { matchTrace } from \"./match-trace\";\nimport { emptyUsage, sumUsage } from \"./sum-usage\";\nimport type { TraceAggregate } from \"./trace-aggregate.type\";\nimport type { TraceQuery } from \"./trace-query.type\";\nimport type { TraceStoreContract } from \"./trace-store.contract\";\n\n/**\n * A {@link CacheDriver} instance, or a (possibly async) factory that\n * yields one on first use. The factory form lets production defer an\n * expensive connect (e.g. the Redis handshake) until the first trace is\n * actually written, and keeps the dashboard wiring free of a live driver\n * at module-import time.\n *\n * Typed `CacheDriver<any, any>` because the store only ever touches the\n * driver's `get` / `set` / `remove` surface and is agnostic to the\n * concrete client + options of whichever driver backs it.\n */\nexport type CacheDriverInput =\n // The store is driver-agnostic; it only uses get/set/remove, so the\n // concrete client/options generics are intentionally unconstrained.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | CacheDriver<any, any>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (() => CacheDriver<any, any> | Promise<CacheDriver<any, any>>);\n\n/**\n * Options for {@link createCacheTraceStore}.\n */\nexport type CacheTraceStoreOptions = {\n /**\n * Key prefix every cache entry this store writes is namespaced under.\n * Per-trace keys are `${prefix}:trace:${traceId}`; the newest-first\n * index lives at `${prefix}:index`. Default `\"panoptic\"`.\n */\n prefix?: string;\n /**\n * Maximum number of traces to retain. When set and exceeded, the\n * oldest-ingested trace is evicted from both the cache and the in-memory\n * mirror (insertion-order FIFO). Absent / `0` = unbounded.\n */\n capacity?: number;\n};\n\n/** One entry in the persisted newest-first index. */\ntype IndexEntry = {\n /** The trace's `traceId` — the suffix of its `${prefix}:trace:` key. */\n id: string;\n /**\n * Monotonic insertion order from an internal counter — NOT a wall clock.\n * Used only to keep the index in stable insertion order across a restart\n * so FIFO eviction stays honest.\n */\n addedAt: number;\n};\n\nconst DEFAULT_PREFIX = \"panoptic\";\n\n/**\n * Cache-backed {@link TraceStoreContract} with a **write-through** design\n * that reconciles the synchronous store contract with an asynchronous\n * cache driver.\n *\n * **How the sync/async tension is resolved.** The contract's `get` /\n * `query` / `aggregate` / `size` are synchronous (the dashboard polls them\n * on every request and the in-memory store answers instantly). A cache\n * driver is async. So this store keeps an **in-memory read mirror** — the\n * same insertion-ordered `Map<traceId, Trace>` the in-memory store uses —\n * and serves every read from it synchronously. Writes go **through** to the\n * cache: `add` updates the mirror immediately, then asynchronously persists\n * the trace + index to the cache (errors are swallowed via an optional\n * `onError` hook so a flaky cache never throws into the collector's hot\n * path). On process restart, {@link CacheTraceStore.ready} re-hydrates the\n * mirror from the cache so traces survive the restart.\n *\n * **Durability is best-effort.** Reads never wait on the cache; the mirror\n * is the source of truth at runtime and the cache is the durable backing\n * store. A write that the cache rejects is still visible in the mirror for\n * the life of the process — it just won't survive a restart.\n *\n * **Lazy driver resolution.** The driver (or its async factory) is resolved\n * on first use and memoized, so a production deployment can defer the Redis\n * connect until the first trace is collected, and the dashboard can be\n * wired with a factory at import time without a live connection.\n *\n * Doubles as an {@link ExporterContract} (`export` ≡ `add`), so it drops\n * straight into a collector via `collector.use(store)`.\n *\n * Instantiated via {@link createCacheTraceStore}; callers never see `new`.\n */\nclass CacheTraceStore implements TraceStoreContract, ExporterContract {\n /** Stable exporter id so a collector can dedupe / log this sink. */\n public readonly name = \"cache-trace-store\";\n\n /**\n * In-memory read mirror keyed by `traceId`. A `Map` preserves insertion\n * order, which newest-first `query` ordering and FIFO eviction both rely\n * on. Every read is served from here synchronously.\n */\n private readonly mirror = new Map<string, Trace>();\n\n private readonly prefix: string;\n\n private readonly capacity: number;\n\n /**\n * Monotonic insertion counter — the source of `IndexEntry.addedAt`.\n * Deliberately NOT `Date.now()`: an internal counter guarantees a stable\n * total order for the index even when many traces land in the same\n * millisecond.\n */\n private addCounter = 0;\n\n /** The optional input — a driver, a factory, or `undefined`. */\n private readonly input: CacheDriverInput;\n\n // The store is driver-agnostic; only get/set/remove are used.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private resolvedDriver?: CacheDriver<any, any>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private driverPending?: Promise<CacheDriver<any, any>>;\n\n private readonly onError?: (error: unknown) => void;\n\n public constructor(\n input: CacheDriverInput,\n options: CacheTraceStoreOptions & { onError?: (error: unknown) => void } = {},\n ) {\n this.input = input;\n this.prefix = options.prefix ?? DEFAULT_PREFIX;\n this.capacity = options.capacity ?? 0;\n this.onError = options.onError;\n }\n\n public get size(): number {\n return this.mirror.size;\n }\n\n /**\n * Hydrate the in-memory mirror from the cache. Idempotent-safe to call\n * once at startup (the dashboard / config wiring awaits it). Reads the\n * persisted index, fetches each referenced trace, and replays them into\n * the mirror in insertion order so newest-first ordering + eviction stay\n * correct after a restart. A cache failure is routed to `onError` and\n * leaves the mirror empty rather than throwing.\n */\n public async ready(): Promise<void> {\n try {\n const driver = await this.resolveDriver();\n const index = await driver.get<IndexEntry[]>(this.indexKey());\n\n if (!Array.isArray(index)) {\n return;\n }\n\n // Oldest-first replay so the mirror's insertion order matches the\n // original ingestion order.\n const ordered = [...index].sort((left, right) => left.addedAt - right.addedAt);\n\n for (const entry of ordered) {\n const trace = await driver.get<Trace>(this.traceKey(entry.id));\n\n if (trace !== null && trace !== undefined) {\n this.mirror.delete(trace.traceId);\n this.mirror.set(trace.traceId, trace);\n }\n\n if (entry.addedAt >= this.addCounter) {\n this.addCounter = entry.addedAt + 1;\n }\n }\n\n this.evictOverflow();\n } catch (error) {\n this.reportError(error);\n }\n }\n\n public add(trace: Trace): void {\n // Mirror update is synchronous and authoritative for runtime reads.\n this.mirror.delete(trace.traceId);\n this.mirror.set(trace.traceId, trace);\n\n const addedAt = this.addCounter;\n this.addCounter += 1;\n\n const evicted = this.evictOverflow();\n\n // Write through to the cache fire-and-forget; reads never wait on this.\n void this.persist(trace, addedAt, evicted);\n }\n\n /**\n * `ExporterContract.export` — a collector dispatches a completed trace\n * here, which is exactly an `add`.\n */\n public export(trace: Trace): void {\n this.add(trace);\n }\n\n public get(traceId: string): Trace | undefined {\n return this.mirror.get(traceId);\n }\n\n public query(filter?: TraceQuery): Trace[] {\n const matched: Trace[] = [];\n\n for (const trace of this.mirror.values()) {\n if (matchTrace(trace, filter)) {\n matched.push(trace);\n }\n }\n\n return this.sortNewestFirst(matched);\n }\n\n public aggregate(filter?: TraceQuery): TraceAggregate {\n const aggregate: TraceAggregate = {\n traces: 0,\n completed: 0,\n failed: 0,\n cancelled: 0,\n usage: emptyUsage(),\n totalDuration: 0,\n };\n\n for (const trace of this.mirror.values()) {\n if (!matchTrace(trace, filter)) {\n continue;\n }\n\n aggregate.traces += 1;\n aggregate.totalDuration += trace.duration;\n aggregate.usage = sumUsage(aggregate.usage, trace.usage);\n\n this.countStatus(aggregate, trace);\n }\n\n if (aggregate.usage.cost !== undefined) {\n aggregate.cost = aggregate.usage.cost;\n }\n\n return aggregate;\n }\n\n public clear(): void {\n const ids = [...this.mirror.keys()];\n this.mirror.clear();\n\n void this.purge(ids);\n }\n\n /**\n * Persist one trace + the rebuilt index to the cache, optionally removing\n * a trace evicted by the capacity cap. Best-effort: any cache failure is\n * routed to `onError`, never thrown — the mirror already reflects the\n * write so runtime reads are unaffected.\n */\n private async persist(\n trace: Trace,\n addedAt: number,\n evictedId: string | undefined,\n ): Promise<void> {\n try {\n const driver = await this.resolveDriver();\n\n await driver.set(this.traceKey(trace.traceId), trace);\n\n if (evictedId !== undefined) {\n await driver.remove(this.traceKey(evictedId));\n }\n\n await driver.set(this.indexKey(), this.buildIndex(addedAt));\n } catch (error) {\n this.reportError(error);\n }\n }\n\n /** Best-effort removal of every persisted trace + the index on `clear`. */\n private async purge(ids: string[]): Promise<void> {\n try {\n const driver = await this.resolveDriver();\n\n for (const id of ids) {\n await driver.remove(this.traceKey(id));\n }\n\n await driver.remove(this.indexKey());\n } catch (error) {\n this.reportError(error);\n }\n }\n\n /**\n * Rebuild the newest-first index from the current mirror. The mirror's\n * `Map` iteration is oldest-first insertion order; we walk it and assign\n * `addedAt` from the surviving counter span so the persisted order\n * matches the in-memory one. The freshest entry uses `latestAddedAt`.\n */\n private buildIndex(latestAddedAt: number): IndexEntry[] {\n const ids = [...this.mirror.keys()];\n const base = latestAddedAt - (ids.length - 1);\n\n return ids.map((id, offset) => ({ id, addedAt: base + offset }));\n }\n\n /**\n * Resolve the driver once and memoize. Supports a bare driver, a sync\n * factory, and an async factory. Concurrent first-callers share one\n * in-flight resolution.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private async resolveDriver(): Promise<CacheDriver<any, any>> {\n if (this.resolvedDriver !== undefined) {\n return this.resolvedDriver;\n }\n\n if (this.driverPending !== undefined) {\n return this.driverPending;\n }\n\n const candidate =\n typeof this.input === \"function\"\n ? (\n this.input as () =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | CacheDriver<any, any>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<CacheDriver<any, any>>\n )()\n : this.input;\n\n this.driverPending = Promise.resolve(candidate);\n\n try {\n this.resolvedDriver = await this.driverPending;\n\n return this.resolvedDriver;\n } finally {\n this.driverPending = undefined;\n }\n }\n\n /** `${prefix}:trace:${traceId}` — the per-trace cache key. */\n private traceKey(traceId: string): string {\n return `${this.prefix}:trace:${traceId}`;\n }\n\n /** `${prefix}:index` — the newest-first index cache key. */\n private indexKey(): string {\n return `${this.prefix}:index`;\n }\n\n /** Route a swallowed cache error to the optional handler. */\n private reportError(error: unknown): void {\n if (this.onError !== undefined) {\n this.onError(error);\n }\n }\n\n /**\n * Increment the matching terminal-status counter for one trace.\n * Mirrors the in-memory store: non-terminal statuses are counted in\n * `traces` but tracked by none of the three headline counters.\n */\n private countStatus(aggregate: TraceAggregate, trace: Trace): void {\n switch (trace.root.status) {\n case \"completed\": {\n aggregate.completed += 1;\n break;\n }\n\n // An incomplete agent run (its answer was cut off) errored.\n case \"failed\":\n case \"incomplete\": {\n aggregate.failed += 1;\n break;\n }\n\n case \"cancelled\": {\n aggregate.cancelled += 1;\n break;\n }\n\n default: {\n break;\n }\n }\n }\n\n /**\n * Sort matched traces newest-started first. A copy is sorted so the\n * mirror's insertion order (which eviction depends on) is never disturbed.\n */\n private sortNewestFirst(traces: Trace[]): Trace[] {\n return traces.sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt));\n }\n\n /**\n * Evict oldest-inserted traces from the mirror until within `capacity`.\n * Returns the id of the single evicted trace (the common case — one `add`\n * pushes at most one over the cap) so the caller can remove it from the\n * cache too. No-op + `undefined` when unbounded or within the cap.\n */\n private evictOverflow(): string | undefined {\n if (this.capacity <= 0) {\n return undefined;\n }\n\n let evicted: string | undefined;\n\n while (this.mirror.size > this.capacity) {\n const oldest = this.mirror.keys().next().value;\n\n if (oldest === undefined) {\n return evicted;\n }\n\n this.mirror.delete(oldest);\n evicted = oldest;\n }\n\n return evicted;\n }\n}\n\n/**\n * The concrete store type returned by {@link createCacheTraceStore} — the\n * standard {@link TraceStoreContract} + {@link ExporterContract} surface,\n * plus a `ready()` to hydrate the in-memory mirror from the cache on\n * startup so traces survive a process restart.\n */\nexport type CacheTraceStoreHandle = TraceStoreContract &\n ExporterContract & {\n /**\n * Hydrate the in-memory mirror from the cache. Await once at startup\n * (the dashboard wiring does this for you) so previously-persisted\n * traces are queryable after a restart.\n */\n ready(): Promise<void>;\n };\n\n/**\n * Create a cache-backed trace store. Reads are served synchronously from an\n * in-memory mirror; writes go through to the cache, and {@link\n * CacheTraceStoreHandle.ready} re-hydrates the mirror on startup so traces\n * survive a restart. See {@link CacheTraceStore} for the full write-through\n * design.\n *\n * @param cache a {@link CacheDriver}, or a (possibly async) factory that\n * yields one on first use — resolved lazily and memoized so a production\n * Redis connect can be deferred until the first trace is collected.\n * @param options `prefix` (default `\"panoptic\"`), `capacity` (FIFO cap),\n * and an optional `onError` hook for swallowed cache write failures.\n *\n * @example\n * import { RedisCacheDriver } from \"@warlock.js/cache\";\n *\n * // Lazy async factory — defers the Redis connect until first use.\n * const store = createCacheTraceStore(async () => {\n * const driver = new RedisCacheDriver();\n * await driver.connect();\n * return driver;\n * });\n *\n * await store.ready(); // hydrate from a prior run\n * collector.use(store); // fills as traces complete\n * const failed = store.query({ status: \"failed\" });\n */\nexport function createCacheTraceStore(\n cache: CacheDriverInput,\n options: CacheTraceStoreOptions & { onError?: (error: unknown) => void } = {},\n): CacheTraceStoreHandle {\n return new CacheTraceStore(cache, options);\n}\n"],"mappings":";;;;AA0DA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCvB,IAAM,kBAAN,MAAsE;;CAEpE,AAAgB,OAAO;;;;;;CAOvB,AAAiB,yBAAS,IAAI,IAAmB;CAEjD,AAAiB;CAEjB,AAAiB;;;;;;;CAQjB,AAAQ,aAAa;;CAGrB,AAAiB;CAIjB,AAAQ;CAGR,AAAQ;CAER,AAAiB;CAEjB,AAAO,YACL,OACA,UAA2E,CAAC,GAC5E;EACA,KAAK,QAAQ;EACb,KAAK,SAAS,QAAQ,UAAU;EAChC,KAAK,W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mBAAmB,QAC1B,OAAO,KAAK;EAGd,IAAI,KAAK,kBAAkB,QACzB,OAAO,KAAK;EAGd,MAAM,YACJ,OAAO,KAAK,UAAU,aAEhB,KAAK,MAKL,IACF,KAAK;EAEX,KAAK,gBAAgB,QAAQ,QAAQ,SAAS;EAE9C,IAAI;GACF,KAAK,iBAAiB,MAAM,KAAK;GAEjC,OAAO,KAAK;EACd,UAAU;GACR,KAAK,gBAAgB;EACvB;CACF;;CAGA,AAAQ,SAAS,SAAyB;EACxC,OAAO,GAAG,KAAK,OAAO,SAAS;CACjC;;CAGA,AAAQ,WAAmB;EACzB,OAAO,GAAG,KAAK,OAAO;CACxB;;CAGA,AAAQ,YAAY,OAAsB;EACxC,IAAI,KAAK,YAAY,QACnB,KAAK,QAAQ,KAAK;CAEtB;;;;;;CAOA,AAAQ,YAAY,WAA2B,OAAoB;EACjE,QAAQ,MAAM,KAAK,QAAnB;GACE,KAAK;IACH,UAAU,aAAa;IACvB;GAIF,KAAK;GACL,KAAK;IACH,UAAU,UAAU;IACpB;GAGF,KAAK,aACH,UAAU,aAAa;EAO3B;CACF;;;;;;;CAQA,AAAQ,gBAAoC;EAC1C,IAAI,KAAK,YAAY,GACnB;EAGF,IAAI;EAEJ,OAAO,KAAK,OAAO,OAAO,KAAK,UAAU;GACvC,MAAM,SAAS,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,KAAK,OAAO,OAAO,MAAM;GACzB,UAAU;EACZ;EAEA,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,sBACd,OACA,UAA2E,CAAC,GACrD;CACvB,OAAO,IAAI,gBAAgB,OAAO,OAAO;AAC3C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"in-memory-trace-store.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/in-memory-trace-store.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"in-memory-trace-store.d.mts","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/in-memory-trace-store.ts"],"mappings":";;;;;;YAYY;;;;;;;EAOV;;;;;;;;;;;;;;wBA6Kc,yBACd,UAAU,4BACT,qBAAqB"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { matchTrace } from "./match-trace.mjs";
|
|
2
|
+
import { sortNewestFirst } from "./sort-newest-first.mjs";
|
|
2
3
|
import { emptyUsage, sumUsage } from "./sum-usage.mjs";
|
|
3
4
|
|
|
4
5
|
//#region ../../packages/ai-panoptic/src/store/in-memory-trace-store.ts
|
|
@@ -53,7 +54,7 @@ var InMemoryTraceStore = class {
|
|
|
53
54
|
query(filter) {
|
|
54
55
|
const matched = [];
|
|
55
56
|
for (const trace of this.traces.values()) if (matchTrace(trace, filter)) matched.push(trace);
|
|
56
|
-
return
|
|
57
|
+
return sortNewestFirst(matched);
|
|
57
58
|
}
|
|
58
59
|
aggregate(filter) {
|
|
59
60
|
const aggregate = {
|
|
@@ -98,14 +99,6 @@ var InMemoryTraceStore = class {
|
|
|
98
99
|
}
|
|
99
100
|
}
|
|
100
101
|
/**
|
|
101
|
-
* Sort matched traces newest-started first. A copy is sorted so the
|
|
102
|
-
* underlying insertion order (which eviction depends on) is never
|
|
103
|
-
* disturbed.
|
|
104
|
-
*/
|
|
105
|
-
sortNewestFirst(traces) {
|
|
106
|
-
return traces.sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt));
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
102
|
* Evict oldest-inserted traces until the store is within `capacity`.
|
|
110
103
|
* No-op when unbounded. The `Map` iterator yields keys in insertion
|
|
111
104
|
* order, so the first key is always the oldest.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"in-memory-trace-store.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/in-memory-trace-store.ts"],"
|
|
1
|
+
{"version":3,"file":"in-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pB;;;;;;;;;CAUA,AAAQ,YAAY,WAA2B,OAAoB;EACjE,QAAQ,MAAM,KAAK,QAAnB;GACE,KAAK;IACH,UAAU,aAAa;IACvB;GAGF,KAAK;GACL,KAAK;IACH,UAAU,UAAU;IACpB;GAGF,KAAK,aACH,UAAU,aAAa;EAO3B;CACF;;;;;;CAOA,AAAQ,gBAAsB;EAC5B,IAAI,KAAK,YAAY,GACnB;EAGF,OAAO,KAAK,OAAO,OAAO,KAAK,UAAU;GACvC,MAAM,SAAS,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAEzC,IAAI,WAAW,QACb;GAGF,KAAK,OAAO,OAAO,MAAM;EAC3B;CACF;AACF;;;;;;;;;;;;;AAcA,SAAgB,yBACd,SACuC;CACvC,OAAO,IAAI,mBAAmB,OAAO;AACvC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"match-trace.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/match-trace.ts"],"
|
|
1
|
+
{"version":3,"file":"match-trace.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/match-trace.ts"],"mappings":";;;;;;;;;;;;;;AAiBA,SAAgB,WAAW,OAAc,QAA8B;CACrE,IAAI,CAAC,QACH,OAAO;CAGT,IAAI,OAAO,cAAc,UAAa,MAAM,cAAc,OAAO,WAC/D,OAAO;CAGT,IAAI,OAAO,YAAY,UAAa,MAAM,YAAY,OAAO,SAC3D,OAAO;CAGT,IAAI,OAAO,cAAc,UAAa,MAAM,cAAc,OAAO,WAC/D,OAAO;CAGT,IAAI,OAAO,WAAW,UAAa,CAAC,cAAc,MAAM,KAAK,QAAQ,OAAO,MAAM,GAChF,OAAO;CAGT,MAAM,YAAY,KAAK,MAAM,MAAM,SAAS;CAE5C,IAAI,OAAO,iBAAiB,UAAa,YAAY,QAAQ,OAAO,YAAY,GAC9E,OAAO;CAGT,IAAI,OAAO,kBAAkB,UAAa,YAAY,QAAQ,OAAO,aAAa,GAChF,OAAO;CAGT,OAAO;AACT;;;;;AAMA,SAAS,cAAc,QAAsB,QAAgD;CAC3F,IAAI,MAAM,QAAQ,MAAM,GACtB,OAAO,OAAO,SAAS,MAAM;CAG/B,OAAO,WAAW;AACpB;;;;;AAMA,SAAS,QAAQ,OAA8B;CAC7C,IAAI,iBAAiB,MACnB,OAAO,MAAM,QAAQ;CAGvB,OAAO,KAAK,MAAM,KAAK;AACzB"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region ../../packages/ai-panoptic/src/store/sort-newest-first.ts
|
|
2
|
+
/**
|
|
3
|
+
* Sort traces newest-started first, in place. Each `startedAt` is parsed
|
|
4
|
+
* once up front instead of twice per comparison.
|
|
5
|
+
*/
|
|
6
|
+
function sortNewestFirst(traces) {
|
|
7
|
+
const startedAt = /* @__PURE__ */ new Map();
|
|
8
|
+
for (const trace of traces) startedAt.set(trace, Date.parse(trace.startedAt));
|
|
9
|
+
return traces.sort((left, right) => (startedAt.get(right) ?? NaN) - (startedAt.get(left) ?? NaN));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
13
|
+
export { sortNewestFirst };
|
|
14
|
+
//# sourceMappingURL=sort-newest-first.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sort-newest-first.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/sort-newest-first.ts"],"mappings":";;;;;AAMA,SAAgB,gBAAgB,QAA0B;CACxD,MAAM,4BAAY,IAAI,IAAmB;CAEzC,KAAK,MAAM,SAAS,QAClB,UAAU,IAAI,OAAO,KAAK,MAAM,MAAM,SAAS,CAAC;CAGlD,OAAO,OAAO,MACX,MAAM,WAAW,UAAU,IAAI,KAAK,KAAK,QAAe,UAAU,IAAI,IAAI,KAAK,IAClF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sum-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/sum-usage.ts"],"
|
|
1
|
+
{"version":3,"file":"sum-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-panoptic/src/store/sum-usage.ts"],"mappings":";;;;AAGA,SAAgB,SAAS,aAAoB,MAAoB;CAC/D,MAAM,SAAS,WAAW;CAC1B,WAAW,QAAQ,WAAW;CAC9B,WAAW,QAAQ,IAAI;CACvB,OAAO;AACT;;AAGA,SAAgB,aAAoB;CAClC,OAAO;EAAE,OAAO;EAAG,QAAQ;EAAG,OAAO;CAAE;AACzC"}
|
package/llms-full.txt
CHANGED
|
@@ -792,7 +792,7 @@ installing the viewer alone does not collect runs.
|
|
|
792
792
|
|
|
793
793
|
---
|
|
794
794
|
name: use-local-dashboard
|
|
795
|
-
description: 'Run the zero-setup local Panoptic dashboard — a loopback `node:http` server over a trace store served from `ai.config({ panoptic: { dashboard } })`, with a two-pane call-tree + metadata UI (light/dark/system theme, search/filter, session + prompt-version grouping, cost heatmap, Gantt timeline, errors filter, hash deep-links) and an optional cache-backed persistent store. Triggers: `dashboard`, `DashboardOptions`, `DashboardHandle`, `ai.config({ panoptic })`, `panoptic.dashboard`, `panoptic.cache`, `port: 4319`, `basePath`, `open`, `authToken`, `allowedHosts`, `/api/traces`, `/api/aggregate`, `/api/traces/:id`, `createRequestHandler`, `dashboardHtml`, `sanitizeHref`, `ServeConfig`, `TraceStoreContract`, `createCacheTraceStore`, theme, dark mode, call tree, metadata panel, cost heatmap, timeline / Gantt, errors only, deep-link, group by session, prompt version, group by type, type stats panel, started / ended timestamps, team type; ''open a local AI trace dashboard'', ''view agent traces in the browser'', ''self-hosted panoptic UI'', ''inspect traces without Langfuse'', ''spin up a dev observability server'', ''dark mode dashboard'', ''persist traces across restart'', ''group traces by session / prompt version / type'', ''cost heatmap'', ''timeline / waterfall view'', ''filter failed runs in the dashboard'', ''per-type stats panel'', ''is the dashboard bearer token safe'', ''markdown links XSS in trace content''; typical import `import { ai } from "@warlock.js/ai"` + `import "@warlock.js/ai-panoptic"`. Skip: shipping traces to a backend (OTel / Langfuse / file) — the `export-traces` topic; the queryable store API the dashboard reads — the `query-traces` topic; wiring the subscriber by hand — the `observe-with-panoptic` topic.'
|
|
795
|
+
description: 'Run the zero-setup local Panoptic dashboard — a loopback `node:http` server over a trace store served from `ai.config({ panoptic: { dashboard } })`, with a two-pane call-tree + metadata UI (light/dark/system theme, search/filter, session + prompt-version grouping, cost heatmap, Gantt timeline, errors filter, hash deep-links) and an optional cache-backed persistent store. Triggers: `dashboard`, `DashboardOptions`, `DashboardHandle`, `ai.config({ panoptic })`, `panoptic.dashboard`, `panoptic.cache`, `port: 4319`, `basePath`, `open`, `authToken`, `allowedHosts`, `/api/traces`, `/api/aggregate`, `/api/traces/:id`, `TraceSummary`, `TraceSpanSummary`, `panoptic.capacity`, `createRequestHandler`, `dashboardHtml`, `sanitizeHref`, `ServeConfig`, `TraceStoreContract`, `createCacheTraceStore`, theme, dark mode, call tree, metadata panel, cost heatmap, timeline / Gantt, errors only, deep-link, group by session, prompt version, group by type, type stats panel, started / ended timestamps, team type; ''open a local AI trace dashboard'', ''view agent traces in the browser'', ''self-hosted panoptic UI'', ''inspect traces without Langfuse'', ''spin up a dev observability server'', ''dark mode dashboard'', ''persist traces across restart'', ''group traces by session / prompt version / type'', ''cost heatmap'', ''timeline / waterfall view'', ''filter failed runs in the dashboard'', ''per-type stats panel'', ''is the dashboard bearer token safe'', ''markdown links XSS in trace content''; typical import `import { ai } from "@warlock.js/ai"` + `import "@warlock.js/ai-panoptic"`. Skip: shipping traces to a backend (OTel / Langfuse / file) — the `export-traces` topic; the queryable store API the dashboard reads — the `query-traces` topic; wiring the subscriber by hand — the `observe-with-panoptic` topic.'
|
|
796
796
|
---
|
|
797
797
|
|
|
798
798
|
# The local Panoptic dashboard — zero-setup trace viewing
|
|
@@ -830,7 +830,7 @@ ai.config({
|
|
|
830
830
|
**Where the dashboard reads its traces from.** It needs a queryable store (a `TraceStoreContract`). Panoptic resolves one in this order:
|
|
831
831
|
|
|
832
832
|
1. The first **store-shaped exporter** in `config.exporters` — `createInMemoryTraceStore()` doubles as an `ExporterContract`, so a store passed in `exporters` is reused (captured AND served from the same object).
|
|
833
|
-
2. If none was supplied but `dashboard` is set, panoptic creates a fresh in-memory store and registers it as an exporter so the collector fills it.
|
|
833
|
+
2. If none was supplied but `dashboard` is set, panoptic creates a fresh in-memory store (or a cache-backed one with `cache`) and registers it as an exporter so the collector fills it. That store keeps the newest `panoptic.capacity` traces — default `1000`, `0` for no limit.
|
|
834
834
|
|
|
835
835
|
So `dashboard: true` with no exporters Just Works — you get a store for free. Supply your own when you want a capacity cap or want to `query` / `aggregate` it from app code too.
|
|
836
836
|
|
|
@@ -966,13 +966,13 @@ type DashboardHandle = {
|
|
|
966
966
|
|
|
967
967
|
Every route is **`GET`-only and read-only** (non-`GET` → `405`), mounted under `basePath` — EXCEPT the one opt-in `POST .../spans/:spanId/evaluate` route `DashboardOptions.evaluate` enables (see the `evaluate-system-prompt` topic); absent that config, it 405s like everything else. The page polls the `GET` routes; you can curl them too. Store shapes are already JSON-safe, so responses are a plain `JSON.stringify`.
|
|
968
968
|
|
|
969
|
-
| Route | Returns
|
|
970
|
-
| -------------------------------------------------- |
|
|
971
|
-
| `GET /api/traces` | `store.query(...)` — the
|
|
972
|
-
| `GET /api/traces/:id` | `store.get(id)` — one full trace,
|
|
973
|
-
| `GET /api/aggregate` | `store.aggregate(...)` — the usage + cost + status rollup over the same query filter.
|
|
974
|
-
| `GET /` (basePath) | the self-contained HTML page.
|
|
975
|
-
| `POST /api/traces/:traceId/spans/:spanId/evaluate` | grades the span's last captured system prompt — only when `evaluate` is configured.
|
|
969
|
+
| Route | Returns |
|
|
970
|
+
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
971
|
+
| `GET /api/traces` | `store.query(...)` — the newest `?limit=` (default 200) matches as `TraceSummary` entries (root is a `TraceSpanSummary`: no span tree, no captured content; `spanCount` + `totalCost` added), filtered by the query string (`traceId` / `sessionId` / `status` / time window, parsed by `parseQuery`). `?full=1` returns full traces. |
|
|
972
|
+
| `GET /api/traces/:id` | `store.get(id)` — one full trace, `404 { error: "trace_not_found" }`, or `400 { error: "bad_trace_id" }` for a malformed id. |
|
|
973
|
+
| `GET /api/aggregate` | `store.aggregate(...)` — the usage + cost + status rollup over the same query filter. |
|
|
974
|
+
| `GET /` (basePath) | the self-contained HTML page. |
|
|
975
|
+
| `POST /api/traces/:traceId/spans/:spanId/evaluate` | grades the span's last captured system prompt — only when `evaluate` is configured. |
|
|
976
976
|
|
|
977
977
|
Query-string filters map 1:1 onto `TraceQuery`:
|
|
978
978
|
|
package/llms.txt
CHANGED
|
@@ -11,4 +11,4 @@
|
|
|
11
11
|
- [export-traces](@warlock.js/ai-panoptic/skills/export-traces/SKILL.md): Send @warlock.js/ai-panoptic traces to an observability backend via pluggable exporters, including capturing prompt/response content onto spans. Triggers: `consoleExporter`, `fileExporter`, `otelExporter`, `langfuseExporter`, `ExporterContract`, `ContentCaptureOptions`, `captureContent`, `redactContent`, `fullHistory`, `ContentRedactor`, `toGenAiAttributes`, `walkSpans`, `totalCostUsd`, `GEN_AI_ATTRIBUTES`, `WARLOCK_ATTRIBUTES`, `reportToTrace`, `reportToSpan`, `extractSpanAttributes`, `normalizeError`, `formatSpanLine`, `createPanopticMiddleware`; 'export AI traces to OpenTelemetry', 'send traces to Langfuse', 'log traces to console / a file', 'capture the full prompt/conversation onto a span', 'gen_ai semantic conventions', 'write a custom exporter'; typical import `import { otelExporter, langfuseExporter, consoleExporter, fileExporter } from "@warlock.js/ai-panoptic"`. Skip: wiring the subscriber/collector into a run — the `observe-with-panoptic` topic; the core report shape — the `run-ai-agent` topic of the `warlock-js-ai` skill.
|
|
12
12
|
- [observe-with-panoptic](@warlock.js/ai-panoptic/skills/observe-with-panoptic/SKILL.md): Wire @warlock.js/ai-panoptic into an agent/workflow/supervisor/orchestrator — declaratively via `ai.config({ panoptic })` (registers panoptic on core's Observer seam) or with the one-call `panoptic({ exporters })` subscriber. Triggers: `panoptic`, `Panoptic`, `PanopticOptions`, `PanopticConfig`, `ai.config({ panoptic })`, `observeAll`, per-flow `observe`, `FlowObserveOption`, `registerObserver`, `Observer`, `.attach`, `.middleware`, `.collect`, `.toTrace`, `observe.attach(agent)`, `panoptic().middleware()`, `completedEvents`, `middlewareName`; 'observe a warlock agent', 'trace an agent run', 'attach observability to a workflow/supervisor', 'observe every flow by default', 'add a tracing middleware', 'collect an orchestrator turn report', 'wire OTel/Langfuse into my agent'; typical import `import { ai } from "@warlock.js/ai"` + `import "@warlock.js/ai-panoptic"` (or `import { panoptic } from "@warlock.js/ai-panoptic"`). Skip: the zero-setup local dashboard — the `use-local-dashboard` topic; writing/choosing an exporter (the sink end) — the `export-traces` topic; the core report shape / running the agent itself — the `run-ai-agent` topic of the `warlock-js-ai` skill.
|
|
13
13
|
- [query-traces](@warlock.js/ai-panoptic/skills/query-traces/SKILL.md): Retain @warlock.js/ai-panoptic traces in a queryable store — in-memory, or cache-backed so they survive a process restart — and slice them after the fact: get one run by id, list a session, filter failed runs in a window, roll up usage + cost. Triggers: `createInMemoryTraceStore`, `createCacheTraceStore`, `CacheTraceStoreHandle`, `CacheTraceStoreOptions`, `CacheDriverInput`, `store.ready`, `TraceStoreContract`, `TraceQuery`, `TraceAggregate`, `InMemoryTraceStoreOptions`, `store.query`, `store.aggregate`, `store.get`, `store.add`, `store.clear`, `store.size`, `capacity`, `prefix`, `onError`, `sumUsage`, `emptyUsage`, `matchTrace`; 'query collected traces', 'aggregate AI cost per session', 'how much did this session spend', 'list failed runs', 'retain traces in memory', 'persist traces across a restart', 'cache-backed trace store', 'Redis trace store', 'roll up token usage'; typical import `import { createInMemoryTraceStore, createCacheTraceStore } from "@warlock.js/ai-panoptic"`. Skip: sending traces to an external backend (OTel/Langfuse/console/file) — the `export-traces` topic; wiring the subscriber into a run — the `observe-with-panoptic` topic.
|
|
14
|
-
- [use-local-dashboard](@warlock.js/ai-panoptic/skills/use-local-dashboard/SKILL.md): Run the zero-setup local Panoptic dashboard — a loopback `node:http` server over a trace store served from `ai.config({ panoptic: { dashboard } })`, with a two-pane call-tree + metadata UI (light/dark/system theme, search/filter, session + prompt-version grouping, cost heatmap, Gantt timeline, errors filter, hash deep-links) and an optional cache-backed persistent store. Triggers: `dashboard`, `DashboardOptions`, `DashboardHandle`, `ai.config({ panoptic })`, `panoptic.dashboard`, `panoptic.cache`, `port: 4319`, `basePath`, `open`, `authToken`, `allowedHosts`, `/api/traces`, `/api/aggregate`, `/api/traces/:id`, `createRequestHandler`, `dashboardHtml`, `sanitizeHref`, `ServeConfig`, `TraceStoreContract`, `createCacheTraceStore`, theme, dark mode, call tree, metadata panel, cost heatmap, timeline / Gantt, errors only, deep-link, group by session, prompt version, group by type, type stats panel, started / ended timestamps, team type; 'open a local AI trace dashboard', 'view agent traces in the browser', 'self-hosted panoptic UI', 'inspect traces without Langfuse', 'spin up a dev observability server', 'dark mode dashboard', 'persist traces across restart', 'group traces by session / prompt version / type', 'cost heatmap', 'timeline / waterfall view', 'filter failed runs in the dashboard', 'per-type stats panel', 'is the dashboard bearer token safe', 'markdown links XSS in trace content'; typical import `import { ai } from "@warlock.js/ai"` + `import "@warlock.js/ai-panoptic"`. Skip: shipping traces to a backend (OTel / Langfuse / file) — the `export-traces` topic; the queryable store API the dashboard reads — the `query-traces` topic; wiring the subscriber by hand — the `observe-with-panoptic` topic.
|
|
14
|
+
- [use-local-dashboard](@warlock.js/ai-panoptic/skills/use-local-dashboard/SKILL.md): Run the zero-setup local Panoptic dashboard — a loopback `node:http` server over a trace store served from `ai.config({ panoptic: { dashboard } })`, with a two-pane call-tree + metadata UI (light/dark/system theme, search/filter, session + prompt-version grouping, cost heatmap, Gantt timeline, errors filter, hash deep-links) and an optional cache-backed persistent store. Triggers: `dashboard`, `DashboardOptions`, `DashboardHandle`, `ai.config({ panoptic })`, `panoptic.dashboard`, `panoptic.cache`, `port: 4319`, `basePath`, `open`, `authToken`, `allowedHosts`, `/api/traces`, `/api/aggregate`, `/api/traces/:id`, `TraceSummary`, `TraceSpanSummary`, `panoptic.capacity`, `createRequestHandler`, `dashboardHtml`, `sanitizeHref`, `ServeConfig`, `TraceStoreContract`, `createCacheTraceStore`, theme, dark mode, call tree, metadata panel, cost heatmap, timeline / Gantt, errors only, deep-link, group by session, prompt version, group by type, type stats panel, started / ended timestamps, team type; 'open a local AI trace dashboard', 'view agent traces in the browser', 'self-hosted panoptic UI', 'inspect traces without Langfuse', 'spin up a dev observability server', 'dark mode dashboard', 'persist traces across restart', 'group traces by session / prompt version / type', 'cost heatmap', 'timeline / waterfall view', 'filter failed runs in the dashboard', 'per-type stats panel', 'is the dashboard bearer token safe', 'markdown links XSS in trace content'; typical import `import { ai } from "@warlock.js/ai"` + `import "@warlock.js/ai-panoptic"`. Skip: shipping traces to a backend (OTel / Langfuse / file) — the `export-traces` topic; the queryable store API the dashboard reads — the `query-traces` topic; wiring the subscriber by hand — the `observe-with-panoptic` topic.
|
package/package.json
CHANGED
|
@@ -19,9 +19,9 @@
|
|
|
19
19
|
"peerDependencies": {
|
|
20
20
|
"@opentelemetry/api": "*",
|
|
21
21
|
"@opentelemetry/sdk-trace-base": "*",
|
|
22
|
-
"@warlock.js/ai": "5.
|
|
23
|
-
"@warlock.js/cache": "5.
|
|
24
|
-
"@warlock.js/logger": "5.
|
|
22
|
+
"@warlock.js/ai": "5.53.0",
|
|
23
|
+
"@warlock.js/cache": "5.53.0",
|
|
24
|
+
"@warlock.js/logger": "5.53.0",
|
|
25
25
|
"langfuse": "*"
|
|
26
26
|
},
|
|
27
27
|
"peerDependenciesMeta": {
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"langfuse": "^3.38.20"
|
|
43
43
|
},
|
|
44
|
-
"version": "5.
|
|
44
|
+
"version": "5.53.0",
|
|
45
45
|
"main": "./cjs/index.cjs",
|
|
46
46
|
"module": "./esm/index.mjs",
|
|
47
47
|
"types": "./esm/index.d.mts",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: use-local-dashboard
|
|
3
|
-
description: 'Run the zero-setup local Panoptic dashboard — a loopback `node:http` server over a trace store served from `ai.config({ panoptic: { dashboard } })`, with a two-pane call-tree + metadata UI (light/dark/system theme, search/filter, session + prompt-version grouping, cost heatmap, Gantt timeline, errors filter, hash deep-links) and an optional cache-backed persistent store. Triggers: `dashboard`, `DashboardOptions`, `DashboardHandle`, `ai.config({ panoptic })`, `panoptic.dashboard`, `panoptic.cache`, `port: 4319`, `basePath`, `open`, `authToken`, `allowedHosts`, `/api/traces`, `/api/aggregate`, `/api/traces/:id`, `createRequestHandler`, `dashboardHtml`, `sanitizeHref`, `ServeConfig`, `TraceStoreContract`, `createCacheTraceStore`, theme, dark mode, call tree, metadata panel, cost heatmap, timeline / Gantt, errors only, deep-link, group by session, prompt version, group by type, type stats panel, started / ended timestamps, team type; ''open a local AI trace dashboard'', ''view agent traces in the browser'', ''self-hosted panoptic UI'', ''inspect traces without Langfuse'', ''spin up a dev observability server'', ''dark mode dashboard'', ''persist traces across restart'', ''group traces by session / prompt version / type'', ''cost heatmap'', ''timeline / waterfall view'', ''filter failed runs in the dashboard'', ''per-type stats panel'', ''is the dashboard bearer token safe'', ''markdown links XSS in trace content''; typical import `import { ai } from "@warlock.js/ai"` + `import "@warlock.js/ai-panoptic"`. Skip: shipping traces to a backend (OTel / Langfuse / file) — the `export-traces` topic; the queryable store API the dashboard reads — the `query-traces` topic; wiring the subscriber by hand — the `observe-with-panoptic` topic.'
|
|
3
|
+
description: 'Run the zero-setup local Panoptic dashboard — a loopback `node:http` server over a trace store served from `ai.config({ panoptic: { dashboard } })`, with a two-pane call-tree + metadata UI (light/dark/system theme, search/filter, session + prompt-version grouping, cost heatmap, Gantt timeline, errors filter, hash deep-links) and an optional cache-backed persistent store. Triggers: `dashboard`, `DashboardOptions`, `DashboardHandle`, `ai.config({ panoptic })`, `panoptic.dashboard`, `panoptic.cache`, `port: 4319`, `basePath`, `open`, `authToken`, `allowedHosts`, `/api/traces`, `/api/aggregate`, `/api/traces/:id`, `TraceSummary`, `TraceSpanSummary`, `panoptic.capacity`, `createRequestHandler`, `dashboardHtml`, `sanitizeHref`, `ServeConfig`, `TraceStoreContract`, `createCacheTraceStore`, theme, dark mode, call tree, metadata panel, cost heatmap, timeline / Gantt, errors only, deep-link, group by session, prompt version, group by type, type stats panel, started / ended timestamps, team type; ''open a local AI trace dashboard'', ''view agent traces in the browser'', ''self-hosted panoptic UI'', ''inspect traces without Langfuse'', ''spin up a dev observability server'', ''dark mode dashboard'', ''persist traces across restart'', ''group traces by session / prompt version / type'', ''cost heatmap'', ''timeline / waterfall view'', ''filter failed runs in the dashboard'', ''per-type stats panel'', ''is the dashboard bearer token safe'', ''markdown links XSS in trace content''; typical import `import { ai } from "@warlock.js/ai"` + `import "@warlock.js/ai-panoptic"`. Skip: shipping traces to a backend (OTel / Langfuse / file) — the `export-traces` topic; the queryable store API the dashboard reads — the `query-traces` topic; wiring the subscriber by hand — the `observe-with-panoptic` topic.'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# The local Panoptic dashboard — zero-setup trace viewing
|
|
@@ -38,7 +38,7 @@ ai.config({
|
|
|
38
38
|
**Where the dashboard reads its traces from.** It needs a queryable store (a `TraceStoreContract`). Panoptic resolves one in this order:
|
|
39
39
|
|
|
40
40
|
1. The first **store-shaped exporter** in `config.exporters` — `createInMemoryTraceStore()` doubles as an `ExporterContract`, so a store passed in `exporters` is reused (captured AND served from the same object).
|
|
41
|
-
2. If none was supplied but `dashboard` is set, panoptic creates a fresh in-memory store and registers it as an exporter so the collector fills it.
|
|
41
|
+
2. If none was supplied but `dashboard` is set, panoptic creates a fresh in-memory store (or a cache-backed one with `cache`) and registers it as an exporter so the collector fills it. That store keeps the newest `panoptic.capacity` traces — default `1000`, `0` for no limit.
|
|
42
42
|
|
|
43
43
|
So `dashboard: true` with no exporters Just Works — you get a store for free. Supply your own when you want a capacity cap or want to `query` / `aggregate` it from app code too.
|
|
44
44
|
|
|
@@ -174,13 +174,13 @@ type DashboardHandle = {
|
|
|
174
174
|
|
|
175
175
|
Every route is **`GET`-only and read-only** (non-`GET` → `405`), mounted under `basePath` — EXCEPT the one opt-in `POST .../spans/:spanId/evaluate` route `DashboardOptions.evaluate` enables (see the `evaluate-system-prompt` topic); absent that config, it 405s like everything else. The page polls the `GET` routes; you can curl them too. Store shapes are already JSON-safe, so responses are a plain `JSON.stringify`.
|
|
176
176
|
|
|
177
|
-
| Route | Returns
|
|
178
|
-
| -------------------------------------------------- |
|
|
179
|
-
| `GET /api/traces` | `store.query(...)` — the
|
|
180
|
-
| `GET /api/traces/:id` | `store.get(id)` — one full trace,
|
|
181
|
-
| `GET /api/aggregate` | `store.aggregate(...)` — the usage + cost + status rollup over the same query filter.
|
|
182
|
-
| `GET /` (basePath) | the self-contained HTML page.
|
|
183
|
-
| `POST /api/traces/:traceId/spans/:spanId/evaluate` | grades the span's last captured system prompt — only when `evaluate` is configured.
|
|
177
|
+
| Route | Returns |
|
|
178
|
+
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
179
|
+
| `GET /api/traces` | `store.query(...)` — the newest `?limit=` (default 200) matches as `TraceSummary` entries (root is a `TraceSpanSummary`: no span tree, no captured content; `spanCount` + `totalCost` added), filtered by the query string (`traceId` / `sessionId` / `status` / time window, parsed by `parseQuery`). `?full=1` returns full traces. |
|
|
180
|
+
| `GET /api/traces/:id` | `store.get(id)` — one full trace, `404 { error: "trace_not_found" }`, or `400 { error: "bad_trace_id" }` for a malformed id. |
|
|
181
|
+
| `GET /api/aggregate` | `store.aggregate(...)` — the usage + cost + status rollup over the same query filter. |
|
|
182
|
+
| `GET /` (basePath) | the self-contained HTML page. |
|
|
183
|
+
| `POST /api/traces/:traceId/spans/:spanId/evaluate` | grades the span's last captured system prompt — only when `evaluate` is configured. |
|
|
184
184
|
|
|
185
185
|
Query-string filters map 1:1 onto `TraceQuery`:
|
|
186
186
|
|