@warlock.js/devtools 5.59.0 → 5.60.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 (139) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/cjs/{app-versions-DfpPZOI2.cjs → app-versions-C_ZyzuvD.cjs} +1 -116
  3. package/cjs/app-versions-C_ZyzuvD.cjs.map +1 -0
  4. package/cjs/attach-D5aMqUnA.cjs +1342 -0
  5. package/cjs/attach-D5aMqUnA.cjs.map +1 -0
  6. package/cjs/{auth-B3wyjJnQ.cjs → auth-ChHh5E7j.cjs} +6 -6
  7. package/cjs/{auth-B3wyjJnQ.cjs.map → auth-ChHh5E7j.cjs.map} +1 -1
  8. package/cjs/{boot-nczSvJ_F.cjs → boot-Dg5YZGGR.cjs} +77 -14
  9. package/cjs/boot-Dg5YZGGR.cjs.map +1 -0
  10. package/cjs/{capture-CuyT8Vab.cjs → capture-CBgONYhk.cjs} +4 -4
  11. package/cjs/{capture-CuyT8Vab.cjs.map → capture-CBgONYhk.cjs.map} +1 -1
  12. package/cjs/{cascade-store-CuRRYzt_.cjs → cascade-store-DUT2Laha.cjs} +3 -3
  13. package/cjs/{cascade-store-CuRRYzt_.cjs.map → cascade-store-DUT2Laha.cjs.map} +1 -1
  14. package/cjs/{current-request-id-CeQhRz9Q.cjs → current-request-id-Badec-TH.cjs} +2 -2
  15. package/cjs/{current-request-id-CeQhRz9Q.cjs.map → current-request-id-Badec-TH.cjs.map} +1 -1
  16. package/cjs/{errors-BadbSDX8.cjs → errors-DNQ-g49I.cjs} +198 -1
  17. package/cjs/errors-DNQ-g49I.cjs.map +1 -0
  18. package/cjs/extract-8kaX_cUV.cjs +1103 -0
  19. package/cjs/extract-8kaX_cUV.cjs.map +1 -0
  20. package/cjs/{histogram-DTOGnNBW.cjs → histogram-CkoVizdf.cjs} +6 -6
  21. package/cjs/{histogram-DTOGnNBW.cjs.map → histogram-CkoVizdf.cjs.map} +1 -1
  22. package/cjs/{http-Biauhqi0.cjs → http-DCVCf44M.cjs} +25 -8
  23. package/cjs/http-DCVCf44M.cjs.map +1 -0
  24. package/cjs/index.cjs +1 -1
  25. package/cjs/{insights-BjJA6Ret.cjs → insights-CFof59kF.cjs} +3 -3
  26. package/cjs/{insights-BjJA6Ret.cjs.map → insights-CFof59kF.cjs.map} +1 -1
  27. package/cjs/migrations-BQdNOL5_.cjs +30 -0
  28. package/cjs/migrations-BQdNOL5_.cjs.map +1 -0
  29. package/cjs/{migrations-BP4cYTGo.cjs → models-DF1agAm4.cjs} +106 -24
  30. package/cjs/models-DF1agAm4.cjs.map +1 -0
  31. package/cjs/{process-panel-DskSA7Cm.cjs → process-panel-D3D9Y_dc.cjs} +4 -4
  32. package/cjs/{process-panel-DskSA7Cm.cjs.map → process-panel-D3D9Y_dc.cjs.map} +1 -1
  33. package/cjs/production/index.cjs +4 -4
  34. package/cjs/runs-DECWPGnq.cjs +390 -0
  35. package/cjs/runs-DECWPGnq.cjs.map +1 -0
  36. package/cjs/{server-D3XRbSSb.cjs → server-CC5DpObz.cjs} +8 -7
  37. package/cjs/{server-D3XRbSSb.cjs.map → server-CC5DpObz.cjs.map} +1 -1
  38. package/cjs/{src-QcNghoYN.cjs → src-VyOjEEAo.cjs} +178 -23
  39. package/cjs/src-VyOjEEAo.cjs.map +1 -0
  40. package/cjs/{store-CNFv3wVp.cjs → store-EFn4wp0T.cjs} +2 -2
  41. package/cjs/{stream-route-BqyAlfxQ.cjs → stream-route-DFHuIWgg.cjs} +107 -15
  42. package/cjs/stream-route-DFHuIWgg.cjs.map +1 -0
  43. package/esm/ai/attach.mjs +92 -0
  44. package/esm/ai/attach.mjs.map +1 -0
  45. package/esm/ai/options.mjs +31 -0
  46. package/esm/ai/options.mjs.map +1 -0
  47. package/esm/ai/reports/aggregate.mjs +330 -0
  48. package/esm/ai/reports/aggregate.mjs.map +1 -0
  49. package/esm/ai/reports/evaluate.mjs +108 -0
  50. package/esm/ai/reports/evaluate.mjs.map +1 -0
  51. package/esm/ai/reports/range.mjs +121 -0
  52. package/esm/ai/reports/range.mjs.map +1 -0
  53. package/esm/ai/reports/runs.d.mts +2 -0
  54. package/esm/ai/reports/runs.mjs +212 -0
  55. package/esm/ai/reports/runs.mjs.map +1 -0
  56. package/esm/ai/reports/service.mjs +132 -0
  57. package/esm/ai/reports/service.mjs.map +1 -0
  58. package/esm/ai/rollup/cascade-store.mjs +84 -0
  59. package/esm/ai/rollup/cascade-store.mjs.map +1 -0
  60. package/esm/ai/rollup/categories.mjs +67 -0
  61. package/esm/ai/rollup/categories.mjs.map +1 -0
  62. package/esm/ai/rollup/extract.mjs +225 -0
  63. package/esm/ai/rollup/extract.mjs.map +1 -0
  64. package/esm/ai/rollup/file-store.mjs +147 -0
  65. package/esm/ai/rollup/file-store.mjs.map +1 -0
  66. package/esm/ai/rollup/histogram.mjs +42 -0
  67. package/esm/ai/rollup/histogram.mjs.map +1 -0
  68. package/esm/ai/rollup/increment-error.mjs +19 -0
  69. package/esm/ai/rollup/increment-error.mjs.map +1 -0
  70. package/esm/ai/rollup/index.mjs +9 -0
  71. package/esm/ai/rollup/mapping.mjs +69 -0
  72. package/esm/ai/rollup/mapping.mjs.map +1 -0
  73. package/esm/ai/rollup/memory-store.mjs +26 -0
  74. package/esm/ai/rollup/memory-store.mjs.map +1 -0
  75. package/esm/ai/rollup/writer.mjs +113 -0
  76. package/esm/ai/rollup/writer.mjs.map +1 -0
  77. package/esm/ai/types.d.mts +29 -0
  78. package/esm/ai/types.d.mts.map +1 -0
  79. package/esm/devtools-connector.d.mts.map +1 -1
  80. package/esm/devtools-connector.mjs +54 -2
  81. package/esm/devtools-connector.mjs.map +1 -1
  82. package/esm/index.d.mts +3 -2
  83. package/esm/options.mjs +4 -0
  84. package/esm/options.mjs.map +1 -1
  85. package/esm/production/boot.mjs +69 -3
  86. package/esm/production/boot.mjs.map +1 -1
  87. package/esm/production/contracts.d.mts +371 -2
  88. package/esm/production/contracts.d.mts.map +1 -1
  89. package/esm/production/contracts.mjs +64 -2
  90. package/esm/production/contracts.mjs.map +1 -1
  91. package/esm/production/errors.mjs +8 -0
  92. package/esm/production/errors.mjs.map +1 -1
  93. package/esm/production/http/access.mjs +6 -0
  94. package/esm/production/http/access.mjs.map +1 -1
  95. package/esm/production/http/mount.mjs +13 -0
  96. package/esm/production/http/mount.mjs.map +1 -1
  97. package/esm/production/index.d.mts +2 -2
  98. package/esm/production/store/migrations.d.mts +1 -1
  99. package/esm/production/store/migrations.d.mts.map +1 -1
  100. package/esm/production/store/migrations.mjs +4 -2
  101. package/esm/production/store/migrations.mjs.map +1 -1
  102. package/esm/production/store/models/ai-rollup.migration.mjs +48 -0
  103. package/esm/production/store/models/ai-rollup.migration.mjs.map +1 -0
  104. package/esm/production/store/models/ai-rollup.model.mjs +13 -0
  105. package/esm/production/store/models/ai-rollup.model.mjs.map +1 -0
  106. package/esm/production/store/models/index.mjs +3 -1
  107. package/esm/server/ai-report-routes.mjs +72 -0
  108. package/esm/server/ai-report-routes.mjs.map +1 -0
  109. package/esm/server/ai-routes.mjs +22 -1
  110. package/esm/server/ai-routes.mjs.map +1 -1
  111. package/esm/server/index.mjs +2 -0
  112. package/esm/server/index.mjs.map +1 -1
  113. package/esm/sources/agent-trace-source.d.mts.map +1 -1
  114. package/esm/sources/agent-trace-source.mjs.map +1 -1
  115. package/esm/sources/ai-source.d.mts +2 -0
  116. package/esm/sources/ai-source.d.mts.map +1 -1
  117. package/esm/sources/ai-source.mjs +58 -17
  118. package/esm/sources/ai-source.mjs.map +1 -1
  119. package/esm/types.d.mts +13 -3
  120. package/esm/types.d.mts.map +1 -1
  121. package/llms-full.txt +56 -17
  122. package/package.json +8 -8
  123. package/skills/SKILL.md +56 -17
  124. package/ui/dashboard/assets/app.css +1 -1
  125. package/ui/dashboard/assets/app.js +12 -5
  126. package/ui/dashboard/build-info.json +7 -7
  127. package/cjs/ai-source-BdvMfyKw.cjs +0 -448
  128. package/cjs/ai-source-BdvMfyKw.cjs.map +0 -1
  129. package/cjs/app-versions-DfpPZOI2.cjs.map +0 -1
  130. package/cjs/boot-nczSvJ_F.cjs.map +0 -1
  131. package/cjs/errors-BadbSDX8.cjs.map +0 -1
  132. package/cjs/http-Biauhqi0.cjs.map +0 -1
  133. package/cjs/migrations-BP4cYTGo.cjs.map +0 -1
  134. package/cjs/options-B9FHbRAJ.cjs +0 -205
  135. package/cjs/options-B9FHbRAJ.cjs.map +0 -1
  136. package/cjs/panels-D1ITm-jc.cjs +0 -384
  137. package/cjs/panels-D1ITm-jc.cjs.map +0 -1
  138. package/cjs/src-QcNghoYN.cjs.map +0 -1
  139. package/cjs/stream-route-BqyAlfxQ.cjs.map +0 -1
@@ -0,0 +1,92 @@
1
+ import { describeAiUnavailable, loadAiPackages, toAiUnavailableView } from "../sources/ai-source.mjs";
2
+ import { createAiReportService } from "./reports/service.mjs";
3
+ import { createCascadeAiRollupStore } from "./rollup/cascade-store.mjs";
4
+ import { createFileAiRollupStore } from "./rollup/file-store.mjs";
5
+ import { startAiRollupWriter } from "./rollup/writer.mjs";
6
+ import "./rollup/index.mjs";
7
+ import path from "node:path";
8
+
9
+ //#region ../../packages/devtools/src/ai/attach.ts
10
+ /**
11
+ * Loads Panoptic's trace feed (`subscribeTraces`, `totalCostUsd`) and
12
+ * `@warlock.js/ai`'s observer registry lazily, plus the Runs helpers. Returns
13
+ * `{ unavailable }` (`ai-missing`, `panoptic-missing`, `panoptic-failed`)
14
+ * when they do not load. Shared by the development and production wiring.
15
+ */
16
+ async function loadAiFeed(deps) {
17
+ const loaded = await loadAiPackages(deps);
18
+ if ("unavailable" in loaded) return { unavailable: toAiUnavailableView(loaded.unavailable) };
19
+ const { panoptic, observationOff } = loaded;
20
+ return {
21
+ feed: {
22
+ subscribe: (listener) => panoptic.subscribeTraces(listener),
23
+ totalCost: (usage) => panoptic.totalCostUsd(usage),
24
+ observationOff
25
+ },
26
+ helpers: {
27
+ filterTraces: panoptic.filterTraces,
28
+ groupBySession: panoptic.groupBySession,
29
+ groupByPrompt: panoptic.groupByPrompt,
30
+ groupByType: panoptic.groupByType,
31
+ percentile: panoptic.percentile,
32
+ tracePromptKey: panoptic.tracePromptKey
33
+ }
34
+ };
35
+ }
36
+ const TABLE_MISSING_WARNING = "AI reports are off: the devtools_ai_rollups table is missing. Run the devtools migrations (warlock migrate), then restart.";
37
+ /**
38
+ * Starts the AI reports of this process: with `options.reports` off answers
39
+ * `reports-off`; otherwise builds the store for the mode (development: the
40
+ * file store in `directory`; production: the cascade store, `table-missing`
41
+ * when `verify()` is false, logged once with the migration hint), starts the
42
+ * rollup writer on `feed.subscribe`, and builds the report service.
43
+ * `dispose` unsubscribes and stops the writer (final flush).
44
+ */
45
+ async function attachAiReports(input) {
46
+ const { feed, options, warn } = input;
47
+ const off = (reason) => ({
48
+ ...toAiUnavailableView(describeAiUnavailable(reason)),
49
+ async dispose() {}
50
+ });
51
+ if (!options.reports) return off("reports-off");
52
+ const production = options.mode === "production";
53
+ let store;
54
+ try {
55
+ store = production ? await createCascadeAiRollupStore() : createFileAiRollupStore({ directory: input.directory ?? path.join(process.cwd(), "storage", "devtools", "ai-rollups") });
56
+ if (!await store.verify()) {
57
+ warn(TABLE_MISSING_WARNING);
58
+ return off("table-missing");
59
+ }
60
+ } catch (error) {
61
+ warn(`${TABLE_MISSING_WARNING} (${error instanceof Error ? error.message : String(error)})`);
62
+ return off("table-missing");
63
+ }
64
+ const writer = startAiRollupWriter({
65
+ store,
66
+ totalCost: feed.totalCost,
67
+ options,
68
+ warn
69
+ });
70
+ const unsubscribe = feed.subscribe((trace) => writer.record(trace));
71
+ return {
72
+ available: true,
73
+ service: createAiReportService({
74
+ store,
75
+ pending: () => writer.pending(),
76
+ retentionDays: options.retentionDays,
77
+ observationOff: () => feed.observationOff(),
78
+ ...input.recentFailures ? { recentFailures: input.recentFailures } : {}
79
+ }),
80
+ writer,
81
+ async dispose() {
82
+ unsubscribe();
83
+ await writer.stop();
84
+ }
85
+ };
86
+ }
87
+ /** The global key devtools publishes once mounted, read by Panoptic to keep its own dashboard off. */
88
+ const DEVTOOLS_MOUNTED_KEY = Symbol.for("@warlock.js/devtools.mounted");
89
+
90
+ //#endregion
91
+ export { DEVTOOLS_MOUNTED_KEY, attachAiReports, loadAiFeed };
92
+ //# sourceMappingURL=attach.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/ai/attach.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { DevtoolsAiFailedRun, DevtoolsAiUnavailableView } from \"../production/contracts\";\nimport { describeAiUnavailable, loadAiPackages, toAiUnavailableView } from \"../sources/ai-source\";\nimport { createAiReportService, type DevtoolsAiReportService } from \"./reports/service\";\nimport type { DevtoolsAiRecentFailuresFilter, DevtoolsAiRunHelpers } from \"./reports/runs\";\nimport { createCascadeAiRollupStore, createFileAiRollupStore, startAiRollupWriter } from \"./rollup\";\nimport type {\n DevtoolsAiFeed,\n DevtoolsAiRollupStore,\n DevtoolsAiRollupWriter,\n ResolvedDevtoolsAiOptions,\n} from \"./types\";\n\n/** The AI reports wiring of one process, as the routes receive it. */\nexport type DevtoolsAiReports =\n | {\n available: true;\n service: DevtoolsAiReportService;\n writer: DevtoolsAiRollupWriter;\n dispose(): Promise<void>;\n }\n | (DevtoolsAiUnavailableView & { dispose(): Promise<void> });\n\n/**\n * Loads Panoptic's trace feed (`subscribeTraces`, `totalCostUsd`) and\n * `@warlock.js/ai`'s observer registry lazily, plus the Runs helpers. Returns\n * `{ unavailable }` (`ai-missing`, `panoptic-missing`, `panoptic-failed`)\n * when they do not load. Shared by the development and production wiring.\n */\nexport async function loadAiFeed(deps?: {\n load?: (name: string) => Promise<unknown>;\n version?: (name: string) => string | null;\n}): Promise<\n | { feed: DevtoolsAiFeed; helpers: DevtoolsAiRunHelpers }\n | { unavailable: DevtoolsAiUnavailableView }\n> {\n const loaded = await loadAiPackages(deps);\n\n if (\"unavailable\" in loaded) return { unavailable: toAiUnavailableView(loaded.unavailable) };\n\n const { panoptic, observationOff } = loaded;\n\n return {\n feed: {\n subscribe: (listener) => panoptic.subscribeTraces(listener),\n totalCost: (usage) => panoptic.totalCostUsd(usage),\n observationOff,\n },\n helpers: {\n filterTraces: panoptic.filterTraces,\n groupBySession: panoptic.groupBySession,\n groupByPrompt: panoptic.groupByPrompt,\n groupByType: panoptic.groupByType,\n percentile: panoptic.percentile,\n tracePromptKey: panoptic.tracePromptKey,\n },\n };\n}\n\nconst TABLE_MISSING_WARNING =\n \"AI reports are off: the devtools_ai_rollups table is missing. Run the devtools migrations (warlock migrate), then restart.\";\n\n/**\n * Starts the AI reports of this process: with `options.reports` off answers\n * `reports-off`; otherwise builds the store for the mode (development: the\n * file store in `directory`; production: the cascade store, `table-missing`\n * when `verify()` is false, logged once with the migration hint), starts the\n * rollup writer on `feed.subscribe`, and builds the report service.\n * `dispose` unsubscribes and stops the writer (final flush).\n */\nexport async function attachAiReports(input: {\n feed: DevtoolsAiFeed;\n options: ResolvedDevtoolsAiOptions;\n /** Development only: where the file store writes (core's `storagePath(\"devtools/ai-rollups\")`). */\n directory?: string;\n /** Development only: recent failures from the Runs store, scoped to a page's range and filters. */\n recentFailures?: (filter: DevtoolsAiRecentFailuresFilter) => DevtoolsAiFailedRun[];\n warn: (message: string) => void;\n}): Promise<DevtoolsAiReports> {\n const { feed, options, warn } = input;\n const off = (reason: \"reports-off\" | \"table-missing\"): DevtoolsAiReports => ({\n ...toAiUnavailableView(describeAiUnavailable(reason)),\n async dispose() {},\n });\n\n if (!options.reports) return off(\"reports-off\");\n\n const production = options.mode === \"production\";\n let store: DevtoolsAiRollupStore;\n\n try {\n store = production\n ? await createCascadeAiRollupStore()\n : createFileAiRollupStore({\n directory:\n input.directory ?? path.join(process.cwd(), \"storage\", \"devtools\", \"ai-rollups\"),\n });\n\n if (!(await store.verify())) {\n warn(TABLE_MISSING_WARNING);\n\n return off(\"table-missing\");\n }\n } catch (error) {\n warn(`${TABLE_MISSING_WARNING} (${error instanceof Error ? error.message : String(error)})`);\n\n return off(\"table-missing\");\n }\n\n const writer = startAiRollupWriter({ store, totalCost: feed.totalCost, options, warn });\n const unsubscribe = feed.subscribe((trace) => writer.record(trace));\n const service = createAiReportService({\n store,\n pending: () => writer.pending(),\n retentionDays: options.retentionDays,\n observationOff: () => feed.observationOff(),\n ...(input.recentFailures ? { recentFailures: input.recentFailures } : {}),\n });\n\n return {\n available: true,\n service,\n writer,\n async dispose() {\n unsubscribe();\n await writer.stop();\n },\n };\n}\n\n/** The global key devtools publishes once mounted, read by Panoptic to keep its own dashboard off. */\nexport const DEVTOOLS_MOUNTED_KEY = Symbol.for(\"@warlock.js/devtools.mounted\");\n\n/** What is published under `DEVTOOLS_MOUNTED_KEY`. */\nexport type DevtoolsMountedMarker = { path: string; mode: \"development\" | \"production\" };\n"],"mappings":";;;;;;;;;;;;;;;AA6BA,eAAsB,WAAW,MAM/B;CACA,MAAM,SAAS,MAAM,eAAe,IAAI;CAExC,IAAI,iBAAiB,QAAQ,OAAO,EAAE,aAAa,oBAAoB,OAAO,WAAW,EAAE;CAE3F,MAAM,EAAE,UAAU,mBAAmB;CAErC,OAAO;EACL,MAAM;GACJ,YAAY,aAAa,SAAS,gBAAgB,QAAQ;GAC1D,YAAY,UAAU,SAAS,aAAa,KAAK;GACjD;EACF;EACA,SAAS;GACP,cAAc,SAAS;GACvB,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,aAAa,SAAS;GACtB,YAAY,SAAS;GACrB,gBAAgB,SAAS;EAC3B;CACF;AACF;AAEA,MAAM,wBACJ;;;;;;;;;AAUF,eAAsB,gBAAgB,OAQP;CAC7B,MAAM,EAAE,MAAM,SAAS,SAAS;CAChC,MAAM,OAAO,YAAgE;EAC3E,GAAG,oBAAoB,sBAAsB,MAAM,CAAC;EACpD,MAAM,UAAU,CAAC;CACnB;CAEA,IAAI,CAAC,QAAQ,SAAS,OAAO,IAAI,aAAa;CAE9C,MAAM,aAAa,QAAQ,SAAS;CACpC,IAAI;CAEJ,IAAI;EACF,QAAQ,aACJ,MAAM,2BAA2B,IACjC,wBAAwB,EACtB,WACE,MAAM,aAAa,KAAK,KAAK,QAAQ,IAAI,GAAG,WAAW,YAAY,YAAY,EACnF,CAAC;EAEL,IAAI,CAAE,MAAM,MAAM,OAAO,GAAI;GAC3B,KAAK,qBAAqB;GAE1B,OAAO,IAAI,eAAe;EAC5B;CACF,SAAS,OAAO;EACd,KAAK,GAAG,sBAAsB,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,EAAE;EAE3F,OAAO,IAAI,eAAe;CAC5B;CAEA,MAAM,SAAS,oBAAoB;EAAE;EAAO,WAAW,KAAK;EAAW;EAAS;CAAK,CAAC;CACtF,MAAM,cAAc,KAAK,WAAW,UAAU,OAAO,OAAO,KAAK,CAAC;CASlE,OAAO;EACL,WAAW;EACX,SAVc,sBAAsB;GACpC;GACA,eAAe,OAAO,QAAQ;GAC9B,eAAe,QAAQ;GACvB,sBAAsB,KAAK,eAAe;GAC1C,GAAI,MAAM,iBAAiB,EAAE,gBAAgB,MAAM,eAAe,IAAI,CAAC;EACzE,CAIQ;EACN;EACA,MAAM,UAAU;GACd,YAAY;GACZ,MAAM,OAAO,KAAK;EACpB;CACF;AACF;;AAGA,MAAa,uBAAuB,OAAO,IAAI,8BAA8B"}
@@ -0,0 +1,31 @@
1
+ //#region ../../packages/devtools/src/ai/options.ts
2
+ /** Default `retentionDays` per mode. */
3
+ const DEVTOOLS_AI_RETENTION_DAYS = {
4
+ development: 30,
5
+ production: 90
6
+ };
7
+ /** Default `flushIntervalMs`. */
8
+ const DEVTOOLS_AI_FLUSH_INTERVAL_MS = 6e4;
9
+ /**
10
+ * Applies the defaults of `devtools.ai` for `mode`. Throws an `Error` naming
11
+ * the option when `retentionDays` is not a whole number from 1 to 400 or
12
+ * `flushIntervalMs` is below 5000 (the same style as `resolveDevtoolsOptions`).
13
+ */
14
+ function resolveDevtoolsAiOptions(options, mode) {
15
+ const reports = options?.reports ?? true;
16
+ const retentionDays = options?.retentionDays ?? DEVTOOLS_AI_RETENTION_DAYS[mode];
17
+ const flushIntervalMs = options?.flushIntervalMs ?? 6e4;
18
+ if (typeof reports !== "boolean") throw new Error("Devtools option \"ai.reports\" must be true or false.");
19
+ if (!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 400) throw new Error("Devtools option \"ai.retentionDays\" must be a whole number from 1 to 400.");
20
+ if (typeof flushIntervalMs !== "number" || !Number.isFinite(flushIntervalMs) || flushIntervalMs < 5e3) throw new Error("Devtools option \"ai.flushIntervalMs\" must be at least 5000.");
21
+ return {
22
+ reports,
23
+ retentionDays,
24
+ flushIntervalMs,
25
+ mode
26
+ };
27
+ }
28
+
29
+ //#endregion
30
+ export { DEVTOOLS_AI_FLUSH_INTERVAL_MS, DEVTOOLS_AI_RETENTION_DAYS, resolveDevtoolsAiOptions };
31
+ //# sourceMappingURL=options.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/ai/options.ts"],"sourcesContent":["import type { DevtoolsMode } from \"../production/contracts\";\nimport type { DevtoolsAiOptions, ResolvedDevtoolsAiOptions } from \"./types\";\n\n/** Default `retentionDays` per mode. */\nexport const DEVTOOLS_AI_RETENTION_DAYS: Readonly<Record<DevtoolsMode, number>> = {\n development: 30,\n production: 90,\n};\n\n/** Default `flushIntervalMs`. */\nexport const DEVTOOLS_AI_FLUSH_INTERVAL_MS = 60_000;\n\n/**\n * Applies the defaults of `devtools.ai` for `mode`. Throws an `Error` naming\n * the option when `retentionDays` is not a whole number from 1 to 400 or\n * `flushIntervalMs` is below 5000 (the same style as `resolveDevtoolsOptions`).\n */\nexport function resolveDevtoolsAiOptions(\n options: DevtoolsAiOptions | undefined,\n mode: DevtoolsMode,\n): ResolvedDevtoolsAiOptions {\n const reports = options?.reports ?? true;\n const retentionDays = options?.retentionDays ?? DEVTOOLS_AI_RETENTION_DAYS[mode];\n const flushIntervalMs = options?.flushIntervalMs ?? DEVTOOLS_AI_FLUSH_INTERVAL_MS;\n\n if (typeof reports !== \"boolean\") {\n throw new Error('Devtools option \"ai.reports\" must be true or false.');\n }\n\n if (!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 400) {\n throw new Error('Devtools option \"ai.retentionDays\" must be a whole number from 1 to 400.');\n }\n\n if (\n typeof flushIntervalMs !== \"number\" ||\n !Number.isFinite(flushIntervalMs) ||\n flushIntervalMs < 5000\n ) {\n throw new Error('Devtools option \"ai.flushIntervalMs\" must be at least 5000.');\n }\n\n return { reports, retentionDays, flushIntervalMs, mode };\n}\n"],"mappings":";;AAIA,MAAa,6BAAqE;CAChF,aAAa;CACb,YAAY;AACd;;AAGA,MAAa,gCAAgC;;;;;;AAO7C,SAAgB,yBACd,SACA,MAC2B;CAC3B,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,gBAAgB,SAAS,iBAAiB,2BAA2B;CAC3E,MAAM,kBAAkB,SAAS;CAEjC,IAAI,OAAO,YAAY,WACrB,MAAM,IAAI,MAAM,uDAAqD;CAGvE,IAAI,CAAC,OAAO,UAAU,aAAa,KAAK,gBAAgB,KAAK,gBAAgB,KAC3E,MAAM,IAAI,MAAM,4EAA0E;CAG5F,IACE,OAAO,oBAAoB,YAC3B,CAAC,OAAO,SAAS,eAAe,KAChC,kBAAkB,KAElB,MAAM,IAAI,MAAM,+DAA6D;CAG/E,OAAO;EAAE;EAAS;EAAe;EAAiB;CAAK;AACzD"}
@@ -0,0 +1,330 @@
1
+ import { DEVTOOLS_AI_ERROR_CATEGORIES } from "../../production/contracts.mjs";
2
+ import { DEVTOOLS_AI_ERROR_LABELS } from "../rollup/categories.mjs";
3
+ import { addAiLatency, aiLatencyQuantile, emptyAiLatency } from "../rollup/histogram.mjs";
4
+
5
+ //#region ../../packages/devtools/src/ai/reports/aggregate.ts
6
+ /**
7
+ * Pure folds from rollup rows (stored records plus pending deltas) to the
8
+ * report shapes in `production/contracts.ts`. No I/O, no clock.
9
+ */
10
+ const MAX_NAMED_SERIES = 5;
11
+ const OTHER_KEY = "__other";
12
+ /** `provider/model`, the key the UI filters and colours models by. */
13
+ function modelKey(row) {
14
+ return `${row.provider}/${row.model}`;
15
+ }
16
+ /** Sums rows into totals (latency from the merged histogram). */
17
+ function totalsOf(rows) {
18
+ const totals = {
19
+ runs: 0,
20
+ completed: 0,
21
+ failed: 0,
22
+ incomplete: 0,
23
+ cancelled: 0,
24
+ errorRate: 0,
25
+ tokens: {
26
+ input: 0,
27
+ output: 0,
28
+ cached: 0,
29
+ cacheWrite: 0,
30
+ reasoning: 0
31
+ },
32
+ cost: {
33
+ estimatedUsd: 0,
34
+ pricedRuns: 0,
35
+ unpricedRuns: 0,
36
+ unpricedTokens: 0
37
+ },
38
+ latency: {
39
+ p50Ms: null,
40
+ p95Ms: null,
41
+ meanMs: null
42
+ },
43
+ fallbackRuns: 0,
44
+ refusals: 0
45
+ };
46
+ const histogram = emptyAiLatency();
47
+ let latencyCount = 0;
48
+ let latencySumMs = 0;
49
+ for (const row of rows) {
50
+ totals.runs += row.runs;
51
+ totals.completed += row.completed;
52
+ totals.failed += row.failed;
53
+ totals.incomplete += row.incomplete;
54
+ totals.cancelled += row.cancelled;
55
+ totals.tokens.input += row.inputTokens;
56
+ totals.tokens.output += row.outputTokens;
57
+ totals.tokens.cached += row.cachedTokens;
58
+ totals.tokens.cacheWrite += row.cacheWriteTokens;
59
+ totals.tokens.reasoning += row.reasoningTokens;
60
+ totals.cost.estimatedUsd += row.costUsd;
61
+ totals.cost.pricedRuns += row.pricedRuns;
62
+ totals.cost.unpricedRuns += row.unpricedRuns;
63
+ totals.cost.unpricedTokens += row.unpricedTokens;
64
+ totals.fallbackRuns += row.fallbackRuns;
65
+ totals.refusals += row.refusals;
66
+ addAiLatency(histogram, row.latency);
67
+ latencyCount += row.latencyCount;
68
+ latencySumMs += row.latencySumMs;
69
+ }
70
+ totals.errorRate = totals.runs > 0 ? (totals.failed + totals.incomplete) / totals.runs : 0;
71
+ totals.latency = {
72
+ p50Ms: aiLatencyQuantile(histogram, .5),
73
+ p95Ms: aiLatencyQuantile(histogram, .95),
74
+ meanMs: latencyCount > 0 ? latencySumMs / latencyCount : null
75
+ };
76
+ return totals;
77
+ }
78
+ /** The bucket index of an hour inside `range` (`-1` outside). */
79
+ function bucketOf(hour, range) {
80
+ if (hour < range.from || hour >= range.to) return -1;
81
+ return Math.floor((hour - range.from) / range.stepMs);
82
+ }
83
+ /** Bucket starts of a range, oldest first. */
84
+ function bucketStarts(range) {
85
+ const count = Math.max(0, Math.ceil((range.to - range.from) / range.stepMs));
86
+ return Array.from({ length: count }, (_, index) => range.from + index * range.stepMs);
87
+ }
88
+ /** Top five keys by sum become series, the rest are summed into `__other`. */
89
+ function buildSeries(range, entries) {
90
+ const buckets = bucketStarts(range);
91
+ const byKey = /* @__PURE__ */ new Map();
92
+ for (const entry of entries) {
93
+ if (entry.bucket < 0 || entry.bucket >= buckets.length) continue;
94
+ let item = byKey.get(entry.key);
95
+ if (!item) {
96
+ item = {
97
+ label: entry.label,
98
+ sum: 0,
99
+ values: new Array(buckets.length).fill(0)
100
+ };
101
+ byKey.set(entry.key, item);
102
+ }
103
+ item.values[entry.bucket] = (item.values[entry.bucket] ?? 0) + entry.value;
104
+ item.sum += entry.value;
105
+ }
106
+ const ranked = [...byKey.entries()].sort((a, b) => b[1].sum - a[1].sum || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
107
+ const series = ranked.slice(0, MAX_NAMED_SERIES).map(([key, item]) => ({
108
+ key,
109
+ label: item.label,
110
+ values: item.values,
111
+ other: false
112
+ }));
113
+ const rest = ranked.slice(MAX_NAMED_SERIES);
114
+ if (rest.length > 0) {
115
+ const values = new Array(buckets.length).fill(0);
116
+ for (const [, item] of rest) item.values.forEach((value, index) => {
117
+ values[index] = (values[index] ?? 0) + value;
118
+ });
119
+ series.push({
120
+ key: OTHER_KEY,
121
+ label: "Other",
122
+ values,
123
+ other: true
124
+ });
125
+ }
126
+ return {
127
+ buckets,
128
+ series
129
+ };
130
+ }
131
+ /**
132
+ * A stacked series set: `value(row)` per bucket, grouped by `keyOf(row)`; the
133
+ * five keys with the largest sum are named, the rest summed into `other`
134
+ * (key `__other`, label "Other"). Buckets with no rows are 0.
135
+ */
136
+ function seriesBy(rows, range, keyOf, labelOf, value) {
137
+ return buildSeries(range, rows.map((row) => {
138
+ const key = keyOf(row);
139
+ return {
140
+ bucket: bucketOf(row.hour, range),
141
+ key,
142
+ label: labelOf(key),
143
+ value: value(row)
144
+ };
145
+ }));
146
+ }
147
+ /** Tokens per bucket: `uncached` (input − cached), `cached`, `output`. */
148
+ function tokenSeries(rows, range) {
149
+ const buckets = bucketStarts(range);
150
+ const uncached = new Array(buckets.length).fill(0);
151
+ const cached = new Array(buckets.length).fill(0);
152
+ const output = new Array(buckets.length).fill(0);
153
+ for (const row of rows) {
154
+ const bucket = bucketOf(row.hour, range);
155
+ if (bucket < 0 || bucket >= buckets.length) continue;
156
+ uncached[bucket] = (uncached[bucket] ?? 0) + Math.max(0, row.inputTokens - row.cachedTokens);
157
+ cached[bucket] = (cached[bucket] ?? 0) + row.cachedTokens;
158
+ output[bucket] = (output[bucket] ?? 0) + row.outputTokens;
159
+ }
160
+ return {
161
+ buckets,
162
+ series: [
163
+ {
164
+ key: "uncached",
165
+ label: "Uncached input",
166
+ values: uncached,
167
+ other: false
168
+ },
169
+ {
170
+ key: "cached",
171
+ label: "Cached input",
172
+ values: cached,
173
+ other: false
174
+ },
175
+ {
176
+ key: "output",
177
+ label: "Output",
178
+ values: output,
179
+ other: false
180
+ }
181
+ ]
182
+ };
183
+ }
184
+ /** The error rate per bucket; `rate: null` where a bucket has no runs. */
185
+ function errorRateSeries(rows, range) {
186
+ const points = bucketStarts(range).map((at) => ({
187
+ at,
188
+ runs: 0,
189
+ errors: 0,
190
+ rate: null
191
+ }));
192
+ for (const row of rows) {
193
+ const point = points[bucketOf(row.hour, range)];
194
+ if (!point) continue;
195
+ point.runs += row.runs;
196
+ point.errors += row.failed + row.incomplete;
197
+ }
198
+ for (const point of points) point.rate = point.runs > 0 ? point.errors / point.runs : null;
199
+ return points;
200
+ }
201
+ /** Failed runs per bucket by category (top five plus Other). */
202
+ function errorSeries(rows, range) {
203
+ const entries = [];
204
+ for (const row of rows) {
205
+ const bucket = bucketOf(row.hour, range);
206
+ for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) {
207
+ const value = row.errors[category];
208
+ if (value > 0) entries.push({
209
+ bucket,
210
+ key: category,
211
+ label: DEVTOOLS_AI_ERROR_LABELS[category],
212
+ value
213
+ });
214
+ }
215
+ }
216
+ return buildSeries(range, entries);
217
+ }
218
+ function groupRows(rows, keyOf) {
219
+ const groups = /* @__PURE__ */ new Map();
220
+ for (const row of rows) {
221
+ const key = keyOf(row);
222
+ const group = groups.get(key);
223
+ if (group) group.push(row);
224
+ else groups.set(key, [row]);
225
+ }
226
+ return groups;
227
+ }
228
+ const byKey = (a, b) => a < b ? -1 : a > b ? 1 : 0;
229
+ /** Top rows by estimated cost (by runs when nothing was priced), at most `limit`. */
230
+ function breakdown(rows, by, limit) {
231
+ const items = [...groupRows(rows, (row) => by === "agent" ? row.agent : modelKey(row)).entries()].map(([key, group]) => ({
232
+ key,
233
+ group,
234
+ totals: totalsOf(group)
235
+ }));
236
+ const totalCost = items.reduce((sum, item) => sum + item.totals.cost.estimatedUsd, 0);
237
+ const totalRuns = items.reduce((sum, item) => sum + item.totals.runs, 0);
238
+ const byCost = totalCost > 0;
239
+ items.sort((a, b) => (byCost ? b.totals.cost.estimatedUsd - a.totals.cost.estimatedUsd : 0) || b.totals.runs - a.totals.runs || byKey(a.key, b.key));
240
+ return items.slice(0, limit).map(({ key, group, totals }) => ({
241
+ key,
242
+ label: key,
243
+ provider: by === "model" ? group[0]?.provider ?? null : null,
244
+ totals,
245
+ share: byCost ? totals.cost.estimatedUsd / totalCost : totalRuns > 0 ? totals.runs / totalRuns : 0
246
+ }));
247
+ }
248
+ function pricingOf(totals) {
249
+ const { pricedRuns, unpricedRuns } = totals.cost;
250
+ if (pricedRuns === 0 && unpricedRuns === 0) return "no-tokens";
251
+ if (unpricedRuns === 0) return "set";
252
+ return pricedRuns === 0 ? "missing" : "partial";
253
+ }
254
+ /** One row per `provider/model`, most runs first. */
255
+ function modelRows(rows) {
256
+ const result = [];
257
+ for (const [key, group] of groupRows(rows, modelKey)) {
258
+ const totals = totalsOf(group);
259
+ const runsByAgent = /* @__PURE__ */ new Map();
260
+ let lastSeenAt = 0;
261
+ for (const row of group) {
262
+ runsByAgent.set(row.agent, (runsByAgent.get(row.agent) ?? 0) + row.runs);
263
+ if (row.runs > 0 && row.hour > lastSeenAt) lastSeenAt = row.hour;
264
+ }
265
+ const first = group[0];
266
+ result.push({
267
+ key,
268
+ model: first?.model ?? "",
269
+ provider: first?.provider ?? "",
270
+ totals,
271
+ pricing: pricingOf(totals),
272
+ costPerRunUsd: totals.cost.pricedRuns > 0 ? totals.cost.estimatedUsd / totals.cost.pricedRuns : null,
273
+ fallbackRate: totals.runs > 0 ? totals.fallbackRuns / totals.runs : 0,
274
+ agents: [...runsByAgent.entries()].sort((a, b) => b[1] - a[1] || byKey(a[0], b[0])).slice(0, 5).map(([agent]) => agent),
275
+ lastSeenAt
276
+ });
277
+ }
278
+ return result.sort((a, b) => b.totals.runs - a.totals.runs || byKey(a.key, b.key));
279
+ }
280
+ function countErrors(rows, category) {
281
+ return rows.reduce((sum, row) => sum + row.errors[category], 0);
282
+ }
283
+ function topCounts(rows, category, keyOf) {
284
+ const counts = /* @__PURE__ */ new Map();
285
+ for (const row of rows) {
286
+ const count = row.errors[category];
287
+ if (count > 0) counts.set(keyOf(row), (counts.get(keyOf(row)) ?? 0) + count);
288
+ }
289
+ return [...counts.entries()].sort((a, b) => b[1] - a[1] || byKey(a[0], b[0])).slice(0, 5).map(([key, count]) => ({
290
+ key,
291
+ count
292
+ }));
293
+ }
294
+ /** Categories with at least one error, most first, with `previousCount` from `previousRows`. */
295
+ function errorGroups(rows, previousRows) {
296
+ const counted = DEVTOOLS_AI_ERROR_CATEGORIES.map((category) => ({
297
+ category,
298
+ count: countErrors(rows, category)
299
+ }));
300
+ const total = counted.reduce((sum, item) => sum + item.count, 0);
301
+ return counted.filter((item) => item.count > 0).sort((a, b) => b.count - a.count).map(({ category, count }) => ({
302
+ category,
303
+ label: DEVTOOLS_AI_ERROR_LABELS[category],
304
+ count,
305
+ share: total > 0 ? count / total : 0,
306
+ previousCount: countErrors(previousRows, category),
307
+ byModel: topCounts(rows, category, modelKey),
308
+ byAgent: topCounts(rows, category, (row) => row.agent)
309
+ }));
310
+ }
311
+ /** The distinct agents, models and providers, sorted. */
312
+ function filterOptions(rows) {
313
+ const agents = /* @__PURE__ */ new Set();
314
+ const models = /* @__PURE__ */ new Set();
315
+ const providers = /* @__PURE__ */ new Set();
316
+ for (const row of rows) {
317
+ agents.add(row.agent);
318
+ models.add(modelKey(row));
319
+ providers.add(row.provider);
320
+ }
321
+ return {
322
+ agents: [...agents].sort(byKey),
323
+ models: [...models].sort(byKey),
324
+ providers: [...providers].sort(byKey)
325
+ };
326
+ }
327
+
328
+ //#endregion
329
+ export { breakdown, bucketOf, errorGroups, errorRateSeries, errorSeries, filterOptions, modelRows, seriesBy, tokenSeries, totalsOf };
330
+ //# sourceMappingURL=aggregate.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/reports/aggregate.ts"],"sourcesContent":["import type {\n DevtoolsAiBreakdownRow,\n DevtoolsAiErrorCategory,\n DevtoolsAiErrorGroup,\n DevtoolsAiFilterOptions,\n DevtoolsAiModelRow,\n DevtoolsAiPricingState,\n DevtoolsAiRatePoint,\n DevtoolsAiResolvedRange,\n DevtoolsAiSeriesSet,\n DevtoolsAiTotals,\n} from \"../../production/contracts\";\nimport { DEVTOOLS_AI_ERROR_CATEGORIES } from \"../../production/contracts\";\nimport { DEVTOOLS_AI_ERROR_LABELS } from \"../rollup/categories\";\nimport { addAiLatency, aiLatencyQuantile, emptyAiLatency } from \"../rollup/histogram\";\nimport type { DevtoolsAiRollupDelta } from \"../types\";\n\n/**\n * Pure folds from rollup rows (stored records plus pending deltas) to the\n * report shapes in `production/contracts.ts`. No I/O, no clock.\n */\n\nconst MAX_NAMED_SERIES = 5;\nconst OTHER_KEY = \"__other\";\n\n/** `provider/model`, the key the UI filters and colours models by. */\nfunction modelKey(row: { provider: string; model: string }): string {\n return `${row.provider}/${row.model}`;\n}\n\n/** Sums rows into totals (latency from the merged histogram). */\nexport function totalsOf(rows: readonly DevtoolsAiRollupDelta[]): DevtoolsAiTotals {\n const totals: DevtoolsAiTotals = {\n runs: 0,\n completed: 0,\n failed: 0,\n incomplete: 0,\n cancelled: 0,\n errorRate: 0,\n tokens: { input: 0, output: 0, cached: 0, cacheWrite: 0, reasoning: 0 },\n cost: { estimatedUsd: 0, pricedRuns: 0, unpricedRuns: 0, unpricedTokens: 0 },\n latency: { p50Ms: null, p95Ms: null, meanMs: null },\n fallbackRuns: 0,\n refusals: 0,\n };\n const histogram = emptyAiLatency();\n let latencyCount = 0;\n let latencySumMs = 0;\n\n for (const row of rows) {\n totals.runs += row.runs;\n totals.completed += row.completed;\n totals.failed += row.failed;\n totals.incomplete += row.incomplete;\n totals.cancelled += row.cancelled;\n totals.tokens.input += row.inputTokens;\n totals.tokens.output += row.outputTokens;\n totals.tokens.cached += row.cachedTokens;\n totals.tokens.cacheWrite += row.cacheWriteTokens;\n totals.tokens.reasoning += row.reasoningTokens;\n totals.cost.estimatedUsd += row.costUsd;\n totals.cost.pricedRuns += row.pricedRuns;\n totals.cost.unpricedRuns += row.unpricedRuns;\n totals.cost.unpricedTokens += row.unpricedTokens;\n totals.fallbackRuns += row.fallbackRuns;\n totals.refusals += row.refusals;\n addAiLatency(histogram, row.latency);\n latencyCount += row.latencyCount;\n latencySumMs += row.latencySumMs;\n }\n\n totals.errorRate = totals.runs > 0 ? (totals.failed + totals.incomplete) / totals.runs : 0;\n totals.latency = {\n p50Ms: aiLatencyQuantile(histogram, 0.5),\n p95Ms: aiLatencyQuantile(histogram, 0.95),\n meanMs: latencyCount > 0 ? latencySumMs / latencyCount : null,\n };\n\n return totals;\n}\n\n/** The bucket index of an hour inside `range` (`-1` outside). */\nexport function bucketOf(hour: number, range: DevtoolsAiResolvedRange): number {\n if (hour < range.from || hour >= range.to) return -1;\n\n return Math.floor((hour - range.from) / range.stepMs);\n}\n\n/** Bucket starts of a range, oldest first. */\nfunction bucketStarts(range: DevtoolsAiResolvedRange): number[] {\n const count = Math.max(0, Math.ceil((range.to - range.from) / range.stepMs));\n\n return Array.from({ length: count }, (_, index) => range.from + index * range.stepMs);\n}\n\ntype SeriesEntry = { bucket: number; key: string; label: string; value: number };\n\n/** Top five keys by sum become series, the rest are summed into `__other`. */\nfunction buildSeries(range: DevtoolsAiResolvedRange, entries: SeriesEntry[]): DevtoolsAiSeriesSet {\n const buckets = bucketStarts(range);\n const byKey = new Map<string, { label: string; sum: number; values: number[] }>();\n\n for (const entry of entries) {\n if (entry.bucket < 0 || entry.bucket >= buckets.length) continue;\n\n let item = byKey.get(entry.key);\n\n if (!item) {\n item = { label: entry.label, sum: 0, values: new Array<number>(buckets.length).fill(0) };\n byKey.set(entry.key, item);\n }\n\n item.values[entry.bucket] = (item.values[entry.bucket] ?? 0) + entry.value;\n item.sum += entry.value;\n }\n\n const ranked = [...byKey.entries()].sort(\n (a, b) => b[1].sum - a[1].sum || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0),\n );\n const series: DevtoolsAiSeriesSet[\"series\"] = ranked\n .slice(0, MAX_NAMED_SERIES)\n .map(([key, item]) => ({ key, label: item.label, values: item.values, other: false }));\n const rest = ranked.slice(MAX_NAMED_SERIES);\n\n if (rest.length > 0) {\n const values = new Array<number>(buckets.length).fill(0);\n\n for (const [, item] of rest) {\n item.values.forEach((value, index) => {\n values[index] = (values[index] ?? 0) + value;\n });\n }\n\n series.push({ key: OTHER_KEY, label: \"Other\", values, other: true });\n }\n\n return { buckets, series };\n}\n\n/**\n * A stacked series set: `value(row)` per bucket, grouped by `keyOf(row)`; the\n * five keys with the largest sum are named, the rest summed into `other`\n * (key `__other`, label \"Other\"). Buckets with no rows are 0.\n */\nexport function seriesBy(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n keyOf: (row: DevtoolsAiRollupDelta) => string,\n labelOf: (key: string) => string,\n value: (row: DevtoolsAiRollupDelta) => number,\n): DevtoolsAiSeriesSet {\n return buildSeries(\n range,\n rows.map((row) => {\n const key = keyOf(row);\n\n return { bucket: bucketOf(row.hour, range), key, label: labelOf(key), value: value(row) };\n }),\n );\n}\n\n/** Tokens per bucket: `uncached` (input − cached), `cached`, `output`. */\nexport function tokenSeries(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n): DevtoolsAiSeriesSet {\n const buckets = bucketStarts(range);\n const uncached = new Array<number>(buckets.length).fill(0);\n const cached = new Array<number>(buckets.length).fill(0);\n const output = new Array<number>(buckets.length).fill(0);\n\n for (const row of rows) {\n const bucket = bucketOf(row.hour, range);\n\n if (bucket < 0 || bucket >= buckets.length) continue;\n\n uncached[bucket] = (uncached[bucket] ?? 0) + Math.max(0, row.inputTokens - row.cachedTokens);\n cached[bucket] = (cached[bucket] ?? 0) + row.cachedTokens;\n output[bucket] = (output[bucket] ?? 0) + row.outputTokens;\n }\n\n return {\n buckets,\n series: [\n { key: \"uncached\", label: \"Uncached input\", values: uncached, other: false },\n { key: \"cached\", label: \"Cached input\", values: cached, other: false },\n { key: \"output\", label: \"Output\", values: output, other: false },\n ],\n };\n}\n\n/** The error rate per bucket; `rate: null` where a bucket has no runs. */\nexport function errorRateSeries(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n): DevtoolsAiRatePoint[] {\n const points = bucketStarts(range).map((at) => ({\n at,\n runs: 0,\n errors: 0,\n rate: null as number | null,\n }));\n\n for (const row of rows) {\n const point = points[bucketOf(row.hour, range)];\n\n if (!point) continue;\n\n point.runs += row.runs;\n point.errors += row.failed + row.incomplete;\n }\n\n for (const point of points) point.rate = point.runs > 0 ? point.errors / point.runs : null;\n\n return points;\n}\n\n/** Failed runs per bucket by category (top five plus Other). */\nexport function errorSeries(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n): DevtoolsAiSeriesSet {\n const entries: SeriesEntry[] = [];\n\n for (const row of rows) {\n const bucket = bucketOf(row.hour, range);\n\n for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) {\n const value = row.errors[category];\n\n if (value > 0) {\n entries.push({ bucket, key: category, label: DEVTOOLS_AI_ERROR_LABELS[category], value });\n }\n }\n }\n\n return buildSeries(range, entries);\n}\n\nfunction groupRows(\n rows: readonly DevtoolsAiRollupDelta[],\n keyOf: (row: DevtoolsAiRollupDelta) => string,\n): Map<string, DevtoolsAiRollupDelta[]> {\n const groups = new Map<string, DevtoolsAiRollupDelta[]>();\n\n for (const row of rows) {\n const key = keyOf(row);\n const group = groups.get(key);\n\n if (group) group.push(row);\n else groups.set(key, [row]);\n }\n\n return groups;\n}\n\nconst byKey = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/** Top rows by estimated cost (by runs when nothing was priced), at most `limit`. */\nexport function breakdown(\n rows: readonly DevtoolsAiRollupDelta[],\n by: \"agent\" | \"model\",\n limit: number,\n): DevtoolsAiBreakdownRow[] {\n const groups = groupRows(rows, (row) => (by === \"agent\" ? row.agent : modelKey(row)));\n const items = [...groups.entries()].map(([key, group]) => ({\n key,\n group,\n totals: totalsOf(group),\n }));\n const totalCost = items.reduce((sum, item) => sum + item.totals.cost.estimatedUsd, 0);\n const totalRuns = items.reduce((sum, item) => sum + item.totals.runs, 0);\n const byCost = totalCost > 0;\n\n items.sort(\n (a, b) =>\n (byCost ? b.totals.cost.estimatedUsd - a.totals.cost.estimatedUsd : 0) ||\n b.totals.runs - a.totals.runs ||\n byKey(a.key, b.key),\n );\n\n return items.slice(0, limit).map(({ key, group, totals }) => ({\n key,\n label: key,\n provider: by === \"model\" ? (group[0]?.provider ?? null) : null,\n totals,\n share: byCost\n ? totals.cost.estimatedUsd / totalCost\n : totalRuns > 0\n ? totals.runs / totalRuns\n : 0,\n }));\n}\n\nfunction pricingOf(totals: DevtoolsAiTotals): DevtoolsAiPricingState {\n const { pricedRuns, unpricedRuns } = totals.cost;\n\n // No run used tokens (all failed before the first call): nothing to price yet.\n if (pricedRuns === 0 && unpricedRuns === 0) return \"no-tokens\";\n\n if (unpricedRuns === 0) return \"set\";\n\n return pricedRuns === 0 ? \"missing\" : \"partial\";\n}\n\n/** One row per `provider/model`, most runs first. */\nexport function modelRows(rows: readonly DevtoolsAiRollupDelta[]): DevtoolsAiModelRow[] {\n const result: DevtoolsAiModelRow[] = [];\n\n for (const [key, group] of groupRows(rows, modelKey)) {\n const totals = totalsOf(group);\n const runsByAgent = new Map<string, number>();\n let lastSeenAt = 0;\n\n for (const row of group) {\n runsByAgent.set(row.agent, (runsByAgent.get(row.agent) ?? 0) + row.runs);\n\n if (row.runs > 0 && row.hour > lastSeenAt) lastSeenAt = row.hour;\n }\n\n const first = group[0];\n\n result.push({\n key,\n model: first?.model ?? \"\",\n provider: first?.provider ?? \"\",\n totals,\n pricing: pricingOf(totals),\n costPerRunUsd:\n totals.cost.pricedRuns > 0 ? totals.cost.estimatedUsd / totals.cost.pricedRuns : null,\n fallbackRate: totals.runs > 0 ? totals.fallbackRuns / totals.runs : 0,\n agents: [...runsByAgent.entries()]\n .sort((a, b) => b[1] - a[1] || byKey(a[0], b[0]))\n .slice(0, 5)\n .map(([agent]) => agent),\n lastSeenAt,\n });\n }\n\n return result.sort((a, b) => b.totals.runs - a.totals.runs || byKey(a.key, b.key));\n}\n\nfunction countErrors(\n rows: readonly DevtoolsAiRollupDelta[],\n category: DevtoolsAiErrorCategory,\n): number {\n return rows.reduce((sum, row) => sum + row.errors[category], 0);\n}\n\nfunction topCounts(\n rows: readonly DevtoolsAiRollupDelta[],\n category: DevtoolsAiErrorCategory,\n keyOf: (row: DevtoolsAiRollupDelta) => string,\n): { key: string; count: number }[] {\n const counts = new Map<string, number>();\n\n for (const row of rows) {\n const count = row.errors[category];\n\n if (count > 0) counts.set(keyOf(row), (counts.get(keyOf(row)) ?? 0) + count);\n }\n\n return [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || byKey(a[0], b[0]))\n .slice(0, 5)\n .map(([key, count]) => ({ key, count }));\n}\n\n/** Categories with at least one error, most first, with `previousCount` from `previousRows`. */\nexport function errorGroups(\n rows: readonly DevtoolsAiRollupDelta[],\n previousRows: readonly DevtoolsAiRollupDelta[],\n): DevtoolsAiErrorGroup[] {\n const counted = DEVTOOLS_AI_ERROR_CATEGORIES.map((category) => ({\n category,\n count: countErrors(rows, category),\n }));\n const total = counted.reduce((sum, item) => sum + item.count, 0);\n\n return counted\n .filter((item) => item.count > 0)\n .sort((a, b) => b.count - a.count)\n .map(({ category, count }) => ({\n category,\n label: DEVTOOLS_AI_ERROR_LABELS[category],\n count,\n share: total > 0 ? count / total : 0,\n previousCount: countErrors(previousRows, category),\n byModel: topCounts(rows, category, modelKey),\n byAgent: topCounts(rows, category, (row) => row.agent),\n }));\n}\n\n/** The distinct agents, models and providers, sorted. */\nexport function filterOptions(rows: readonly DevtoolsAiRollupDelta[]): DevtoolsAiFilterOptions {\n const agents = new Set<string>();\n const models = new Set<string>();\n const providers = new Set<string>();\n\n for (const row of rows) {\n agents.add(row.agent);\n models.add(modelKey(row));\n providers.add(row.provider);\n }\n\n return {\n agents: [...agents].sort(byKey),\n models: [...models].sort(byKey),\n providers: [...providers].sort(byKey),\n };\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,mBAAmB;AACzB,MAAM,YAAY;;AAGlB,SAAS,SAAS,KAAkD;CAClE,OAAO,GAAG,IAAI,SAAS,GAAG,IAAI;AAChC;;AAGA,SAAg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K,YAAY;EAAE;EAAK;CAAM,EAAE;AAC3C;;AAGA,SAAgB,YACd,MACA,cACwB;CACxB,MAAM,UAAU,6BAA6B,KAAK,cAAc;EAC9D;EACA,OAAO,YAAY,MAAM,QAAQ;CACnC,EAAE;CACF,MAAM,QAAQ,QAAQ,QAAQ,KAAK,SAAS,MAAM,KAAK,OAAO,CAAC;CAE/D,OAAO,QACJ,QAAQ,SAAS,KAAK,QAAQ,CAAC,CAAC,CAChC,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,CACjC,KAAK,EAAE,UAAU,aAAa;EAC7B;EACA,OAAO,yBAAyB;EAChC;EACA,OAAO,QAAQ,IAAI,QAAQ,QAAQ;EACnC,eAAe,YAAY,cAAc,QAAQ;EACjD,SAAS,UAAU,MAAM,UAAU,QAAQ;EAC3C,SAAS,UAAU,MAAM,WAAW,QAAQ,IAAI,KAAK;CACvD,EAAE;AACN;;AAGA,SAAgB,cAAc,MAAiE;CAC7F,MAAM,yBAAS,IAAI,IAAY;CAC/B,MAAM,yBAAS,IAAI,IAAY;CAC/B,MAAM,4BAAY,IAAI,IAAY;CAElC,KAAK,MAAM,OAAO,MAAM;EACtB,OAAO,IAAI,IAAI,KAAK;EACpB,OAAO,IAAI,SAAS,GAAG,CAAC;EACxB,UAAU,IAAI,IAAI,QAAQ;CAC5B;CAEA,OAAO;EACL,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK,KAAK;EAC9B,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK,KAAK;EAC9B,WAAW,CAAC,GAAG,SAAS,CAAC,CAAC,KAAK,KAAK;CACtC;AACF"}
@@ -0,0 +1,108 @@
1
+ import { DevtoolsApiError, createErrorRef } from "../../production/errors.mjs";
2
+
3
+ //#region ../../packages/devtools/src/ai/reports/evaluate.ts
4
+ const MAX_PROMPTS = 50;
5
+ const MAX_RUNS_SCANNED = 300;
6
+ const MAX_SYSTEM_PROMPT = 1e5;
7
+ const MAX_INSTRUCTIONS = 4e3;
8
+ const PREVIEW_LENGTH = 200;
9
+ function judgeLabel(model) {
10
+ return typeof model.provider === "string" && typeof model.name === "string" ? `${model.provider}/${model.name}` : model.name ?? "custom model";
11
+ }
12
+ /** Builds the evaluator over the agent traces and Panoptic's evaluate helpers (loaded lazily). */
13
+ function createAiEvaluator(input) {
14
+ const load = input.load ?? (() => import("@warlock.js/ai-panoptic"));
15
+ /** Panoptic's evaluate helpers, or `undefined` when Panoptic (or its evaluate support) is not there. */
16
+ async function panoptic() {
17
+ try {
18
+ const module = await load("@warlock.js/ai-panoptic");
19
+ return typeof module.getEvaluateConfig === "function" && typeof module.evaluateSystemPrompt === "function" ? module : void 0;
20
+ } catch {
21
+ return;
22
+ }
23
+ }
24
+ const unavailable = () => new DevtoolsApiError("ai.evaluate-unavailable");
25
+ return {
26
+ async view() {
27
+ const module = await panoptic();
28
+ let config;
29
+ try {
30
+ config = module?.getEvaluateConfig();
31
+ } catch {
32
+ config = void 0;
33
+ }
34
+ const byHash = /* @__PURE__ */ new Map();
35
+ const runs = input.agentTraces.list().sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || 0).slice(0, MAX_RUNS_SCANNED);
36
+ for (const run of runs) {
37
+ const prompt = input.agentTraces.get(run.runId)?.systemPrompt;
38
+ if (!prompt || typeof prompt.text !== "string" || prompt.text === "") continue;
39
+ const known = byHash.get(prompt.hash);
40
+ if (known) {
41
+ if (!known.agents.includes(run.agent)) known.agents.push(run.agent);
42
+ } else byHash.set(prompt.hash, {
43
+ agents: [run.agent],
44
+ runId: run.runId,
45
+ startedAt: run.startedAt,
46
+ text: prompt.text
47
+ });
48
+ }
49
+ return {
50
+ available: true,
51
+ configured: config !== void 0,
52
+ judge: config === void 0 ? null : typeof config.model === "function" ? "custom model" : judgeLabel(config.model),
53
+ instructions: config?.instructions ?? "",
54
+ prompts: [...byHash.entries()].slice(0, MAX_PROMPTS).map(([hash, item]) => ({
55
+ hash,
56
+ agents: item.agents,
57
+ runId: item.runId,
58
+ lastSeenAt: item.startedAt,
59
+ preview: item.text.slice(0, PREVIEW_LENGTH),
60
+ length: item.text.length
61
+ }))
62
+ };
63
+ },
64
+ async evaluate(request) {
65
+ const { runId, systemPrompt, instructions } = request;
66
+ if (runId === void 0 === (systemPrompt === void 0)) throw new DevtoolsApiError("input.invalid");
67
+ if (runId !== void 0 && (typeof runId !== "string" || runId === "") || systemPrompt !== void 0 && (typeof systemPrompt !== "string" || systemPrompt.trim() === "" || systemPrompt.length > MAX_SYSTEM_PROMPT) || instructions !== void 0 && (typeof instructions !== "string" || instructions.length > MAX_INSTRUCTIONS)) throw new DevtoolsApiError("input.invalid");
68
+ const module = await panoptic();
69
+ let config;
70
+ try {
71
+ config = module?.getEvaluateConfig();
72
+ } catch {
73
+ config = void 0;
74
+ }
75
+ if (!module || !config) throw unavailable();
76
+ let text = systemPrompt;
77
+ if (runId !== void 0) {
78
+ text = input.agentTraces.get(runId)?.systemPrompt?.text;
79
+ if (typeof text !== "string" || text === "") throw new DevtoolsApiError("ai.prompt-not-found");
80
+ }
81
+ const started = Date.now();
82
+ try {
83
+ const model = typeof config.model === "function" ? await config.model() : config.model;
84
+ const verdict = await module.evaluateSystemPrompt(text, {
85
+ ...config,
86
+ model
87
+ }, instructions);
88
+ return {
89
+ score: typeof verdict.score === "number" ? verdict.score : null,
90
+ issues: Array.isArray(verdict.issues) ? verdict.issues.map(String) : [],
91
+ judge: judgeLabel(model),
92
+ durationMs: Date.now() - started
93
+ };
94
+ } catch (error) {
95
+ const ref = createErrorRef();
96
+ input.warn?.(`Devtools evaluate error ${ref}: ${error instanceof Error ? error.message : String(error)}`);
97
+ throw new DevtoolsApiError("ai.evaluate-failed", {
98
+ ref,
99
+ cause: error
100
+ });
101
+ }
102
+ }
103
+ };
104
+ }
105
+
106
+ //#endregion
107
+ export { createAiEvaluator };
108
+ //# sourceMappingURL=evaluate.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evaluate.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/reports/evaluate.ts"],"sourcesContent":["import type {\n DevtoolsAiEvaluateRequest,\n DevtoolsAiEvaluateResult,\n DevtoolsAiEvaluateView,\n} from \"../../production/contracts\";\nimport { createErrorRef, DevtoolsApiError } from \"../../production/errors\";\nimport type { DevtoolsAgentTraceSource } from \"../../sources/agent-trace-source\";\n\nconst MAX_PROMPTS = 50;\nconst MAX_RUNS_SCANNED = 300;\nconst MAX_SYSTEM_PROMPT = 100_000;\nconst MAX_INSTRUCTIONS = 4000;\nconst PREVIEW_LENGTH = 200;\n\ntype EvaluateModule = {\n getEvaluateConfig?: () => EvaluateConfigLike | undefined;\n evaluateSystemPrompt?: (\n systemPrompt: string,\n config: EvaluateConfigLike,\n instructions?: string,\n ) => Promise<{ score?: number; issues?: string[] }>;\n};\n\ntype ModelLike = { name?: string; provider?: string };\n\ntype EvaluateConfigLike = {\n model: ModelLike | (() => ModelLike | Promise<ModelLike>);\n instructions?: string;\n};\n\n/** What the Evaluate routes use; injected so specs need no model. */\nexport type DevtoolsAiEvaluator = {\n /** The page data: whether a judge is configured and the recent distinct system prompts. */\n view(): Promise<Extract<DevtoolsAiEvaluateView, { available: true }>>;\n /**\n * Grades a prompt with Panoptic's `evaluateSystemPrompt`. Throws\n * `DevtoolsApiError` `input.invalid` (both or neither of runId/systemPrompt,\n * sizes), `ai.evaluate-unavailable` (no judge configured),\n * `ai.prompt-not-found` (run gone or its text not kept) or\n * `ai.evaluate-failed` (the judge threw; logged with the reference).\n */\n evaluate(request: DevtoolsAiEvaluateRequest): Promise<DevtoolsAiEvaluateResult>;\n};\n\nfunction judgeLabel(model: ModelLike): string {\n return typeof model.provider === \"string\" && typeof model.name === \"string\"\n ? `${model.provider}/${model.name}`\n : (model.name ?? \"custom model\");\n}\n\n/** Builds the evaluator over the agent traces and Panoptic's evaluate helpers (loaded lazily). */\nexport function createAiEvaluator(input: {\n agentTraces: DevtoolsAgentTraceSource;\n load?: (name: string) => Promise<unknown>;\n warn?: (message: string) => void;\n}): DevtoolsAiEvaluator {\n const load = input.load ?? (() => import(\"@warlock.js/ai-panoptic\"));\n\n /** Panoptic's evaluate helpers, or `undefined` when Panoptic (or its evaluate support) is not there. */\n async function panoptic(): Promise<(EvaluateModule & Required<EvaluateModule>) | undefined> {\n try {\n const module = (await load(\"@warlock.js/ai-panoptic\")) as EvaluateModule;\n\n return typeof module.getEvaluateConfig === \"function\" &&\n typeof module.evaluateSystemPrompt === \"function\"\n ? (module as EvaluateModule & Required<EvaluateModule>)\n : undefined;\n } catch {\n return undefined;\n }\n }\n\n const unavailable = (): DevtoolsApiError => new DevtoolsApiError(\"ai.evaluate-unavailable\");\n\n return {\n async view() {\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n const byHash = new Map<\n string,\n { agents: string[]; runId: string; startedAt: string; text: string }\n >();\n const runs = input.agentTraces\n .list()\n .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || 0)\n .slice(0, MAX_RUNS_SCANNED);\n\n for (const run of runs) {\n const prompt = input.agentTraces.get(run.runId)?.systemPrompt;\n\n if (!prompt || typeof prompt.text !== \"string\" || prompt.text === \"\") continue;\n\n const known = byHash.get(prompt.hash);\n\n if (known) {\n if (!known.agents.includes(run.agent)) known.agents.push(run.agent);\n } else {\n byHash.set(prompt.hash, {\n agents: [run.agent],\n runId: run.runId,\n startedAt: run.startedAt,\n text: prompt.text,\n });\n }\n }\n\n return {\n available: true as const,\n configured: config !== undefined,\n judge:\n config === undefined\n ? null\n : typeof config.model === \"function\"\n ? \"custom model\"\n : judgeLabel(config.model),\n instructions: config?.instructions ?? \"\",\n prompts: [...byHash.entries()].slice(0, MAX_PROMPTS).map(([hash, item]) => ({\n hash,\n agents: item.agents,\n runId: item.runId,\n lastSeenAt: item.startedAt,\n preview: item.text.slice(0, PREVIEW_LENGTH),\n length: item.text.length,\n })),\n };\n },\n\n async evaluate(request) {\n const { runId, systemPrompt, instructions } = request;\n\n if ((runId === undefined) === (systemPrompt === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (\n (runId !== undefined && (typeof runId !== \"string\" || runId === \"\")) ||\n (systemPrompt !== undefined &&\n (typeof systemPrompt !== \"string\" ||\n systemPrompt.trim() === \"\" ||\n systemPrompt.length > MAX_SYSTEM_PROMPT)) ||\n (instructions !== undefined &&\n (typeof instructions !== \"string\" || instructions.length > MAX_INSTRUCTIONS))\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n if (!module || !config) throw unavailable();\n\n let text = systemPrompt;\n\n if (runId !== undefined) {\n text = input.agentTraces.get(runId)?.systemPrompt?.text;\n\n if (typeof text !== \"string\" || text === \"\")\n throw new DevtoolsApiError(\"ai.prompt-not-found\");\n }\n\n const started = Date.now();\n\n try {\n const model = typeof config.model === \"function\" ? await config.model() : config.model;\n const verdict = await module.evaluateSystemPrompt(\n text as string,\n { ...config, model },\n instructions,\n );\n\n return {\n score: typeof verdict.score === \"number\" ? verdict.score : null,\n issues: Array.isArray(verdict.issues) ? verdict.issues.map(String) : [],\n judge: judgeLabel(model),\n durationMs: Date.now() - started,\n };\n } catch (error) {\n const ref = createErrorRef();\n\n input.warn?.(\n `Devtools evaluate error ${ref}: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n throw new DevtoolsApiError(\"ai.evaluate-failed\", { ref, cause: error });\n }\n },\n };\n}\n"],"mappings":";;;AAQA,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAgCvB,SAAS,WAAW,OAA0B;CAC5C,OAAO,OAAO,MAAM,aAAa,YAAY,OAAO,MAAM,SAAS,WAC/D,GAAG,MAAM,SAAS,GAAG,MAAM,S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