@warlock.js/devtools 5.61.0 → 5.62.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/cjs/{extract-8kaX_cUV.cjs → ai-source-CeHZDYG1.cjs} +449 -408
  3. package/cjs/ai-source-CeHZDYG1.cjs.map +1 -0
  4. package/cjs/{attach-D5aMqUnA.cjs → attach-D9gWc6lU.cjs} +19 -19
  5. package/cjs/attach-D9gWc6lU.cjs.map +1 -0
  6. package/cjs/{boot-D0nF-7w3.cjs → boot-Guumt-du.cjs} +10 -8
  7. package/cjs/boot-Guumt-du.cjs.map +1 -0
  8. package/cjs/{http-1nnpAoI7.cjs → http-CPbhLN61.cjs} +5 -5
  9. package/cjs/{http-1nnpAoI7.cjs.map → http-CPbhLN61.cjs.map} +1 -1
  10. package/cjs/index.cjs +1 -1
  11. package/cjs/{process-panel-D3D9Y_dc.cjs → process-panel-Dev6eg_f.cjs} +2 -2
  12. package/cjs/{process-panel-D3D9Y_dc.cjs.map → process-panel-Dev6eg_f.cjs.map} +1 -1
  13. package/cjs/{runs-DECWPGnq.cjs → runs-DXTf_o5P.cjs} +10 -11
  14. package/cjs/runs-DXTf_o5P.cjs.map +1 -0
  15. package/cjs/{server-DLT3uPef.cjs → server-Dc0YdP6Y.cjs} +6 -6
  16. package/cjs/{server-DLT3uPef.cjs.map → server-Dc0YdP6Y.cjs.map} +1 -1
  17. package/cjs/{src-BZiSv8A1.cjs → src-Ca1gNdZj.cjs} +15 -15
  18. package/cjs/{src-BZiSv8A1.cjs.map → src-Ca1gNdZj.cjs.map} +1 -1
  19. package/cjs/{stream-route-B6WAjbPG.cjs → stream-route-qEHoPVth.cjs} +21 -15
  20. package/cjs/stream-route-qEHoPVth.cjs.map +1 -0
  21. package/esm/ai/reports/runs.mjs +5 -6
  22. package/esm/ai/reports/runs.mjs.map +1 -1
  23. package/esm/ai/rollup/extract.mjs +21 -4
  24. package/esm/ai/rollup/extract.mjs.map +1 -1
  25. package/esm/panels.mjs +14 -1
  26. package/esm/panels.mjs.map +1 -1
  27. package/esm/production/boot.mjs +4 -2
  28. package/esm/production/boot.mjs.map +1 -1
  29. package/esm/production/options.d.mts +5 -0
  30. package/esm/production/options.d.mts.map +1 -1
  31. package/esm/production/options.mjs.map +1 -1
  32. package/esm/server/ai-routes.mjs +11 -5
  33. package/esm/server/ai-routes.mjs.map +1 -1
  34. package/esm/sources/ai-source.d.mts.map +1 -1
  35. package/esm/sources/ai-source.mjs +3 -3
  36. package/esm/sources/ai-source.mjs.map +1 -1
  37. package/esm/types.d.mts +5 -2
  38. package/esm/types.d.mts.map +1 -1
  39. package/llms-full.txt +5 -2
  40. package/package.json +8 -8
  41. package/skills/SKILL.md +5 -2
  42. package/cjs/attach-D5aMqUnA.cjs.map +0 -1
  43. package/cjs/boot-D0nF-7w3.cjs.map +0 -1
  44. package/cjs/extract-8kaX_cUV.cjs.map +0 -1
  45. package/cjs/runs-DECWPGnq.cjs.map +0 -1
  46. package/cjs/stream-route-B6WAjbPG.cjs.map +0 -1
@@ -331,6 +331,19 @@ function productionPanels(packagePanels, overrides = {}) {
331
331
  panels: packagePanels.filter((panel) => overrides[panel.id] ?? panel.production)
332
332
  };
333
333
  }
334
+ /** The tabs that read per-process run details; production keeps hourly totals instead. */
335
+ const DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS = ["ai", "agents"];
336
+ /**
337
+ * Drops the Runs (`ai`) and Agents (`agents`) tabs from a production tab list.
338
+ * `ignored` lists the ones the project asked for (`production.panels[id] === true`),
339
+ * so boot can warn once.
340
+ */
341
+ function withoutDevelopmentAiTabs(builtIn, overrides = {}) {
342
+ return {
343
+ builtIn: builtIn.filter((tab) => !DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.includes(tab)),
344
+ ignored: DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.filter((tab) => overrides[tab] === true)
345
+ };
346
+ }
334
347
  /**
335
348
  * The tab list `GET api/panels` answers with: the built-in tabs in
336
349
  * `builtIn` (default: every one), in display order, then the package panels
@@ -343,314 +356,13 @@ function listPanelInfos(panels, builtIn) {
343
356
  type: "built-in",
344
357
  shareable: false
345
358
  }));
346
- for (const panel of panels) tabs.push({
347
- id: panel.id,
348
- title: panel.title,
349
- type: "package",
350
- shareable: panel.share !== void 0 && panel.share !== null
351
- });
352
- return tabs;
353
- }
354
-
355
- //#endregion
356
- //#region ../../packages/devtools/src/safe-value.ts
357
- const MAX_DEPTH = 6;
358
- /**
359
- * A JSON-safe snapshot of a value devtools keeps for later display.
360
- *
361
- * Log contexts and phase attributes are app data: they can hold live objects
362
- * (a request, its socket) whose graphs are circular and which must not be kept
363
- * alive by the collector anyway. Plain objects and arrays are copied; anything
364
- * with a `toJSON()` is serialized through it; other class instances collapse
365
- * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to
366
- * `[Object]` / `[Array]`.
367
- */
368
- function toSafeValue(value) {
369
- return snapshot(value, 0, /* @__PURE__ */ new WeakSet());
370
- }
371
- function snapshot(value, depth, seen) {
372
- if (value === null || value === void 0) return value;
373
- switch (typeof value) {
374
- case "string":
375
- case "number":
376
- case "boolean": return value;
377
- case "bigint": return value.toString();
378
- case "symbol": return value.toString();
379
- case "function": return;
380
- }
381
- const object = value;
382
- if (seen.has(object)) return "[Circular]";
383
- if (value instanceof Date) return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
384
- if (value instanceof Error) return {
385
- name: value.name,
386
- message: value.message
387
- };
388
- if (depth >= MAX_DEPTH) return Array.isArray(value) ? "[Array]" : "[Object]";
389
- seen.add(object);
390
- try {
391
- if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));
392
- const prototype = Object.getPrototypeOf(object);
393
- if (prototype !== Object.prototype && prototype !== null) {
394
- const toJSON = object.toJSON;
395
- if (typeof toJSON === "function") try {
396
- return snapshot(toJSON.call(object), depth + 1, seen);
397
- } catch {
398
- return `[${constructorName(object)}]`;
399
- }
400
- return `[${constructorName(object)}]`;
401
- }
402
- const copy = {};
403
- for (const [key, entry] of Object.entries(object)) {
404
- const safe = snapshot(entry, depth + 1, seen);
405
- if (safe !== void 0) copy[key] = safe;
406
- }
407
- return copy;
408
- } finally {
409
- seen.delete(object);
410
- }
411
- }
412
- function constructorName(object) {
413
- return object.constructor?.name || "Object";
414
- }
415
-
416
- //#endregion
417
- //#region ../../packages/devtools/src/sources/ai-source.ts
418
- /** Replaces absolute file paths in an error line with their package-relative part, or `<path>`. */
419
- function redactPaths(text) {
420
- return text.replace(/(?:file:\/\/)?(?:[A-Za-z]:)?[\\/][^\s'"`()]*/g, (match) => {
421
- const normalized = match.replace(/^file:\/\//, "").replaceAll("\\", "/");
422
- const index = normalized.lastIndexOf("node_modules/");
423
- return index === -1 ? "<path>" : normalized.slice(index + 13);
424
- });
425
- }
426
- const OBSERVATION_COMMAND = "ai.config({ panoptic: { observeAll: true } })";
427
- /** The answer for each reason; `detail` carries the load error and versions for `panoptic-failed`. */
428
- function describeAiUnavailable(reason, detail) {
429
- switch (reason) {
430
- case "ai-missing": return {
431
- available: false,
432
- reason,
433
- title: "AI isn't installed",
434
- message: "Add @warlock.js/ai to see AI runs here.",
435
- command: "warlock add ai"
436
- };
437
- case "panoptic-missing": return {
438
- available: false,
439
- reason,
440
- title: "Panoptic isn't installed",
441
- message: "Your app uses @warlock.js/ai. Add Panoptic to see its runs.",
442
- command: "warlock add ai-panoptic"
443
- };
444
- case "panoptic-failed": return {
445
- available: false,
446
- reason,
447
- title: "Panoptic could not be loaded",
448
- message: "Panoptic is installed but failed to load. Check that both packages share a version.",
449
- detail
450
- };
451
- case "not-collected": return {
452
- available: false,
453
- reason,
454
- title: "AI runs are not collected here",
455
- message: "Production keeps hourly AI totals, not run details. Open Reports, Models or Errors here, or the Runs tab in development (warlock dev)."
456
- };
457
- case "table-missing": return {
458
- available: false,
459
- reason,
460
- title: "AI reports need their table",
461
- message: "Run the devtools migrations to create devtools_ai_rollups, then restart the app.",
462
- command: "warlock migrate"
463
- };
464
- case "reports-off": return {
465
- available: false,
466
- reason,
467
- title: "AI reports are off",
468
- message: "Set devtools.ai.reports to true in src/config/devtools.ts to keep hourly AI totals."
469
- };
470
- case "observation-off": return {
471
- available: false,
472
- reason,
473
- title: "AI observation is off",
474
- message: "Turn it on in src/config/ai.ts, then restart warlock dev.",
475
- command: OBSERVATION_COMMAND
476
- };
477
- }
478
- }
479
- /** The unavailable answer as the AI routes send it: `command` and `detail` are `null` when absent. */
480
- function toAiUnavailableView(unavailable) {
481
- return {
482
- available: false,
483
- reason: unavailable.reason,
484
- title: unavailable.title,
485
- message: unavailable.message,
486
- command: unavailable.command ?? null,
487
- detail: unavailable.detail ?? null
488
- };
489
- }
490
- /** Summaries use root usage once: nested spans already roll up into it. */
491
- function summarizeAiTrace(trace, cost) {
492
- const models = /* @__PURE__ */ new Set();
493
- let toolCalls = 0;
494
- let retries = 0;
495
- let cacheHits;
496
- let incomplete = false;
497
- let truncatedTrips = 0;
498
- let compactions = 0;
499
- let skippedCompactions = 0;
500
- let providerCompactions = 0;
501
- const visit = (span) => {
502
- const attributes = span.attributes ?? {};
503
- const model = attributes["agent.model.name"];
504
- const provider = attributes["agent.model.provider"];
505
- if (typeof model === "string") models.add(typeof provider === "string" ? `${provider}/${model}` : model);
506
- if (span.type === "tool") toolCalls += 1;
507
- if (typeof attributes.retries === "number") retries += attributes.retries;
508
- if (typeof attributes["agent.cacheHits"] === "number") cacheHits = (cacheHits ?? 0) + attributes["agent.cacheHits"];
509
- if (typeof attributes["agent.truncatedTrips"] === "number") truncatedTrips += attributes["agent.truncatedTrips"];
510
- if (typeof attributes["agent.providerCompactions"] === "number") providerCompactions += attributes["agent.providerCompactions"];
511
- if (Array.isArray(attributes["agent.compactions"])) {
512
- const records = attributes["agent.compactions"];
513
- for (const record of records) {
514
- if (typeof record !== "object" || record === null || !("type" in record)) continue;
515
- if (record.type === "applied") compactions += 1;
516
- if (record.type === "skipped") skippedCompactions += 1;
517
- }
518
- }
519
- incomplete ||= span.status === "incomplete" || span.error?.type === "AgentIncompleteError" || span.error?.type === "AGENT_INCOMPLETE";
520
- span.children.forEach(visit);
521
- };
522
- visit(trace.root);
523
- return {
524
- traceId: trace.traceId,
525
- requestId: trace.requestId,
526
- sessionId: trace.sessionId,
527
- name: trace.root.name,
528
- status: trace.root.status,
529
- startedAt: trace.startedAt,
530
- duration: trace.duration,
531
- usage: trace.usage,
532
- cost,
533
- models: [...models],
534
- toolCalls,
535
- retries,
536
- cacheHits,
537
- incomplete,
538
- truncatedTrips,
539
- compactions,
540
- skippedCompactions,
541
- providerCompactions
542
- };
543
- }
544
- /** Content-free snapshot; never retain prompts, completions or tool arguments/results. */
545
- function snapshotSpan(span) {
546
- return {
547
- spanId: span.spanId,
548
- parentSpanId: span.parentSpanId,
549
- traceId: span.traceId,
550
- sessionId: span.sessionId,
551
- name: span.name,
552
- version: span.version,
553
- type: span.type,
554
- status: span.status,
555
- startedAt: span.startedAt,
556
- endedAt: span.endedAt,
557
- duration: span.duration,
558
- usage: structuredClone(span.usage),
559
- error: span.error ? {
560
- type: span.error.type,
561
- message: span.error.message
562
- } : void 0,
563
- attributes: toSafeValue(span.attributes),
564
- children: span.children.map(snapshotSpan)
565
- };
566
- }
567
- /**
568
- * Loads Panoptic (required) and `@warlock.js/ai` (for the observation check)
569
- * lazily, or says why not. Shared by the development source and the AI
570
- * reports wiring, so both answer the same unavailable reasons.
571
- */
572
- async function loadAiPackages(deps = {}) {
573
- const aiPackage = "@warlock.js/ai";
574
- const load = deps.load ?? ((name) => name === "@warlock.js/ai-panoptic" ? import("@warlock.js/ai-panoptic") : import(aiPackage));
575
- const version = deps.version ?? ((name) => require_app_versions.installedVersion(name, process.cwd(), {}.resolve));
576
- let panoptic;
577
- try {
578
- panoptic = await load("@warlock.js/ai-panoptic");
579
- if (typeof panoptic.subscribeTraces !== "function") throw new Error("Trace subscription unavailable");
580
- } catch (error) {
581
- const aiVersion = version("@warlock.js/ai");
582
- const panopticVersion = version("@warlock.js/ai-panoptic");
583
- if (aiVersion === null) return { unavailable: describeAiUnavailable("ai-missing") };
584
- if (panopticVersion === null) return { unavailable: describeAiUnavailable("panoptic-missing") };
585
- return { unavailable: describeAiUnavailable("panoptic-failed", `${redactPaths((error instanceof Error ? error.message : String(error)).split("\n")[0] ?? "").slice(0, 300)} (@warlock.js/ai ${aiVersion}, @warlock.js/ai-panoptic ${panopticVersion})`) };
586
- }
587
- let core;
588
- try {
589
- core = await load("@warlock.js/ai");
590
- } catch {
591
- core = void 0;
592
- }
593
- const observationOff = () => typeof core?.isObserveAll === "function" && typeof core.getObservers === "function" && !core.isObserveAll() && core.getObservers().length === 0;
594
- return {
595
- panoptic,
596
- observationOff
597
- };
598
- }
599
- /**
600
- * Optional, lazy integration. Retains only traces collected after devtools boots,
601
- * using Panoptic's bounded query store; existing exporter/cache stores stay independent.
602
- */
603
- async function attachAiSource(capacity, deps = {}) {
604
- const loaded = await loadAiPackages(deps);
605
- if ("unavailable" in loaded) return {
606
- ...loaded.unavailable,
607
- dispose() {}
608
- };
609
- const { panoptic, observationOff } = loaded;
610
- const { currentRequestId } = await Promise.resolve().then(() => require("./current-request-id-Badec-TH.cjs")).then((n) => n.current_request_id_exports);
611
- const store = panoptic.createInMemoryTraceStore({ capacity });
612
- const listeners = /* @__PURE__ */ new Set();
613
- const detach = panoptic.subscribeTraces((trace) => {
614
- const requestId = currentRequestId() ?? trace.requestId;
615
- store.add({
616
- ...trace,
617
- requestId,
618
- usage: structuredClone(trace.usage),
619
- root: snapshotSpan(trace.root)
620
- });
621
- for (const listener of listeners) try {
622
- listener({
623
- traceId: trace.traceId,
624
- requestId
625
- });
626
- } catch {}
627
- });
628
- return {
629
- available: true,
630
- observationOff,
631
- totalCost: (usage) => panoptic.totalCostUsd(usage),
632
- helpers: {
633
- filterTraces: panoptic.filterTraces,
634
- groupBySession: panoptic.groupBySession,
635
- groupByPrompt: panoptic.groupByPrompt,
636
- groupByType: panoptic.groupByType,
637
- percentile: panoptic.percentile,
638
- tracePromptKey: panoptic.tracePromptKey
639
- },
640
- store,
641
- summarize: (trace) => summarizeAiTrace(trace, panoptic.totalCostUsd(trace.usage)),
642
- subscribe(listener) {
643
- listeners.add(listener);
644
- return () => {
645
- listeners.delete(listener);
646
- };
647
- },
648
- dispose() {
649
- detach();
650
- listeners.clear();
651
- store.clear();
652
- }
653
- };
359
+ for (const panel of panels) tabs.push({
360
+ id: panel.id,
361
+ title: panel.title,
362
+ type: "package",
363
+ shareable: panel.share !== void 0 && panel.share !== null
364
+ });
365
+ return tabs;
654
366
  }
655
367
 
656
368
  //#endregion
@@ -786,9 +498,26 @@ function subtract(own, other) {
786
498
  own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);
787
499
  own.reasoning = Math.max(0, own.reasoning - other.reasoning);
788
500
  }
501
+ /**
502
+ * The model a span reports: `agent.model.*` first, then `<span type>.model.*`
503
+ * (image, speech and transcription spans).
504
+ */
505
+ function spanModelOf(span) {
506
+ const attributes = span.attributes;
507
+ const pick = (key) => {
508
+ for (const prefix of ["agent", span.type]) {
509
+ const value = attributes?.[`${prefix}.${key}`];
510
+ if (typeof value === "string" && value !== "") return value;
511
+ }
512
+ };
513
+ return {
514
+ name: pick("model.name"),
515
+ provider: pick("model.provider")
516
+ };
517
+ }
789
518
  /** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */
790
519
  function isAiModelSpan(span) {
791
- return typeof span.attributes?.["agent.model.name"] === "string" || MODEL_SPAN_TYPES.has(span.type);
520
+ return spanModelOf(span).name !== void 0 || MODEL_SPAN_TYPES.has(span.type);
792
521
  }
793
522
  /** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */
794
523
  function nearestModelSpans(span) {
@@ -863,114 +592,414 @@ function traceToRollupDeltas(trace, totalCost) {
863
592
  const ended = Date.parse(span.endedAt);
864
593
  return Math.floor((Number.isNaN(ended) ? fallbackEnd : ended) / HOUR_MS) * HOUR_MS;
865
594
  };
866
- const deltas = [];
867
- const topLevel = isAiModelSpan(root) ? [root] : nearestModelSpans(root);
595
+ const deltas = [];
596
+ const topLevel = isAiModelSpan(root) ? [root] : nearestModelSpans(root);
597
+ const visit = (span) => {
598
+ const tokens = normalise(span.usage);
599
+ let cost = spanCost(span, totalCost);
600
+ const inner = nearestModelSpans(span);
601
+ for (const child of inner) {
602
+ subtract(tokens, normalise(child.usage));
603
+ cost -= spanCost(child, totalCost);
604
+ }
605
+ cost = Math.max(0, cost);
606
+ const pricedAtZero = hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));
607
+ const attributes = span.attributes ?? {};
608
+ const delta = buildDelta({
609
+ hour: hourOf(span),
610
+ ...aiRollupNamesOf(span)
611
+ }, span.status, span.error?.type, tokens, cost, pricedAtZero);
612
+ if (count(attributes["agent.fallbackTrips"]) > 0) delta.fallbackRuns = 1;
613
+ if (count(attributes["agent.refusals"]) > 0 || span.error?.type === "CONTENT_FILTER") delta.refusals = 1;
614
+ const duration = count(span.duration);
615
+ const bucket = aiLatencyBucket(duration);
616
+ delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;
617
+ delta.latencyCount = 1;
618
+ delta.latencySumMs = Math.max(0, duration);
619
+ deltas.push(delta);
620
+ for (const child of inner) visit(child);
621
+ };
622
+ for (const span of topLevel) visit(span);
623
+ const leftover = normalise(root.usage);
624
+ let leftoverCost = spanCost(root, totalCost);
625
+ for (const span of topLevel) {
626
+ subtract(leftover, normalise(span.usage));
627
+ leftoverCost -= spanCost(span, totalCost);
628
+ }
629
+ if (leftover.input + leftover.output > 0) deltas.push(buildDelta({
630
+ hour: hourOf(root),
631
+ agent: cut(root.name, 200),
632
+ model: UNKNOWN,
633
+ provider: UNKNOWN
634
+ }, root.status, root.error?.type, leftover, Math.max(0, leftoverCost)));
635
+ return deltas;
636
+ }
637
+ /** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */
638
+ function aiRollupNamesOf(span) {
639
+ return {
640
+ agent: cut(span.name, 200),
641
+ model: cut(spanModelOf(span).name, 200),
642
+ provider: cut(spanModelOf(span).provider, 100)
643
+ };
644
+ }
645
+ /** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */
646
+ function rollupId(key) {
647
+ return (0, node_crypto.createHash)("sha256").update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`).digest("hex").slice(0, 40);
648
+ }
649
+ /** A delta with every counter at zero for `key`. */
650
+ function emptyRollupDelta(key) {
651
+ return {
652
+ hour: key.hour,
653
+ agent: key.agent,
654
+ model: key.model,
655
+ provider: key.provider,
656
+ runs: 0,
657
+ completed: 0,
658
+ failed: 0,
659
+ incomplete: 0,
660
+ cancelled: 0,
661
+ inputTokens: 0,
662
+ outputTokens: 0,
663
+ cachedTokens: 0,
664
+ cacheWriteTokens: 0,
665
+ reasoningTokens: 0,
666
+ costUsd: 0,
667
+ pricedRuns: 0,
668
+ unpricedRuns: 0,
669
+ unpricedTokens: 0,
670
+ fallbackRuns: 0,
671
+ refusals: 0,
672
+ errors: emptyErrorCounts(),
673
+ latency: emptyAiLatency(),
674
+ latencyCount: 0,
675
+ latencySumMs: 0
676
+ };
677
+ }
678
+ const NUMERIC_COUNTERS = [
679
+ "runs",
680
+ "completed",
681
+ "failed",
682
+ "incomplete",
683
+ "cancelled",
684
+ "inputTokens",
685
+ "outputTokens",
686
+ "cachedTokens",
687
+ "cacheWriteTokens",
688
+ "reasoningTokens",
689
+ "costUsd",
690
+ "pricedRuns",
691
+ "unpricedRuns",
692
+ "unpricedTokens",
693
+ "fallbackRuns",
694
+ "refusals",
695
+ "latencyCount",
696
+ "latencySumMs"
697
+ ];
698
+ /** Adds the counters of `source` into `target` in place (keys must match). */
699
+ function addRollupCounters(target, source) {
700
+ for (const field of NUMERIC_COUNTERS) target[field] += source[field];
701
+ for (const category of Object.keys(target.errors)) target.errors[category] += source.errors[category] ?? 0;
702
+ addAiLatency(target.latency, source.latency);
703
+ }
704
+
705
+ //#endregion
706
+ //#region ../../packages/devtools/src/safe-value.ts
707
+ const MAX_DEPTH = 6;
708
+ /**
709
+ * A JSON-safe snapshot of a value devtools keeps for later display.
710
+ *
711
+ * Log contexts and phase attributes are app data: they can hold live objects
712
+ * (a request, its socket) whose graphs are circular and which must not be kept
713
+ * alive by the collector anyway. Plain objects and arrays are copied; anything
714
+ * with a `toJSON()` is serialized through it; other class instances collapse
715
+ * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to
716
+ * `[Object]` / `[Array]`.
717
+ */
718
+ function toSafeValue(value) {
719
+ return snapshot(value, 0, /* @__PURE__ */ new WeakSet());
720
+ }
721
+ function snapshot(value, depth, seen) {
722
+ if (value === null || value === void 0) return value;
723
+ switch (typeof value) {
724
+ case "string":
725
+ case "number":
726
+ case "boolean": return value;
727
+ case "bigint": return value.toString();
728
+ case "symbol": return value.toString();
729
+ case "function": return;
730
+ }
731
+ const object = value;
732
+ if (seen.has(object)) return "[Circular]";
733
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
734
+ if (value instanceof Error) return {
735
+ name: value.name,
736
+ message: value.message
737
+ };
738
+ if (depth >= MAX_DEPTH) return Array.isArray(value) ? "[Array]" : "[Object]";
739
+ seen.add(object);
740
+ try {
741
+ if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));
742
+ const prototype = Object.getPrototypeOf(object);
743
+ if (prototype !== Object.prototype && prototype !== null) {
744
+ const toJSON = object.toJSON;
745
+ if (typeof toJSON === "function") try {
746
+ return snapshot(toJSON.call(object), depth + 1, seen);
747
+ } catch {
748
+ return `[${constructorName(object)}]`;
749
+ }
750
+ return `[${constructorName(object)}]`;
751
+ }
752
+ const copy = {};
753
+ for (const [key, entry] of Object.entries(object)) {
754
+ const safe = snapshot(entry, depth + 1, seen);
755
+ if (safe !== void 0) copy[key] = safe;
756
+ }
757
+ return copy;
758
+ } finally {
759
+ seen.delete(object);
760
+ }
761
+ }
762
+ function constructorName(object) {
763
+ return object.constructor?.name || "Object";
764
+ }
765
+
766
+ //#endregion
767
+ //#region ../../packages/devtools/src/sources/ai-source.ts
768
+ /** Replaces absolute file paths in an error line with their package-relative part, or `<path>`. */
769
+ function redactPaths(text) {
770
+ return text.replace(/(?:file:\/\/)?(?:[A-Za-z]:)?[\\/][^\s'"`()]*/g, (match) => {
771
+ const normalized = match.replace(/^file:\/\//, "").replaceAll("\\", "/");
772
+ const index = normalized.lastIndexOf("node_modules/");
773
+ return index === -1 ? "<path>" : normalized.slice(index + 13);
774
+ });
775
+ }
776
+ const OBSERVATION_COMMAND = "ai.config({ panoptic: { observeAll: true } })";
777
+ /** The answer for each reason; `detail` carries the load error and versions for `panoptic-failed`. */
778
+ function describeAiUnavailable(reason, detail) {
779
+ switch (reason) {
780
+ case "ai-missing": return {
781
+ available: false,
782
+ reason,
783
+ title: "AI isn't installed",
784
+ message: "Add @warlock.js/ai to see AI runs here.",
785
+ command: "warlock add ai"
786
+ };
787
+ case "panoptic-missing": return {
788
+ available: false,
789
+ reason,
790
+ title: "Panoptic isn't installed",
791
+ message: "Your app uses @warlock.js/ai. Add Panoptic to see its runs.",
792
+ command: "warlock add ai-panoptic"
793
+ };
794
+ case "panoptic-failed": return {
795
+ available: false,
796
+ reason,
797
+ title: "Panoptic could not be loaded",
798
+ message: "Panoptic is installed but failed to load. Check that both packages share a version.",
799
+ detail
800
+ };
801
+ case "not-collected": return {
802
+ available: false,
803
+ reason,
804
+ title: "AI runs are not collected here",
805
+ message: "Production keeps hourly AI totals, not run details. Open Reports, Models or Errors here, or the Runs tab in development (warlock dev)."
806
+ };
807
+ case "table-missing": return {
808
+ available: false,
809
+ reason,
810
+ title: "AI reports need their table",
811
+ message: "Run the devtools migrations to create devtools_ai_rollups, then restart the app.",
812
+ command: "warlock migrate"
813
+ };
814
+ case "reports-off": return {
815
+ available: false,
816
+ reason,
817
+ title: "AI reports are off",
818
+ message: "Set devtools.ai.reports to true in src/config/devtools.ts to keep hourly AI totals."
819
+ };
820
+ case "observation-off": return {
821
+ available: false,
822
+ reason,
823
+ title: "AI observation is off",
824
+ message: "Turn it on in src/config/ai.ts, then restart warlock dev.",
825
+ command: OBSERVATION_COMMAND
826
+ };
827
+ }
828
+ }
829
+ /** The unavailable answer as the AI routes send it: `command` and `detail` are `null` when absent. */
830
+ function toAiUnavailableView(unavailable) {
831
+ return {
832
+ available: false,
833
+ reason: unavailable.reason,
834
+ title: unavailable.title,
835
+ message: unavailable.message,
836
+ command: unavailable.command ?? null,
837
+ detail: unavailable.detail ?? null
838
+ };
839
+ }
840
+ /** Summaries use root usage once: nested spans already roll up into it. */
841
+ function summarizeAiTrace(trace, cost) {
842
+ const models = /* @__PURE__ */ new Set();
843
+ let toolCalls = 0;
844
+ let retries = 0;
845
+ let cacheHits;
846
+ let incomplete = false;
847
+ let truncatedTrips = 0;
848
+ let compactions = 0;
849
+ let skippedCompactions = 0;
850
+ let providerCompactions = 0;
868
851
  const visit = (span) => {
869
- const tokens = normalise(span.usage);
870
- let cost = spanCost(span, totalCost);
871
- const inner = nearestModelSpans(span);
872
- for (const child of inner) {
873
- subtract(tokens, normalise(child.usage));
874
- cost -= spanCost(child, totalCost);
875
- }
876
- cost = Math.max(0, cost);
877
- const pricedAtZero = hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));
878
852
  const attributes = span.attributes ?? {};
879
- const delta = buildDelta({
880
- hour: hourOf(span),
881
- ...aiRollupNamesOf(span)
882
- }, span.status, span.error?.type, tokens, cost, pricedAtZero);
883
- if (count(attributes["agent.fallbackTrips"]) > 0) delta.fallbackRuns = 1;
884
- if (count(attributes["agent.refusals"]) > 0 || span.error?.type === "CONTENT_FILTER") delta.refusals = 1;
885
- const duration = count(span.duration);
886
- const bucket = aiLatencyBucket(duration);
887
- delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;
888
- delta.latencyCount = 1;
889
- delta.latencySumMs = Math.max(0, duration);
890
- deltas.push(delta);
891
- for (const child of inner) visit(child);
853
+ const { name: model, provider } = spanModelOf(span);
854
+ if (model !== void 0) models.add(provider !== void 0 ? `${provider}/${model}` : model);
855
+ if (span.type === "tool") toolCalls += 1;
856
+ if (typeof attributes.retries === "number") retries += attributes.retries;
857
+ if (typeof attributes["agent.cacheHits"] === "number") cacheHits = (cacheHits ?? 0) + attributes["agent.cacheHits"];
858
+ if (typeof attributes["agent.truncatedTrips"] === "number") truncatedTrips += attributes["agent.truncatedTrips"];
859
+ if (typeof attributes["agent.providerCompactions"] === "number") providerCompactions += attributes["agent.providerCompactions"];
860
+ if (Array.isArray(attributes["agent.compactions"])) {
861
+ const records = attributes["agent.compactions"];
862
+ for (const record of records) {
863
+ if (typeof record !== "object" || record === null || !("type" in record)) continue;
864
+ if (record.type === "applied") compactions += 1;
865
+ if (record.type === "skipped") skippedCompactions += 1;
866
+ }
867
+ }
868
+ incomplete ||= span.status === "incomplete" || span.error?.type === "AgentIncompleteError" || span.error?.type === "AGENT_INCOMPLETE";
869
+ span.children.forEach(visit);
892
870
  };
893
- for (const span of topLevel) visit(span);
894
- const leftover = normalise(root.usage);
895
- let leftoverCost = spanCost(root, totalCost);
896
- for (const span of topLevel) {
897
- subtract(leftover, normalise(span.usage));
898
- leftoverCost -= spanCost(span, totalCost);
899
- }
900
- if (leftover.input + leftover.output > 0) deltas.push(buildDelta({
901
- hour: hourOf(root),
902
- agent: cut(root.name, 200),
903
- model: UNKNOWN,
904
- provider: UNKNOWN
905
- }, root.status, root.error?.type, leftover, Math.max(0, leftoverCost)));
906
- return deltas;
907
- }
908
- /** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */
909
- function aiRollupNamesOf(span) {
871
+ visit(trace.root);
910
872
  return {
911
- agent: cut(span.name, 200),
912
- model: cut(span.attributes?.["agent.model.name"], 200),
913
- provider: cut(span.attributes?.["agent.model.provider"], 100)
873
+ traceId: trace.traceId,
874
+ requestId: trace.requestId,
875
+ sessionId: trace.sessionId,
876
+ name: trace.root.name,
877
+ status: trace.root.status,
878
+ startedAt: trace.startedAt,
879
+ duration: trace.duration,
880
+ usage: trace.usage,
881
+ cost,
882
+ models: [...models],
883
+ toolCalls,
884
+ retries,
885
+ cacheHits,
886
+ incomplete,
887
+ truncatedTrips,
888
+ compactions,
889
+ skippedCompactions,
890
+ providerCompactions
914
891
  };
915
892
  }
916
- /** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */
917
- function rollupId(key) {
918
- return (0, node_crypto.createHash)("sha256").update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`).digest("hex").slice(0, 40);
893
+ /** Content-free snapshot; never retain prompts, completions or tool arguments/results. */
894
+ function snapshotSpan(span) {
895
+ return {
896
+ spanId: span.spanId,
897
+ parentSpanId: span.parentSpanId,
898
+ traceId: span.traceId,
899
+ sessionId: span.sessionId,
900
+ name: span.name,
901
+ version: span.version,
902
+ type: span.type,
903
+ status: span.status,
904
+ startedAt: span.startedAt,
905
+ endedAt: span.endedAt,
906
+ duration: span.duration,
907
+ usage: structuredClone(span.usage),
908
+ error: span.error ? {
909
+ type: span.error.type,
910
+ message: span.error.message
911
+ } : void 0,
912
+ attributes: toSafeValue(span.attributes),
913
+ children: span.children.map(snapshotSpan)
914
+ };
919
915
  }
920
- /** A delta with every counter at zero for `key`. */
921
- function emptyRollupDelta(key) {
916
+ /**
917
+ * Loads Panoptic (required) and `@warlock.js/ai` (for the observation check)
918
+ * lazily, or says why not. Shared by the development source and the AI
919
+ * reports wiring, so both answer the same unavailable reasons.
920
+ */
921
+ async function loadAiPackages(deps = {}) {
922
+ const aiPackage = "@warlock.js/ai";
923
+ const load = deps.load ?? ((name) => name === "@warlock.js/ai-panoptic" ? import("@warlock.js/ai-panoptic") : import(aiPackage));
924
+ const version = deps.version ?? ((name) => require_app_versions.installedVersion(name, process.cwd(), {}.resolve));
925
+ let panoptic;
926
+ try {
927
+ panoptic = await load("@warlock.js/ai-panoptic");
928
+ if (typeof panoptic.subscribeTraces !== "function") throw new Error("Trace subscription unavailable");
929
+ } catch (error) {
930
+ const aiVersion = version("@warlock.js/ai");
931
+ const panopticVersion = version("@warlock.js/ai-panoptic");
932
+ if (aiVersion === null) return { unavailable: describeAiUnavailable("ai-missing") };
933
+ if (panopticVersion === null) return { unavailable: describeAiUnavailable("panoptic-missing") };
934
+ return { unavailable: describeAiUnavailable("panoptic-failed", `${redactPaths((error instanceof Error ? error.message : String(error)).split("\n")[0] ?? "").slice(0, 300)} (@warlock.js/ai ${aiVersion}, @warlock.js/ai-panoptic ${panopticVersion})`) };
935
+ }
936
+ let core;
937
+ try {
938
+ core = await load("@warlock.js/ai");
939
+ } catch {
940
+ core = void 0;
941
+ }
942
+ const observationOff = () => typeof core?.isObserveAll === "function" && typeof core.getObservers === "function" && !core.isObserveAll() && core.getObservers().length === 0;
922
943
  return {
923
- hour: key.hour,
924
- agent: key.agent,
925
- model: key.model,
926
- provider: key.provider,
927
- runs: 0,
928
- completed: 0,
929
- failed: 0,
930
- incomplete: 0,
931
- cancelled: 0,
932
- inputTokens: 0,
933
- outputTokens: 0,
934
- cachedTokens: 0,
935
- cacheWriteTokens: 0,
936
- reasoningTokens: 0,
937
- costUsd: 0,
938
- pricedRuns: 0,
939
- unpricedRuns: 0,
940
- unpricedTokens: 0,
941
- fallbackRuns: 0,
942
- refusals: 0,
943
- errors: emptyErrorCounts(),
944
- latency: emptyAiLatency(),
945
- latencyCount: 0,
946
- latencySumMs: 0
944
+ panoptic,
945
+ observationOff
947
946
  };
948
947
  }
949
- const NUMERIC_COUNTERS = [
950
- "runs",
951
- "completed",
952
- "failed",
953
- "incomplete",
954
- "cancelled",
955
- "inputTokens",
956
- "outputTokens",
957
- "cachedTokens",
958
- "cacheWriteTokens",
959
- "reasoningTokens",
960
- "costUsd",
961
- "pricedRuns",
962
- "unpricedRuns",
963
- "unpricedTokens",
964
- "fallbackRuns",
965
- "refusals",
966
- "latencyCount",
967
- "latencySumMs"
968
- ];
969
- /** Adds the counters of `source` into `target` in place (keys must match). */
970
- function addRollupCounters(target, source) {
971
- for (const field of NUMERIC_COUNTERS) target[field] += source[field];
972
- for (const category of Object.keys(target.errors)) target.errors[category] += source.errors[category] ?? 0;
973
- addAiLatency(target.latency, source.latency);
948
+ /**
949
+ * Optional, lazy integration. Retains only traces collected after devtools boots,
950
+ * using Panoptic's bounded query store; existing exporter/cache stores stay independent.
951
+ */
952
+ async function attachAiSource(capacity, deps = {}) {
953
+ const loaded = await loadAiPackages(deps);
954
+ if ("unavailable" in loaded) return {
955
+ ...loaded.unavailable,
956
+ dispose() {}
957
+ };
958
+ const { panoptic, observationOff } = loaded;
959
+ const { currentRequestId } = await Promise.resolve().then(() => require("./current-request-id-Badec-TH.cjs")).then((n) => n.current_request_id_exports);
960
+ const store = panoptic.createInMemoryTraceStore({ capacity });
961
+ const listeners = /* @__PURE__ */ new Set();
962
+ const detach = panoptic.subscribeTraces((trace) => {
963
+ const requestId = currentRequestId() ?? trace.requestId;
964
+ store.add({
965
+ ...trace,
966
+ requestId,
967
+ usage: structuredClone(trace.usage),
968
+ root: snapshotSpan(trace.root)
969
+ });
970
+ for (const listener of listeners) try {
971
+ listener({
972
+ traceId: trace.traceId,
973
+ requestId
974
+ });
975
+ } catch {}
976
+ });
977
+ return {
978
+ available: true,
979
+ observationOff,
980
+ totalCost: (usage) => panoptic.totalCostUsd(usage),
981
+ helpers: {
982
+ filterTraces: panoptic.filterTraces,
983
+ groupBySession: panoptic.groupBySession,
984
+ groupByPrompt: panoptic.groupByPrompt,
985
+ groupByType: panoptic.groupByType,
986
+ percentile: panoptic.percentile,
987
+ tracePromptKey: panoptic.tracePromptKey
988
+ },
989
+ store,
990
+ summarize: (trace) => summarizeAiTrace(trace, panoptic.totalCostUsd(trace.usage)),
991
+ subscribe(listener) {
992
+ listeners.add(listener);
993
+ return () => {
994
+ listeners.delete(listener);
995
+ };
996
+ },
997
+ dispose() {
998
+ detach();
999
+ listeners.clear();
1000
+ store.clear();
1001
+ }
1002
+ };
974
1003
  }
975
1004
 
976
1005
  //#endregion
@@ -1082,6 +1111,12 @@ Object.defineProperty(exports, "rollupId", {
1082
1111
  return rollupId;
1083
1112
  }
1084
1113
  });
1114
+ Object.defineProperty(exports, "spanModelOf", {
1115
+ enumerable: true,
1116
+ get: function () {
1117
+ return spanModelOf;
1118
+ }
1119
+ });
1085
1120
  Object.defineProperty(exports, "toAiUnavailableView", {
1086
1121
  enumerable: true,
1087
1122
  get: function () {
@@ -1100,4 +1135,10 @@ Object.defineProperty(exports, "traceToRollupDeltas", {
1100
1135
  return traceToRollupDeltas;
1101
1136
  }
1102
1137
  });
1103
- //# sourceMappingURL=extract-8kaX_cUV.cjs.map
1138
+ Object.defineProperty(exports, "withoutDevelopmentAiTabs", {
1139
+ enumerable: true,
1140
+ get: function () {
1141
+ return withoutDevelopmentAiTabs;
1142
+ }
1143
+ });
1144
+ //# sourceMappingURL=ai-source-CeHZDYG1.cjs.map