@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,67 @@
1
+ import { DEVTOOLS_AI_ERROR_CATEGORIES } from "../../production/contracts.mjs";
2
+
3
+ //#region ../../packages/devtools/src/ai/rollup/categories.ts
4
+ /** Labels the Errors page shows, by category. */
5
+ const DEVTOOLS_AI_ERROR_LABELS = {
6
+ "rate-limit": "Rate limit",
7
+ timeout: "Timeout",
8
+ refusal: "Refusal",
9
+ provider: "Provider error",
10
+ budget: "Budget",
11
+ tool: "Tool failed",
12
+ schema: "Invalid output",
13
+ incomplete: "Incomplete",
14
+ other: "Other"
15
+ };
16
+ /** Error counts with every category at 0. */
17
+ function emptyErrorCounts() {
18
+ const counts = {};
19
+ for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) counts[category] = 0;
20
+ return counts;
21
+ }
22
+ const CODE_CATEGORIES = {
23
+ PROVIDER_RATE_LIMIT: "rate-limit",
24
+ PROVIDER_QUOTA_EXCEEDED: "rate-limit",
25
+ PROVIDER_OVERLOADED: "rate-limit",
26
+ PROVIDER_TIMEOUT: "timeout",
27
+ CONTENT_FILTER: "refusal",
28
+ GUARDRAIL_VIOLATION: "refusal",
29
+ PROVIDER_ERROR: "provider",
30
+ PROVIDER_INVALID_REQUEST: "provider",
31
+ PROVIDER_AUTH: "provider",
32
+ CONTEXT_LENGTH_EXCEEDED: "provider",
33
+ PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH: "provider",
34
+ BUDGET_EXCEEDED: "budget",
35
+ TOOL_EXEC_FAILED: "tool",
36
+ SCHEMA_VALIDATION_FAILED: "schema",
37
+ AGENT_INCOMPLETE: "incomplete",
38
+ AGENT_MAX_TRIPS: "incomplete",
39
+ AgentIncompleteError: "incomplete"
40
+ };
41
+ /**
42
+ * The category of a failed or stopped agent span, from its status and error
43
+ * type (an `AIErrorCode` such as `PROVIDER_RATE_LIMIT`, or an error name):
44
+ *
45
+ * - `rate-limit`: PROVIDER_RATE_LIMIT, PROVIDER_QUOTA_EXCEEDED, PROVIDER_OVERLOADED
46
+ * - `timeout`: PROVIDER_TIMEOUT, or a name/type containing "Timeout"
47
+ * - `refusal`: CONTENT_FILTER, GUARDRAIL_VIOLATION
48
+ * - `provider`: PROVIDER_ERROR, PROVIDER_INVALID_REQUEST, PROVIDER_AUTH,
49
+ * CONTEXT_LENGTH_EXCEEDED, PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH
50
+ * - `budget`: BUDGET_EXCEEDED
51
+ * - `tool`: TOOL_EXEC_FAILED
52
+ * - `schema`: SCHEMA_VALIDATION_FAILED
53
+ * - `incomplete`: status `incomplete` or `max-iterations`, AGENT_INCOMPLETE,
54
+ * AGENT_MAX_TRIPS, AgentIncompleteError
55
+ * - `other`: anything else
56
+ */
57
+ function classifyAiError(status, errorType) {
58
+ if (status === "incomplete" || status === "max-iterations") return "incomplete";
59
+ if (!errorType) return "other";
60
+ const known = CODE_CATEGORIES[errorType];
61
+ if (known) return known;
62
+ return /timeout/i.test(errorType) ? "timeout" : "other";
63
+ }
64
+
65
+ //#endregion
66
+ export { DEVTOOLS_AI_ERROR_LABELS, classifyAiError, emptyErrorCounts };
67
+ //# sourceMappingURL=categories.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"categories.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/categories.ts"],"sourcesContent":["import {\n DEVTOOLS_AI_ERROR_CATEGORIES,\n type DevtoolsAiErrorCategory,\n} from \"../../production/contracts\";\nimport type { DevtoolsAiErrorCounts } from \"../types\";\n\n/** Labels the Errors page shows, by category. */\nexport const DEVTOOLS_AI_ERROR_LABELS: Readonly<Record<DevtoolsAiErrorCategory, string>> = {\n \"rate-limit\": \"Rate limit\",\n timeout: \"Timeout\",\n refusal: \"Refusal\",\n provider: \"Provider error\",\n budget: \"Budget\",\n tool: \"Tool failed\",\n schema: \"Invalid output\",\n incomplete: \"Incomplete\",\n other: \"Other\",\n};\n\n/** Error counts with every category at 0. */\nexport function emptyErrorCounts(): DevtoolsAiErrorCounts {\n const counts = {} as DevtoolsAiErrorCounts;\n\n for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) counts[category] = 0;\n\n return counts;\n}\n\nconst CODE_CATEGORIES: Readonly<Record<string, DevtoolsAiErrorCategory>> = {\n PROVIDER_RATE_LIMIT: \"rate-limit\",\n PROVIDER_QUOTA_EXCEEDED: \"rate-limit\",\n PROVIDER_OVERLOADED: \"rate-limit\",\n PROVIDER_TIMEOUT: \"timeout\",\n CONTENT_FILTER: \"refusal\",\n GUARDRAIL_VIOLATION: \"refusal\",\n PROVIDER_ERROR: \"provider\",\n PROVIDER_INVALID_REQUEST: \"provider\",\n PROVIDER_AUTH: \"provider\",\n CONTEXT_LENGTH_EXCEEDED: \"provider\",\n PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH: \"provider\",\n BUDGET_EXCEEDED: \"budget\",\n TOOL_EXEC_FAILED: \"tool\",\n SCHEMA_VALIDATION_FAILED: \"schema\",\n AGENT_INCOMPLETE: \"incomplete\",\n AGENT_MAX_TRIPS: \"incomplete\",\n AgentIncompleteError: \"incomplete\",\n};\n\n/**\n * The category of a failed or stopped agent span, from its status and error\n * type (an `AIErrorCode` such as `PROVIDER_RATE_LIMIT`, or an error name):\n *\n * - `rate-limit`: PROVIDER_RATE_LIMIT, PROVIDER_QUOTA_EXCEEDED, PROVIDER_OVERLOADED\n * - `timeout`: PROVIDER_TIMEOUT, or a name/type containing \"Timeout\"\n * - `refusal`: CONTENT_FILTER, GUARDRAIL_VIOLATION\n * - `provider`: PROVIDER_ERROR, PROVIDER_INVALID_REQUEST, PROVIDER_AUTH,\n * CONTEXT_LENGTH_EXCEEDED, PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH\n * - `budget`: BUDGET_EXCEEDED\n * - `tool`: TOOL_EXEC_FAILED\n * - `schema`: SCHEMA_VALIDATION_FAILED\n * - `incomplete`: status `incomplete` or `max-iterations`, AGENT_INCOMPLETE,\n * AGENT_MAX_TRIPS, AgentIncompleteError\n * - `other`: anything else\n */\nexport function classifyAiError(\n status: string,\n errorType: string | undefined,\n): DevtoolsAiErrorCategory {\n if (status === \"incomplete\" || status === \"max-iterations\") return \"incomplete\";\n\n if (!errorType) return \"other\";\n\n const known = CODE_CATEGORIES[errorType];\n\n if (known) return known;\n\n return /timeout/i.test(errorType) ? \"timeout\" : \"other\";\n}\n"],"mappings":";;;;AAOA,MAAa,2BAA8E;CACzF,cAAc;CACd,SAAS;CACT,SAAS;CACT,UAAU;CACV,QAAQ;CACR,MAAM;CACN,QAAQ;CACR,YAAY;CACZ,OAAO;AACT;;AAGA,SAAgB,mBAA0C;CACxD,MAAM,SAAS,CAAC;CAEhB,KAAK,MAAM,YAAY,8BAA8B,OAAO,YAAY;CAExE,OAAO;AACT;AAEA,MAAM,kBAAqE;CACzE,qBAAqB;CACrB,yBAAyB;CACzB,qBAAqB;CACrB,kBAAkB;CAClB,gBAAgB;CAChB,qBAAqB;CACrB,gBAAgB;CAChB,0BAA0B;CAC1B,eAAe;CACf,yBAAyB;CACzB,0CAA0C;CAC1C,iBAAiB;CACjB,kBAAkB;CAClB,0BAA0B;CAC1B,kBAAkB;CAClB,iBAAiB;CACjB,sBAAsB;AACxB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,gBACd,QACA,WACyB;CACzB,IAAI,WAAW,gBAAgB,WAAW,kBAAkB,OAAO;CAEnE,IAAI,CAAC,WAAW,OAAO;CAEvB,MAAM,QAAQ,gBAAgB;CAE9B,IAAI,OAAO,OAAO;CAElB,OAAO,WAAW,KAAK,SAAS,IAAI,YAAY;AAClD"}
@@ -0,0 +1,225 @@
1
+ import { classifyAiError, emptyErrorCounts } from "./categories.mjs";
2
+ import { addAiLatency, aiLatencyBucket, emptyAiLatency } from "./histogram.mjs";
3
+ import { createHash } from "node:crypto";
4
+
5
+ //#region ../../packages/devtools/src/ai/rollup/extract.ts
6
+ const HOUR_MS = 36e5;
7
+ const UNKNOWN = "(unknown)";
8
+ const MODEL_SPAN_TYPES = /* @__PURE__ */ new Set([
9
+ "agent",
10
+ "image",
11
+ "speech",
12
+ "transcription"
13
+ ]);
14
+ function count(value) {
15
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
16
+ }
17
+ function normalise(usage) {
18
+ const cached = count(usage?.cachedTokens);
19
+ const cacheWrite = count(usage?.cacheWriteTokens);
20
+ const input = count(usage?.input);
21
+ return {
22
+ input: usage?.inputIncludesCache === false ? input + cached + cacheWrite : input,
23
+ output: count(usage?.output),
24
+ cached,
25
+ cacheWrite,
26
+ reasoning: count(usage?.reasoningTokens)
27
+ };
28
+ }
29
+ function subtract(own, other) {
30
+ own.input = Math.max(0, own.input - other.input);
31
+ own.output = Math.max(0, own.output - other.output);
32
+ own.cached = Math.max(0, own.cached - other.cached);
33
+ own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);
34
+ own.reasoning = Math.max(0, own.reasoning - other.reasoning);
35
+ }
36
+ /** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */
37
+ function isAiModelSpan(span) {
38
+ return typeof span.attributes?.["agent.model.name"] === "string" || MODEL_SPAN_TYPES.has(span.type);
39
+ }
40
+ /** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */
41
+ function nearestModelSpans(span) {
42
+ const found = [];
43
+ for (const child of span.children ?? []) if (isAiModelSpan(child)) found.push(child);
44
+ else found.push(...nearestModelSpans(child));
45
+ return found;
46
+ }
47
+ function cut(value, max) {
48
+ if (typeof value !== "string" || value === "") return UNKNOWN;
49
+ return value.length > max ? value.slice(0, max) : value;
50
+ }
51
+ function spanCost(span, totalCost) {
52
+ return count(totalCost(span.usage));
53
+ }
54
+ /** Whether a span's usage carries pricing at all (a free model is priced at 0; no pricing is `undefined`). */
55
+ function hasPricing(span, totalCost) {
56
+ return typeof totalCost(span.usage) === "number";
57
+ }
58
+ function buildDelta(key, status, errorType, tokens, cost, pricedAtZero = false) {
59
+ const delta = emptyRollupDelta(key);
60
+ delta.runs = 1;
61
+ delta.inputTokens = tokens.input;
62
+ delta.outputTokens = tokens.output;
63
+ delta.cachedTokens = tokens.cached;
64
+ delta.cacheWriteTokens = tokens.cacheWrite;
65
+ delta.reasoningTokens = tokens.reasoning;
66
+ if (status === "completed") delta.completed = 1;
67
+ else if (status === "failed") delta.failed = 1;
68
+ else if (status === "incomplete" || status === "max-iterations") delta.incomplete = 1;
69
+ else if (status === "cancelled") delta.cancelled = 1;
70
+ if (status === "failed" || status === "incomplete" || status === "max-iterations") delta.errors[classifyAiError(status, errorType)] = 1;
71
+ if (cost > 0 || pricedAtZero && tokens.input + tokens.output > 0) {
72
+ delta.costUsd = cost;
73
+ delta.pricedRuns = 1;
74
+ } else if (tokens.input + tokens.output > 0) {
75
+ delta.unpricedRuns = 1;
76
+ delta.unpricedTokens = tokens.input + tokens.output;
77
+ }
78
+ return delta;
79
+ }
80
+ /**
81
+ * Turns one finished Panoptic trace into rollup deltas, one per
82
+ * model-bearing span (a span with an `agent.model.name` attribute, or of type
83
+ * `agent`, `image`, `speech` or `transcription`), keyed by the hour of the
84
+ * span's `endedAt`.
85
+ *
86
+ * Each span counts its OWN usage and cost: its rolled-up `usage` minus the
87
+ * usage of its nearest model-bearing descendants (an agent used as a tool is
88
+ * counted once, as itself). Root usage left after subtracting every
89
+ * model-bearing span (a custom flow with no agent span) becomes one more delta
90
+ * for the root name with model `(unknown)`, counted as one run.
91
+ *
92
+ * Per span: status maps to completed / failed / incomplete (`incomplete`,
93
+ * `max-iterations`) / cancelled; failed and incomplete runs add one error to
94
+ * `classifyAiError(status, error.type)`; tokens are normalised so `input`
95
+ * includes cache reads and writes; `costUsd` is `totalCost` of the own usage
96
+ * when it is above 0 (or the span's model is priced as free), otherwise a run
97
+ * with tokens counts in `unpricedRuns` and `unpricedTokens`; `agent.fallbackTrips > 0` adds a fallback run;
98
+ * `agent.refusals > 0` or a CONTENT_FILTER error adds a refusal; the span's
99
+ * `duration` goes into the latency histogram.
100
+ *
101
+ * Pure: no clock, no I/O. Names are cut to 200 (provider 100) characters.
102
+ */
103
+ function traceToRollupDeltas(trace, totalCost) {
104
+ const root = trace.root;
105
+ if (!root) return [];
106
+ const rootEnd = Date.parse(root.endedAt);
107
+ const fallbackEnd = Number.isNaN(rootEnd) ? Date.parse(trace.endedAt) : rootEnd;
108
+ if (Number.isNaN(fallbackEnd)) return [];
109
+ const hourOf = (span) => {
110
+ const ended = Date.parse(span.endedAt);
111
+ return Math.floor((Number.isNaN(ended) ? fallbackEnd : ended) / HOUR_MS) * HOUR_MS;
112
+ };
113
+ const deltas = [];
114
+ const topLevel = isAiModelSpan(root) ? [root] : nearestModelSpans(root);
115
+ const visit = (span) => {
116
+ const tokens = normalise(span.usage);
117
+ let cost = spanCost(span, totalCost);
118
+ const inner = nearestModelSpans(span);
119
+ for (const child of inner) {
120
+ subtract(tokens, normalise(child.usage));
121
+ cost -= spanCost(child, totalCost);
122
+ }
123
+ cost = Math.max(0, cost);
124
+ const pricedAtZero = hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));
125
+ const attributes = span.attributes ?? {};
126
+ const delta = buildDelta({
127
+ hour: hourOf(span),
128
+ ...aiRollupNamesOf(span)
129
+ }, span.status, span.error?.type, tokens, cost, pricedAtZero);
130
+ if (count(attributes["agent.fallbackTrips"]) > 0) delta.fallbackRuns = 1;
131
+ if (count(attributes["agent.refusals"]) > 0 || span.error?.type === "CONTENT_FILTER") delta.refusals = 1;
132
+ const duration = count(span.duration);
133
+ const bucket = aiLatencyBucket(duration);
134
+ delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;
135
+ delta.latencyCount = 1;
136
+ delta.latencySumMs = Math.max(0, duration);
137
+ deltas.push(delta);
138
+ for (const child of inner) visit(child);
139
+ };
140
+ for (const span of topLevel) visit(span);
141
+ const leftover = normalise(root.usage);
142
+ let leftoverCost = spanCost(root, totalCost);
143
+ for (const span of topLevel) {
144
+ subtract(leftover, normalise(span.usage));
145
+ leftoverCost -= spanCost(span, totalCost);
146
+ }
147
+ if (leftover.input + leftover.output > 0) deltas.push(buildDelta({
148
+ hour: hourOf(root),
149
+ agent: cut(root.name, 200),
150
+ model: UNKNOWN,
151
+ provider: UNKNOWN
152
+ }, root.status, root.error?.type, leftover, Math.max(0, leftoverCost)));
153
+ return deltas;
154
+ }
155
+ /** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */
156
+ function aiRollupNamesOf(span) {
157
+ return {
158
+ agent: cut(span.name, 200),
159
+ model: cut(span.attributes?.["agent.model.name"], 200),
160
+ provider: cut(span.attributes?.["agent.model.provider"], 100)
161
+ };
162
+ }
163
+ /** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */
164
+ function rollupId(key) {
165
+ return createHash("sha256").update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`).digest("hex").slice(0, 40);
166
+ }
167
+ /** A delta with every counter at zero for `key`. */
168
+ function emptyRollupDelta(key) {
169
+ return {
170
+ hour: key.hour,
171
+ agent: key.agent,
172
+ model: key.model,
173
+ provider: key.provider,
174
+ runs: 0,
175
+ completed: 0,
176
+ failed: 0,
177
+ incomplete: 0,
178
+ cancelled: 0,
179
+ inputTokens: 0,
180
+ outputTokens: 0,
181
+ cachedTokens: 0,
182
+ cacheWriteTokens: 0,
183
+ reasoningTokens: 0,
184
+ costUsd: 0,
185
+ pricedRuns: 0,
186
+ unpricedRuns: 0,
187
+ unpricedTokens: 0,
188
+ fallbackRuns: 0,
189
+ refusals: 0,
190
+ errors: emptyErrorCounts(),
191
+ latency: emptyAiLatency(),
192
+ latencyCount: 0,
193
+ latencySumMs: 0
194
+ };
195
+ }
196
+ const NUMERIC_COUNTERS = [
197
+ "runs",
198
+ "completed",
199
+ "failed",
200
+ "incomplete",
201
+ "cancelled",
202
+ "inputTokens",
203
+ "outputTokens",
204
+ "cachedTokens",
205
+ "cacheWriteTokens",
206
+ "reasoningTokens",
207
+ "costUsd",
208
+ "pricedRuns",
209
+ "unpricedRuns",
210
+ "unpricedTokens",
211
+ "fallbackRuns",
212
+ "refusals",
213
+ "latencyCount",
214
+ "latencySumMs"
215
+ ];
216
+ /** Adds the counters of `source` into `target` in place (keys must match). */
217
+ function addRollupCounters(target, source) {
218
+ for (const field of NUMERIC_COUNTERS) target[field] += source[field];
219
+ for (const category of Object.keys(target.errors)) target.errors[category] += source.errors[category] ?? 0;
220
+ addAiLatency(target.latency, source.latency);
221
+ }
222
+
223
+ //#endregion
224
+ export { addRollupCounters, aiRollupNamesOf, emptyRollupDelta, isAiModelSpan, rollupId, traceToRollupDeltas };
225
+ //# sourceMappingURL=extract.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/extract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Trace } from \"@warlock.js/ai-panoptic\";\nimport type { DevtoolsAiRollupDelta, DevtoolsAiTotalCost } from \"../types\";\nimport { classifyAiError, emptyErrorCounts } from \"./categories\";\nimport { addAiLatency, aiLatencyBucket, emptyAiLatency } from \"./histogram\";\n\ntype Span = Trace[\"root\"];\ntype RollupKey = { hour: number; agent: string; model: string; provider: string };\n\nconst HOUR_MS = 3_600_000;\nconst UNKNOWN = \"(unknown)\";\nconst MODEL_SPAN_TYPES: ReadonlySet<string> = new Set([\n \"agent\",\n \"image\",\n \"speech\",\n \"transcription\",\n]);\n\n/** Token counts with `input` normalised to the whole prompt. */\ntype Tokens = {\n input: number;\n output: number;\n cached: number;\n cacheWrite: number;\n reasoning: number;\n};\n\nfunction count(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction normalise(usage: Span[\"usage\"] | undefined): Tokens {\n const cached = count(usage?.cachedTokens);\n const cacheWrite = count(usage?.cacheWriteTokens);\n const input = count(usage?.input);\n\n return {\n input: usage?.inputIncludesCache === false ? input + cached + cacheWrite : input,\n output: count(usage?.output),\n cached,\n cacheWrite,\n reasoning: count(usage?.reasoningTokens),\n };\n}\n\nfunction subtract(own: Tokens, other: Tokens): void {\n own.input = Math.max(0, own.input - other.input);\n own.output = Math.max(0, own.output - other.output);\n own.cached = Math.max(0, own.cached - other.cached);\n own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);\n own.reasoning = Math.max(0, own.reasoning - other.reasoning);\n}\n\n/** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */\nexport function isAiModelSpan(span: Span): boolean {\n return (\n typeof span.attributes?.[\"agent.model.name\"] === \"string\" || MODEL_SPAN_TYPES.has(span.type)\n );\n}\n\n/** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */\nfunction nearestModelSpans(span: Span): Span[] {\n const found: Span[] = [];\n\n for (const child of span.children ?? []) {\n if (isAiModelSpan(child)) found.push(child);\n else found.push(...nearestModelSpans(child));\n }\n\n return found;\n}\n\nfunction cut(value: unknown, max: number): string {\n if (typeof value !== \"string\" || value === \"\") return UNKNOWN;\n\n return value.length > max ? value.slice(0, max) : value;\n}\n\nfunction spanCost(span: Span, totalCost: DevtoolsAiTotalCost): number {\n return count(totalCost(span.usage));\n}\n\n/** Whether a span's usage carries pricing at all (a free model is priced at 0; no pricing is `undefined`). */\nfunction hasPricing(span: Span, totalCost: DevtoolsAiTotalCost): boolean {\n return typeof totalCost(span.usage) === \"number\";\n}\n\nfunction buildDelta(\n key: RollupKey,\n status: string,\n errorType: string | undefined,\n tokens: Tokens,\n cost: number,\n /** The own usage is priced even when `cost` is 0 (a model priced as free). */\n pricedAtZero = false,\n): DevtoolsAiRollupDelta {\n const delta = emptyRollupDelta(key);\n\n delta.runs = 1;\n delta.inputTokens = tokens.input;\n delta.outputTokens = tokens.output;\n delta.cachedTokens = tokens.cached;\n delta.cacheWriteTokens = tokens.cacheWrite;\n delta.reasoningTokens = tokens.reasoning;\n\n if (status === \"completed\") delta.completed = 1;\n else if (status === \"failed\") delta.failed = 1;\n else if (status === \"incomplete\" || status === \"max-iterations\") delta.incomplete = 1;\n else if (status === \"cancelled\") delta.cancelled = 1;\n\n if (status === \"failed\" || status === \"incomplete\" || status === \"max-iterations\") {\n delta.errors[classifyAiError(status, errorType)] = 1;\n }\n\n if (cost > 0 || (pricedAtZero && tokens.input + tokens.output > 0)) {\n delta.costUsd = cost;\n delta.pricedRuns = 1;\n } else if (tokens.input + tokens.output > 0) {\n delta.unpricedRuns = 1;\n delta.unpricedTokens = tokens.input + tokens.output;\n }\n\n return delta;\n}\n\n/**\n * Turns one finished Panoptic trace into rollup deltas, one per\n * model-bearing span (a span with an `agent.model.name` attribute, or of type\n * `agent`, `image`, `speech` or `transcription`), keyed by the hour of the\n * span's `endedAt`.\n *\n * Each span counts its OWN usage and cost: its rolled-up `usage` minus the\n * usage of its nearest model-bearing descendants (an agent used as a tool is\n * counted once, as itself). Root usage left after subtracting every\n * model-bearing span (a custom flow with no agent span) becomes one more delta\n * for the root name with model `(unknown)`, counted as one run.\n *\n * Per span: status maps to completed / failed / incomplete (`incomplete`,\n * `max-iterations`) / cancelled; failed and incomplete runs add one error to\n * `classifyAiError(status, error.type)`; tokens are normalised so `input`\n * includes cache reads and writes; `costUsd` is `totalCost` of the own usage\n * when it is above 0 (or the span's model is priced as free), otherwise a run\n * with tokens counts in `unpricedRuns` and `unpricedTokens`; `agent.fallbackTrips > 0` adds a fallback run;\n * `agent.refusals > 0` or a CONTENT_FILTER error adds a refusal; the span's\n * `duration` goes into the latency histogram.\n *\n * Pure: no clock, no I/O. Names are cut to 200 (provider 100) characters.\n */\nexport function traceToRollupDeltas(\n trace: Trace,\n totalCost: DevtoolsAiTotalCost,\n): DevtoolsAiRollupDelta[] {\n const root = trace.root;\n\n if (!root) return [];\n\n // A span without a readable end falls back to the root's end, then the trace's; no end at all skips the trace.\n const rootEnd = Date.parse(root.endedAt);\n const fallbackEnd = Number.isNaN(rootEnd) ? Date.parse(trace.endedAt) : rootEnd;\n\n if (Number.isNaN(fallbackEnd)) return [];\n\n const hourOf = (span: Span): number => {\n const ended = Date.parse(span.endedAt);\n const at = Number.isNaN(ended) ? fallbackEnd : ended;\n\n return Math.floor(at / HOUR_MS) * HOUR_MS;\n };\n\n const deltas: DevtoolsAiRollupDelta[] = [];\n const topLevel: Span[] = isAiModelSpan(root) ? [root] : nearestModelSpans(root);\n\n const visit = (span: Span): void => {\n const tokens = normalise(span.usage);\n let cost = spanCost(span, totalCost);\n const inner = nearestModelSpans(span);\n\n for (const child of inner) {\n subtract(tokens, normalise(child.usage));\n cost -= spanCost(child, totalCost);\n }\n\n cost = Math.max(0, cost);\n\n // Priced at zero only when the span's own pricing is known: none of the nested model spans carry a cost.\n const pricedAtZero =\n hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));\n\n const attributes = span.attributes ?? {};\n const key: RollupKey = { hour: hourOf(span), ...aiRollupNamesOf(span) };\n const delta = buildDelta(key, span.status, span.error?.type, tokens, cost, pricedAtZero);\n\n if (count(attributes[\"agent.fallbackTrips\"]) > 0) delta.fallbackRuns = 1;\n\n if (count(attributes[\"agent.refusals\"]) > 0 || span.error?.type === \"CONTENT_FILTER\") {\n delta.refusals = 1;\n }\n\n const duration = count(span.duration);\n\n const bucket = aiLatencyBucket(duration);\n\n delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;\n delta.latencyCount = 1;\n delta.latencySumMs = Math.max(0, duration);\n\n deltas.push(delta);\n\n for (const child of inner) visit(child);\n };\n\n // Only the real model-bearing roots start the walk; `visit` handles nesting.\n for (const span of topLevel) visit(span);\n\n const leftover = normalise(root.usage);\n let leftoverCost = spanCost(root, totalCost);\n\n for (const span of topLevel) {\n subtract(leftover, normalise(span.usage));\n leftoverCost -= spanCost(span, totalCost);\n }\n\n if (leftover.input + leftover.output > 0) {\n deltas.push(\n buildDelta(\n { hour: hourOf(root), agent: cut(root.name, 200), model: UNKNOWN, provider: UNKNOWN },\n root.status,\n root.error?.type,\n leftover,\n Math.max(0, leftoverCost),\n ),\n );\n }\n\n return deltas;\n}\n\n/** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */\nexport function aiRollupNamesOf(span: Span): { agent: string; model: string; provider: string } {\n return {\n agent: cut(span.name, 200),\n model: cut(span.attributes?.[\"agent.model.name\"], 200),\n provider: cut(span.attributes?.[\"agent.model.provider\"], 100),\n };\n}\n\n/** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */\nexport function rollupId(key: RollupKey): string {\n return createHash(\"sha256\")\n .update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`)\n .digest(\"hex\")\n .slice(0, 40);\n}\n\n/** A delta with every counter at zero for `key`. */\nexport function emptyRollupDelta(key: RollupKey): DevtoolsAiRollupDelta {\n return {\n hour: key.hour,\n agent: key.agent,\n model: key.model,\n provider: key.provider,\n runs: 0,\n completed: 0,\n failed: 0,\n incomplete: 0,\n cancelled: 0,\n inputTokens: 0,\n outputTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n reasoningTokens: 0,\n costUsd: 0,\n pricedRuns: 0,\n unpricedRuns: 0,\n unpricedTokens: 0,\n fallbackRuns: 0,\n refusals: 0,\n errors: emptyErrorCounts(),\n latency: emptyAiLatency(),\n latencyCount: 0,\n latencySumMs: 0,\n };\n}\n\nconst NUMERIC_COUNTERS = [\n \"runs\",\n \"completed\",\n \"failed\",\n \"incomplete\",\n \"cancelled\",\n \"inputTokens\",\n \"outputTokens\",\n \"cachedTokens\",\n \"cacheWriteTokens\",\n \"reasoningTokens\",\n \"costUsd\",\n \"pricedRuns\",\n \"unpricedRuns\",\n \"unpricedTokens\",\n \"fallbackRuns\",\n \"refusals\",\n \"latencyCount\",\n \"latencySumMs\",\n] as const;\n\n/** Adds the counters of `source` into `target` in place (keys must match). */\nexport function addRollupCounters(\n target: DevtoolsAiRollupDelta,\n source: DevtoolsAiRollupDelta,\n): void {\n for (const field of NUMERIC_COUNTERS) target[field] += source[field];\n\n for (const category of Object.keys(target.errors) as (keyof typeof target.errors)[]) {\n target.errors[category] += source.errors[category] ?? 0;\n }\n\n addAiLatency(target.latency, source.latency);\n}\n"],"mappings":";;;;;AASA,MAAM,UAAU;AAChB,MAAM,UAAU;AAChB,MAAM,mCAAwC,IAAI,IAAI;CACpD;CACA;CACA;CACA;AACF,CAAC;AAWD,SAAS,MAAM,OAAwB;CACrC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,UAAU,OAA0C;CAC3D,MAAM,SAAS,MAAM,OAAO,YAAY;CACxC,MAAM,aAAa,MAAM,OAAO,gBAAgB;CAChD,MAAM,QAAQ,MAAM,OAAO,KAAK;CAEhC,OAAO;EACL,OAAO,OAAO,uBAAuB,QAAQ,QAAQ,SAAS,aAAa;EAC3E,QAAQ,MAAM,OAAO,MAAM;EAC3B;EACA;EACA,WAAW,MAAM,OAAO,eAAe;CACzC;AACF;AAEA,SAAS,SAAS,KAAa,OAAqB;CAClD,IAAI,QAAQ,KAAK,IAAI,GAAG,IAAI,QAAQ,MAAM,KAAK;CAC/C,IAAI,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,MAAM,MAAM;CAClD,IAAI,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,MAAM,MAAM;CAClD,IAAI,aAAa,KAAK,IAAI,GAAG,IAAI,aAAa,MAAM,UAAU;CAC9D,IAAI,YAAY,KAAK,IAAI,GAAG,IAAI,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EAAE;AAChB;;AAGA,SAAgB,iBAAiB,KAAuC;CACtE,OAAO;EACL,MAAM,IAAI;EACV,OAAO,IAAI;EACX,OAAO,IAAI;EACX,UAAU,IAAI;EACd,MAAM;EACN,WAAW;EACX,QAAQ;EACR,YAAY;EACZ,WAAW;EACX,aAAa;EACb,cAAc;EACd,cAAc;EACd,kBAAkB;EAClB,iBAAiB;EACjB,SAAS;EACT,YAAY;EACZ,cAAc;EACd,gBAAgB;EAChB,cAAc;EACd,UAAU;EACV,QAAQ,iBAAiB;EACzB,SAAS,eAAe;EACxB,cAAc;EACd,cAAc;CAChB;AACF;AAEA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,kBACd,QACA,QACM;CACN,KAAK,MAAM,SAAS,kBAAkB,OAAO,UAAU,OAAO;CAE9D,KAAK,MAAM,YAAY,OAAO,KAAK,OAAO,MAAM,GAC9C,OAAO,OAAO,aAAa,OAAO,OAAO,aAAa;CAGxD,aAAa,OAAO,SAAS,OAAO,OAAO;AAC7C"}
@@ -0,0 +1,147 @@
1
+ import { DevtoolsAiRollupIncrementError } from "./increment-error.mjs";
2
+ import { applyAiRollupDelta, matchesAiRollupFilter } from "./memory-store.mjs";
3
+ import path from "node:path";
4
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
5
+
6
+ //#region ../../packages/devtools/src/ai/rollup/file-store.ts
7
+ const DAY_MS = 864e5;
8
+ const DAY_FILE = /^(\d{4}-\d{2}-\d{2})\.json$/;
9
+ function dayName(hour) {
10
+ return new Date(hour).toISOString().slice(0, 10);
11
+ }
12
+ function dayStart(name) {
13
+ return Date.parse(`${name}T00:00:00.000Z`);
14
+ }
15
+ /**
16
+ * The development `DevtoolsAiRollupStore`: one JSON file per UTC day
17
+ * (`YYYY-MM-DD.json`, an array of records) in `directory`. Development runs
18
+ * one process, so `increment` reads the day's file, adds, and writes it back
19
+ * through a temporary file and a rename (a failed day is reported with
20
+ * `DevtoolsAiRollupIncrementError`, the other days stay saved). `prune` deletes whole day files
21
+ * before the cut-off and rewrites the boundary day. `verify` is `true` when
22
+ * the folder exists or can be created. A corrupt file is renamed to
23
+ * `<name>.corrupt-<time>` and treated as empty.
24
+ */
25
+ function createFileAiRollupStore(options) {
26
+ const { directory } = options;
27
+ const now = options.now ?? Date.now;
28
+ let queue = Promise.resolve();
29
+ const serial = (task) => {
30
+ const run = queue.then(task, task);
31
+ queue = run.catch(() => void 0);
32
+ return run;
33
+ };
34
+ const fileOf = (name) => path.join(directory, `${name}.json`);
35
+ async function readDay(name) {
36
+ const file = fileOf(name);
37
+ let text;
38
+ try {
39
+ text = await readFile(file, "utf8");
40
+ } catch (error) {
41
+ if (error.code === "ENOENT") return [];
42
+ throw error;
43
+ }
44
+ try {
45
+ const parsed = JSON.parse(text);
46
+ if (!Array.isArray(parsed)) throw new Error("not an array");
47
+ return parsed;
48
+ } catch {
49
+ await rename(file, `${file}.corrupt-${now()}`).catch(() => void 0);
50
+ return [];
51
+ }
52
+ }
53
+ async function writeDay(name, records) {
54
+ await mkdir(directory, { recursive: true });
55
+ const file = fileOf(name);
56
+ const temporary = `${file}.tmp-${process.pid}`;
57
+ await writeFile(temporary, JSON.stringify(records), "utf8");
58
+ await rename(temporary, file);
59
+ }
60
+ return {
61
+ async verify() {
62
+ try {
63
+ await mkdir(directory, { recursive: true });
64
+ return true;
65
+ } catch {
66
+ return false;
67
+ }
68
+ },
69
+ increment(deltas) {
70
+ return serial(async () => {
71
+ const byDay = /* @__PURE__ */ new Map();
72
+ for (const delta of deltas) {
73
+ const name = dayName(delta.hour);
74
+ byDay.set(name, [...byDay.get(name) ?? [], delta]);
75
+ }
76
+ const unwritten = [];
77
+ let firstError;
78
+ for (const [name, dayDeltas] of byDay) try {
79
+ const rows = new Map((await readDay(name)).map((record) => [record.id, record]));
80
+ for (const delta of dayDeltas) applyAiRollupDelta(rows, delta, now());
81
+ await writeDay(name, [...rows.values()]);
82
+ } catch (error) {
83
+ firstError ??= error;
84
+ unwritten.push(...dayDeltas);
85
+ }
86
+ if (unwritten.length === 0) return;
87
+ if (unwritten.length === deltas.length) throw firstError;
88
+ throw new DevtoolsAiRollupIncrementError(unwritten, {
89
+ written: deltas.length - unwritten.length,
90
+ cause: firstError
91
+ });
92
+ });
93
+ },
94
+ async list(filter) {
95
+ if (filter.toHour <= filter.fromHour) return [];
96
+ const found = [];
97
+ const first = dayStart(dayName(filter.fromHour));
98
+ let names;
99
+ try {
100
+ names = await readdir(directory);
101
+ } catch {
102
+ return [];
103
+ }
104
+ for (const file of names.sort()) {
105
+ const name = DAY_FILE.exec(file)?.[1];
106
+ if (!name) continue;
107
+ const start = dayStart(name);
108
+ if (start < first || start >= filter.toHour) continue;
109
+ for (const record of await readDay(name)) if (matchesAiRollupFilter(record, filter)) found.push(record);
110
+ }
111
+ return found;
112
+ },
113
+ prune(beforeHour) {
114
+ return serial(async () => {
115
+ let names;
116
+ try {
117
+ names = await readdir(directory);
118
+ } catch {
119
+ return 0;
120
+ }
121
+ let removed = 0;
122
+ for (const file of names) {
123
+ const name = DAY_FILE.exec(file)?.[1];
124
+ if (!name) continue;
125
+ const start = dayStart(name);
126
+ if (start >= beforeHour) continue;
127
+ const records = await readDay(name);
128
+ if (start + DAY_MS <= beforeHour) {
129
+ await rm(fileOf(name), { force: true });
130
+ removed += records.length;
131
+ continue;
132
+ }
133
+ const kept = records.filter((record) => record.hour >= beforeHour);
134
+ if (kept.length !== records.length) {
135
+ removed += records.length - kept.length;
136
+ await writeDay(name, kept);
137
+ }
138
+ }
139
+ return removed;
140
+ });
141
+ }
142
+ };
143
+ }
144
+
145
+ //#endregion
146
+ export { createFileAiRollupStore };
147
+ //# sourceMappingURL=file-store.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-store.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/file-store.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n DevtoolsAiRollupDelta,\n DevtoolsAiRollupRecord,\n DevtoolsAiRollupStore,\n} from \"../types\";\nimport { DevtoolsAiRollupIncrementError } from \"./increment-error\";\nimport { applyAiRollupDelta, matchesAiRollupFilter } from \"./memory-store\";\n\nexport type FileAiRollupStoreOptions = {\n /** The folder, e.g. `storage/devtools/ai-rollups`; created on the first write. */\n directory: string;\n now?: () => number;\n};\n\nconst DAY_MS = 86_400_000;\nconst DAY_FILE = /^(\\d{4}-\\d{2}-\\d{2})\\.json$/;\n\nfunction dayName(hour: number): string {\n return new Date(hour).toISOString().slice(0, 10);\n}\n\nfunction dayStart(name: string): number {\n return Date.parse(`${name}T00:00:00.000Z`);\n}\n\n/**\n * The development `DevtoolsAiRollupStore`: one JSON file per UTC day\n * (`YYYY-MM-DD.json`, an array of records) in `directory`. Development runs\n * one process, so `increment` reads the day's file, adds, and writes it back\n * through a temporary file and a rename (a failed day is reported with\n * `DevtoolsAiRollupIncrementError`, the other days stay saved). `prune` deletes whole day files\n * before the cut-off and rewrites the boundary day. `verify` is `true` when\n * the folder exists or can be created. A corrupt file is renamed to\n * `<name>.corrupt-<time>` and treated as empty.\n */\nexport function createFileAiRollupStore(options: FileAiRollupStoreOptions): DevtoolsAiRollupStore {\n const { directory } = options;\n const now = options.now ?? Date.now;\n // Writes run one after another, so two flushes never interleave a read and a rename.\n let queue: Promise<unknown> = Promise.resolve();\n\n const serial = <T>(task: () => Promise<T>): Promise<T> => {\n const run = queue.then(task, task);\n\n queue = run.catch(() => undefined);\n\n return run;\n };\n\n const fileOf = (name: string) => path.join(directory, `${name}.json`);\n\n async function readDay(name: string): Promise<DevtoolsAiRollupRecord[]> {\n const file = fileOf(name);\n let text: string;\n\n try {\n text = await readFile(file, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\n throw error;\n }\n\n try {\n const parsed: unknown = JSON.parse(text);\n\n if (!Array.isArray(parsed)) throw new Error(\"not an array\");\n\n return parsed as DevtoolsAiRollupRecord[];\n } catch {\n await rename(file, `${file}.corrupt-${now()}`).catch(() => undefined);\n\n return [];\n }\n }\n\n async function writeDay(name: string, records: DevtoolsAiRollupRecord[]): Promise<void> {\n await mkdir(directory, { recursive: true });\n\n const file = fileOf(name);\n const temporary = `${file}.tmp-${process.pid}`;\n\n await writeFile(temporary, JSON.stringify(records), \"utf8\");\n await rename(temporary, file);\n }\n\n return {\n async verify() {\n try {\n await mkdir(directory, { recursive: true });\n\n return true;\n } catch {\n return false;\n }\n },\n increment(deltas) {\n return serial(async () => {\n const byDay = new Map<string, (typeof deltas)[number][]>();\n\n for (const delta of deltas) {\n const name = dayName(delta.hour);\n\n byDay.set(name, [...(byDay.get(name) ?? []), delta]);\n }\n\n // Each day file is written on its own; a failed day is reported so a retry never adds a saved day twice.\n const unwritten: DevtoolsAiRollupDelta[] = [];\n let firstError: unknown;\n\n for (const [name, dayDeltas] of byDay) {\n try {\n const rows = new Map((await readDay(name)).map((record) => [record.id, record]));\n\n for (const delta of dayDeltas) applyAiRollupDelta(rows, delta, now());\n\n await writeDay(name, [...rows.values()]);\n } catch (error) {\n firstError ??= error;\n unwritten.push(...dayDeltas);\n }\n }\n\n if (unwritten.length === 0) return;\n\n if (unwritten.length === deltas.length) throw firstError;\n\n throw new DevtoolsAiRollupIncrementError(unwritten, {\n written: deltas.length - unwritten.length,\n cause: firstError,\n });\n });\n },\n async list(filter) {\n if (filter.toHour <= filter.fromHour) return [];\n\n const found: DevtoolsAiRollupRecord[] = [];\n const first = dayStart(dayName(filter.fromHour));\n let names: string[];\n\n try {\n names = await readdir(directory);\n } catch {\n return [];\n }\n\n // Only the day files inside the range are read (a range may be open-ended).\n for (const file of names.sort()) {\n const name = DAY_FILE.exec(file)?.[1];\n\n if (!name) continue;\n\n const start = dayStart(name);\n\n if (start < first || start >= filter.toHour) continue;\n\n for (const record of await readDay(name)) {\n if (matchesAiRollupFilter(record, filter)) found.push(record);\n }\n }\n\n return found;\n },\n prune(beforeHour) {\n return serial(async () => {\n let names: string[];\n\n try {\n names = await readdir(directory);\n } catch {\n return 0;\n }\n\n let removed = 0;\n\n for (const file of names) {\n const name = DAY_FILE.exec(file)?.[1];\n\n if (!name) continue;\n\n const start = dayStart(name);\n\n if (start >= beforeHour) continue;\n\n const records = await readDay(name);\n\n if (start + DAY_MS <= beforeHour) {\n await rm(fileOf(name), { force: true });\n removed += records.length;\n\n continue;\n }\n\n const kept = records.filter((record) => record.hour >= beforeHour);\n\n if (kept.length !== records.length) {\n removed += records.length - kept.length;\n await writeDay(name, kept);\n }\n }\n\n return removed;\n });\n },\n };\n}\n"],"mappings":";;;;;;AAgBA,MAAM,SAAS;AACf,MAAM,WAAW;AAEjB,SAAS,QAAQ,MAAsB;CACrC,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,MAAM,GAAG,EAAE;AACjD;AAEA,SAAS,SAAS,MAAsB;CACtC,OAAO,KAAK,MAAM,GAAG,KAAK,eAAe;AAC3C;;;;;;;;;;;AAYA,SAAgB,wBAAwB,SAA0D;CAChG,MAAM,EAAE,cAAc;CACtB,MAAM,MAAM,QAAQ,OAAO,KAAK;CAEhC,IAAI,QAA0B,QAAQ,QAAQ;CAE9C,MAAM,UAAa,SAAuC;EACxD,MAAM,MAAM,MAAM,KAAK,MAAM,IAAI;EAEjC,QAAQ,IAAI,YAAY,MAAS;EAEjC,OAAO;CACT;CAEA,MAAM,UAAU,SAAiB,KAAK,KAAK,WAAW,GAAG,KAAK,MAAM;CAEpE,eAAe,QAAQ,MAAiD;EACtE,MAAM,OAAO,OAAO,IAAI;EACxB,IAAI;EAEJ,IAAI;GACF,OAAO,MAAM,SAAS,MAAM,MAAM;EACpC,SAAS,OAAO;GACd,IAAK,MAAgC,SAAS,UAAU,OAAO,CAAC;GAEhE,MAAM;EACR;EAEA,IAAI;GACF,MAAM,S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AAQ,WAAW,OAAO,QAAQ,UAAU;KAEjE,IAAI,KAAK,WAAW,QAAQ,QAAQ;MAClC,WAAW,QAAQ,SAAS,KAAK;MACjC,MAAM,SAAS,MAAM,IAAI;KAC3B;IACF;IAEA,OAAO;GACT,CAAC;EACH;CACF;AACF"}
@@ -0,0 +1,42 @@
1
+ import { DEVTOOLS_AI_LATENCY_BUCKETS_MS } from "../../production/contracts.mjs";
2
+
3
+ //#region ../../packages/devtools/src/ai/rollup/histogram.ts
4
+ /**
5
+ * Latency histograms over `DEVTOOLS_AI_LATENCY_BUCKETS_MS`, stored as plain
6
+ * count arrays in the rollups (one more count than bounds).
7
+ */
8
+ const BUCKETS = DEVTOOLS_AI_LATENCY_BUCKETS_MS;
9
+ /** `DEVTOOLS_AI_LATENCY_BUCKETS_MS.length + 1` zeros. */
10
+ function emptyAiLatency() {
11
+ return new Array(BUCKETS.length + 1).fill(0);
12
+ }
13
+ /** The bucket index of a duration; a negative or non-finite value counts as 0. */
14
+ function aiLatencyBucket(durationMs) {
15
+ if (!Number.isFinite(durationMs) || durationMs < 0) return 0;
16
+ const index = BUCKETS.findIndex((bound) => durationMs <= bound);
17
+ return index === -1 ? BUCKETS.length : index;
18
+ }
19
+ /** Adds `source` into `target` in place (same length). */
20
+ function addAiLatency(target, source) {
21
+ for (let index = 0; index < target.length; index++) target[index] = (target[index] ?? 0) + (source[index] ?? 0);
22
+ }
23
+ /**
24
+ * The `q` quantile (0–1): the upper bound of the bucket that holds it, or the
25
+ * last bound for the overflow bucket. `null` for an empty histogram.
26
+ */
27
+ function aiLatencyQuantile(counts, q) {
28
+ let total = 0;
29
+ for (const count of counts) total += count;
30
+ if (total <= 0) return null;
31
+ const target = Math.max(1, Math.ceil(Math.min(1, Math.max(0, q)) * total));
32
+ let seen = 0;
33
+ for (let index = 0; index < counts.length; index++) {
34
+ seen += counts[index] ?? 0;
35
+ if (seen >= target) return BUCKETS[Math.min(index, BUCKETS.length - 1)] ?? null;
36
+ }
37
+ return BUCKETS[BUCKETS.length - 1] ?? null;
38
+ }
39
+
40
+ //#endregion
41
+ export { addAiLatency, aiLatencyBucket, aiLatencyQuantile, emptyAiLatency };
42
+ //# sourceMappingURL=histogram.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"histogram.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/histogram.ts"],"sourcesContent":["import { DEVTOOLS_AI_LATENCY_BUCKETS_MS } from \"../../production/contracts\";\n\n/**\n * Latency histograms over `DEVTOOLS_AI_LATENCY_BUCKETS_MS`, stored as plain\n * count arrays in the rollups (one more count than bounds).\n */\n\nconst BUCKETS = DEVTOOLS_AI_LATENCY_BUCKETS_MS;\n\n/** `DEVTOOLS_AI_LATENCY_BUCKETS_MS.length + 1` zeros. */\nexport function emptyAiLatency(): number[] {\n return new Array<number>(BUCKETS.length + 1).fill(0);\n}\n\n/** The bucket index of a duration; a negative or non-finite value counts as 0. */\nexport function aiLatencyBucket(durationMs: number): number {\n if (!Number.isFinite(durationMs) || durationMs < 0) return 0;\n\n const index = BUCKETS.findIndex((bound) => durationMs <= bound);\n\n return index === -1 ? BUCKETS.length : index;\n}\n\n/** Adds `source` into `target` in place (same length). */\nexport function addAiLatency(target: number[], source: readonly number[]): void {\n for (let index = 0; index < target.length; index++) {\n target[index] = (target[index] ?? 0) + (source[index] ?? 0);\n }\n}\n\n/**\n * The `q` quantile (0–1): the upper bound of the bucket that holds it, or the\n * last bound for the overflow bucket. `null` for an empty histogram.\n */\nexport function aiLatencyQuantile(counts: readonly number[], q: number): number | null {\n let total = 0;\n\n for (const count of counts) total += count;\n\n if (total <= 0) return null;\n\n const target = Math.max(1, Math.ceil(Math.min(1, Math.max(0, q)) * total));\n let seen = 0;\n\n for (let index = 0; index < counts.length; index++) {\n seen += counts[index] ?? 0;\n\n if (seen >= target) return BUCKETS[Math.min(index, BUCKETS.length - 1)] ?? null;\n }\n\n return BUCKETS[BUCKETS.length - 1] ?? null;\n}\n"],"mappings":";;;;;;;AAOA,MAAM,UAAU;;AAGhB,SAAgB,iBAA2B;CACzC,OAAO,IAAI,MAAc,QAAQ,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;AACrD;;AAGA,SAAgB,gBAAgB,YAA4B;CAC1D,IAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,GAAG,OAAO;CAE3D,MAAM,QAAQ,QAAQ,WAAW,UAAU,cAAc,KAAK;CAE9D,OAAO,UAAU,KAAK,QAAQ,SAAS;AACzC;;AAGA,SAAgB,aAAa,QAAkB,QAAiC;CAC9E,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SACzC,OAAO,UAAU,OAAO,UAAU,MAAM,OAAO,UAAU;AAE7D;;;;;AAMA,SAAgB,kBAAkB,QAA2B,GAA0B;CACrF,IAAI,QAAQ;CAEZ,KAAK,MAAM,SAAS,QAAQ,SAAS;CAErC,IAAI,SAAS,GAAG,OAAO;CAEvB,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC;CACzE,IAAI,OAAO;CAEX,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS;EAClD,QAAQ,OAAO,UAAU;EAEzB,IAAI,QAAQ,QAAQ,OAAO,QAAQ,KAAK,IAAI,OAAO,QAAQ,SAAS,CAAC,MAAM;CAC7E;CAEA,OAAO,QAAQ,QAAQ,SAAS,MAAM;AACxC"}
@@ -0,0 +1,19 @@
1
+ //#region ../../packages/devtools/src/ai/rollup/increment-error.ts
2
+ /**
3
+ * Thrown by `DevtoolsAiRollupStore.increment` when only part of the deltas
4
+ * were written. `unwritten` lists the deltas that were not saved, so the
5
+ * writer retries those alone and never adds a saved delta twice. A store that
6
+ * throws any other error is treated as having written nothing.
7
+ */
8
+ var DevtoolsAiRollupIncrementError = class extends Error {
9
+ constructor(unwritten, options) {
10
+ const reason = options.cause instanceof Error ? options.cause.message : String(options.cause);
11
+ super(`${unwritten.length} of ${unwritten.length + options.written} AI totals were not saved (${reason})`, { cause: options.cause });
12
+ this.name = "DevtoolsAiRollupIncrementError";
13
+ this.unwritten = unwritten;
14
+ }
15
+ };
16
+
17
+ //#endregion
18
+ export { DevtoolsAiRollupIncrementError };
19
+ //# sourceMappingURL=increment-error.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"increment-error.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/increment-error.ts"],"sourcesContent":["import type { DevtoolsAiRollupDelta } from \"../types\";\n\n/**\n * Thrown by `DevtoolsAiRollupStore.increment` when only part of the deltas\n * were written. `unwritten` lists the deltas that were not saved, so the\n * writer retries those alone and never adds a saved delta twice. A store that\n * throws any other error is treated as having written nothing.\n */\nexport class DevtoolsAiRollupIncrementError extends Error {\n public readonly unwritten: readonly DevtoolsAiRollupDelta[];\n\n public constructor(\n unwritten: readonly DevtoolsAiRollupDelta[],\n options: { written: number; cause: unknown },\n ) {\n const reason = options.cause instanceof Error ? options.cause.message : String(options.cause);\n\n super(\n `${unwritten.length} of ${unwritten.length + options.written} AI totals were not saved (${reason})`,\n { cause: options.cause },\n );\n this.name = \"DevtoolsAiRollupIncrementError\";\n this.unwritten = unwritten;\n }\n}\n"],"mappings":";;;;;;;AAQA,IAAa,iCAAb,cAAoD,MAAM;CAGxD,AAAO,YACL,WACA,SACA;EACA,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,QAAQ,MAAM,UAAU,OAAO,QAAQ,KAAK;EAE5F,MACE,GAAG,UAAU,OAAO,MAAM,UAAU,SAAS,QAAQ,QAAQ,6BAA6B,OAAO,IACjG,EAAE,OAAO,QAAQ,MAAM,CACzB;EACA,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF"}
@@ -0,0 +1,9 @@
1
+ import { DEVTOOLS_AI_ERROR_LABELS, classifyAiError, emptyErrorCounts } from "./categories.mjs";
2
+ import { addAiLatency, aiLatencyBucket, aiLatencyQuantile, emptyAiLatency } from "./histogram.mjs";
3
+ import { addRollupCounters, emptyRollupDelta, rollupId, traceToRollupDeltas } from "./extract.mjs";
4
+ import { DevtoolsAiRollupIncrementError } from "./increment-error.mjs";
5
+ import { createCascadeAiRollupStore } from "./cascade-store.mjs";
6
+ import { createFileAiRollupStore } from "./file-store.mjs";
7
+ import { startAiRollupWriter } from "./writer.mjs";
8
+
9
+ export { createCascadeAiRollupStore, createFileAiRollupStore, startAiRollupWriter };