@warlock.js/devtools 5.58.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 (162) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/cjs/app-versions-C_ZyzuvD.cjs +138 -0
  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-DV2GA1A9.cjs → auth-ChHh5E7j.cjs} +20 -13
  7. package/cjs/auth-ChHh5E7j.cjs.map +1 -0
  8. package/cjs/{boot-CyeHPFtk.cjs → boot-Dg5YZGGR.cjs} +78 -14
  9. package/cjs/boot-Dg5YZGGR.cjs.map +1 -0
  10. package/cjs/{capture-DcyBhdqw.cjs → capture-CBgONYhk.cjs} +4 -4
  11. package/cjs/{capture-DcyBhdqw.cjs.map → capture-CBgONYhk.cjs.map} +1 -1
  12. package/cjs/{cascade-store-DEGxAFDI.cjs → cascade-store-DUT2Laha.cjs} +3 -3
  13. package/cjs/cascade-store-DUT2Laha.cjs.map +1 -0
  14. package/cjs/{current-request-id-BoJJb3y7.cjs → current-request-id-Badec-TH.cjs} +3 -3
  15. package/cjs/{current-request-id-BoJJb3y7.cjs.map → current-request-id-Badec-TH.cjs.map} +1 -1
  16. package/cjs/{errors-DEqdWaqm.cjs → errors-DNQ-g49I.cjs} +201 -4
  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/{helpers-7k_Q-abk.cjs → helpers-BcMBFy9v.cjs} +9 -6
  21. package/cjs/{helpers-7k_Q-abk.cjs.map → helpers-BcMBFy9v.cjs.map} +1 -1
  22. package/cjs/{histogram-BRV5eHcp.cjs → histogram-CkoVizdf.cjs} +6 -6
  23. package/cjs/{histogram-BRV5eHcp.cjs.map → histogram-CkoVizdf.cjs.map} +1 -1
  24. package/cjs/{http-XNLYU2vS.cjs → http-DCVCf44M.cjs} +26 -9
  25. package/cjs/http-DCVCf44M.cjs.map +1 -0
  26. package/cjs/index.cjs +1 -1
  27. package/cjs/{insights-BBZnUpWO.cjs → insights-CFof59kF.cjs} +6 -6
  28. package/cjs/{insights-BBZnUpWO.cjs.map → insights-CFof59kF.cjs.map} +1 -1
  29. package/cjs/migrations-BQdNOL5_.cjs +30 -0
  30. package/cjs/migrations-BQdNOL5_.cjs.map +1 -0
  31. package/cjs/{migrations-DTTzCNpR.cjs → models-DF1agAm4.cjs} +107 -25
  32. package/cjs/models-DF1agAm4.cjs.map +1 -0
  33. package/cjs/{process-panel-DEOnLxoT.cjs → process-panel-D3D9Y_dc.cjs} +5 -5
  34. package/cjs/{process-panel-DEOnLxoT.cjs.map → process-panel-D3D9Y_dc.cjs.map} +1 -1
  35. package/cjs/production/index.cjs +4 -4
  36. package/cjs/runs-DECWPGnq.cjs +390 -0
  37. package/cjs/runs-DECWPGnq.cjs.map +1 -0
  38. package/cjs/{server-C8JfggQU.cjs → server-CC5DpObz.cjs} +10 -7
  39. package/cjs/server-CC5DpObz.cjs.map +1 -0
  40. package/cjs/{src-DjOUdhKc.cjs → src-VyOjEEAo.cjs} +179 -24
  41. package/cjs/src-VyOjEEAo.cjs.map +1 -0
  42. package/cjs/{store-C06KO_A1.cjs → store-EFn4wp0T.cjs} +2 -2
  43. package/cjs/{stream-route-D4k-sJvW.cjs → stream-route-DFHuIWgg.cjs} +125 -19
  44. package/cjs/stream-route-DFHuIWgg.cjs.map +1 -0
  45. package/esm/ai/attach.mjs +92 -0
  46. package/esm/ai/attach.mjs.map +1 -0
  47. package/esm/ai/options.mjs +31 -0
  48. package/esm/ai/options.mjs.map +1 -0
  49. package/esm/ai/reports/aggregate.mjs +330 -0
  50. package/esm/ai/reports/aggregate.mjs.map +1 -0
  51. package/esm/ai/reports/evaluate.mjs +108 -0
  52. package/esm/ai/reports/evaluate.mjs.map +1 -0
  53. package/esm/ai/reports/range.mjs +121 -0
  54. package/esm/ai/reports/range.mjs.map +1 -0
  55. package/esm/ai/reports/runs.d.mts +2 -0
  56. package/esm/ai/reports/runs.mjs +212 -0
  57. package/esm/ai/reports/runs.mjs.map +1 -0
  58. package/esm/ai/reports/service.mjs +132 -0
  59. package/esm/ai/reports/service.mjs.map +1 -0
  60. package/esm/ai/rollup/cascade-store.mjs +84 -0
  61. package/esm/ai/rollup/cascade-store.mjs.map +1 -0
  62. package/esm/ai/rollup/categories.mjs +67 -0
  63. package/esm/ai/rollup/categories.mjs.map +1 -0
  64. package/esm/ai/rollup/extract.mjs +225 -0
  65. package/esm/ai/rollup/extract.mjs.map +1 -0
  66. package/esm/ai/rollup/file-store.mjs +147 -0
  67. package/esm/ai/rollup/file-store.mjs.map +1 -0
  68. package/esm/ai/rollup/histogram.mjs +42 -0
  69. package/esm/ai/rollup/histogram.mjs.map +1 -0
  70. package/esm/ai/rollup/increment-error.mjs +19 -0
  71. package/esm/ai/rollup/increment-error.mjs.map +1 -0
  72. package/esm/ai/rollup/index.mjs +9 -0
  73. package/esm/ai/rollup/mapping.mjs +69 -0
  74. package/esm/ai/rollup/mapping.mjs.map +1 -0
  75. package/esm/ai/rollup/memory-store.mjs +26 -0
  76. package/esm/ai/rollup/memory-store.mjs.map +1 -0
  77. package/esm/ai/rollup/writer.mjs +113 -0
  78. package/esm/ai/rollup/writer.mjs.map +1 -0
  79. package/esm/ai/types.d.mts +29 -0
  80. package/esm/ai/types.d.mts.map +1 -0
  81. package/esm/app-versions.mjs +74 -0
  82. package/esm/app-versions.mjs.map +1 -0
  83. package/esm/devtools-connector.d.mts.map +1 -1
  84. package/esm/devtools-connector.mjs +54 -2
  85. package/esm/devtools-connector.mjs.map +1 -1
  86. package/esm/index.d.mts +3 -2
  87. package/esm/options.mjs +4 -0
  88. package/esm/options.mjs.map +1 -1
  89. package/esm/production/auth/helpers.mjs +8 -5
  90. package/esm/production/auth/helpers.mjs.map +1 -1
  91. package/esm/production/auth/service.mjs +14 -6
  92. package/esm/production/auth/service.mjs.map +1 -1
  93. package/esm/production/boot.mjs +70 -3
  94. package/esm/production/boot.mjs.map +1 -1
  95. package/esm/production/contracts.d.mts +378 -2
  96. package/esm/production/contracts.d.mts.map +1 -1
  97. package/esm/production/contracts.mjs +64 -2
  98. package/esm/production/contracts.mjs.map +1 -1
  99. package/esm/production/errors.d.mts +1 -1
  100. package/esm/production/errors.mjs +11 -3
  101. package/esm/production/errors.mjs.map +1 -1
  102. package/esm/production/http/access.mjs +6 -0
  103. package/esm/production/http/access.mjs.map +1 -1
  104. package/esm/production/http/mount.mjs +13 -0
  105. package/esm/production/http/mount.mjs.map +1 -1
  106. package/esm/production/http/share-session.mjs.map +1 -1
  107. package/esm/production/index.d.mts +2 -2
  108. package/esm/production/insights/writer.mjs.map +1 -1
  109. package/esm/production/options.d.mts +5 -1
  110. package/esm/production/options.d.mts.map +1 -1
  111. package/esm/production/options.mjs +13 -1
  112. package/esm/production/options.mjs.map +1 -1
  113. package/esm/production/store/memory-store.mjs.map +1 -1
  114. package/esm/production/store/migrations.d.mts +1 -1
  115. package/esm/production/store/migrations.d.mts.map +1 -1
  116. package/esm/production/store/migrations.mjs +4 -2
  117. package/esm/production/store/migrations.mjs.map +1 -1
  118. package/esm/production/store/models/ai-rollup.migration.mjs +48 -0
  119. package/esm/production/store/models/ai-rollup.migration.mjs.map +1 -0
  120. package/esm/production/store/models/ai-rollup.model.mjs +13 -0
  121. package/esm/production/store/models/ai-rollup.model.mjs.map +1 -0
  122. package/esm/production/store/models/index.mjs +3 -1
  123. package/esm/server/ai-report-routes.mjs +72 -0
  124. package/esm/server/ai-report-routes.mjs.map +1 -0
  125. package/esm/server/ai-routes.mjs +41 -6
  126. package/esm/server/ai-routes.mjs.map +1 -1
  127. package/esm/server/index.mjs +2 -0
  128. package/esm/server/index.mjs.map +1 -1
  129. package/esm/server/session-routes.mjs +3 -1
  130. package/esm/server/session-routes.mjs.map +1 -1
  131. package/esm/sources/agent-trace-source.d.mts.map +1 -1
  132. package/esm/sources/agent-trace-source.mjs.map +1 -1
  133. package/esm/sources/ai-source.d.mts +2 -0
  134. package/esm/sources/ai-source.d.mts.map +1 -1
  135. package/esm/sources/ai-source.mjs +120 -11
  136. package/esm/sources/ai-source.mjs.map +1 -1
  137. package/esm/types.d.mts +23 -4
  138. package/esm/types.d.mts.map +1 -1
  139. package/llms-full.txt +79 -32
  140. package/package.json +8 -8
  141. package/skills/SKILL.md +79 -32
  142. package/ui/dashboard/assets/app.css +1 -1
  143. package/ui/dashboard/assets/app.js +23 -16
  144. package/ui/dashboard/build-info.json +7 -7
  145. package/cjs/ai-source-DTpxumMA.cjs +0 -381
  146. package/cjs/ai-source-DTpxumMA.cjs.map +0 -1
  147. package/cjs/auth-DV2GA1A9.cjs.map +0 -1
  148. package/cjs/boot-CyeHPFtk.cjs.map +0 -1
  149. package/cjs/cascade-store-DEGxAFDI.cjs.map +0 -1
  150. package/cjs/contracts-CDuY-ahl.cjs +0 -116
  151. package/cjs/contracts-CDuY-ahl.cjs.map +0 -1
  152. package/cjs/errors-DEqdWaqm.cjs.map +0 -1
  153. package/cjs/http-XNLYU2vS.cjs.map +0 -1
  154. package/cjs/migrations-DTTzCNpR.cjs.map +0 -1
  155. package/cjs/options-CHhmQJic.cjs +0 -193
  156. package/cjs/options-CHhmQJic.cjs.map +0 -1
  157. package/cjs/panels-CHd20RK5.cjs +0 -385
  158. package/cjs/panels-CHd20RK5.cjs.map +0 -1
  159. package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +0 -52
  160. package/cjs/server-C8JfggQU.cjs.map +0 -1
  161. package/cjs/src-DjOUdhKc.cjs.map +0 -1
  162. package/cjs/stream-route-D4k-sJvW.cjs.map +0 -1
@@ -0,0 +1,1342 @@
1
+ const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
2
+ const require_errors = require("./errors-DNQ-g49I.cjs");
3
+ const require_extract = require("./extract-8kaX_cUV.cjs");
4
+ const require_ip = require("./ip-DbNhPOzi.cjs");
5
+ let node_path = require("node:path");
6
+ node_path = require_app_versions.__toESM(node_path, 1);
7
+ let node_fs_promises = require("node:fs/promises");
8
+
9
+ //#region ../../packages/devtools/src/ai/options.ts
10
+ /** Default `retentionDays` per mode. */
11
+ const DEVTOOLS_AI_RETENTION_DAYS = {
12
+ development: 30,
13
+ production: 90
14
+ };
15
+ /** Default `flushIntervalMs`. */
16
+ const DEVTOOLS_AI_FLUSH_INTERVAL_MS = 6e4;
17
+ /**
18
+ * Applies the defaults of `devtools.ai` for `mode`. Throws an `Error` naming
19
+ * the option when `retentionDays` is not a whole number from 1 to 400 or
20
+ * `flushIntervalMs` is below 5000 (the same style as `resolveDevtoolsOptions`).
21
+ */
22
+ function resolveDevtoolsAiOptions(options, mode) {
23
+ const reports = options?.reports ?? true;
24
+ const retentionDays = options?.retentionDays ?? DEVTOOLS_AI_RETENTION_DAYS[mode];
25
+ const flushIntervalMs = options?.flushIntervalMs ?? 6e4;
26
+ if (typeof reports !== "boolean") throw new Error("Devtools option \"ai.reports\" must be true or false.");
27
+ if (!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 400) throw new Error("Devtools option \"ai.retentionDays\" must be a whole number from 1 to 400.");
28
+ if (typeof flushIntervalMs !== "number" || !Number.isFinite(flushIntervalMs) || flushIntervalMs < 5e3) throw new Error("Devtools option \"ai.flushIntervalMs\" must be at least 5000.");
29
+ return {
30
+ reports,
31
+ retentionDays,
32
+ flushIntervalMs,
33
+ mode
34
+ };
35
+ }
36
+
37
+ //#endregion
38
+ //#region ../../packages/devtools/src/production/options.ts
39
+ /** The defaults `resolveProductionOptions` applies (environment values excluded). */
40
+ const DEVTOOLS_PRODUCTION_DEFAULTS = {
41
+ sampleRate: .1,
42
+ slowRequestMs: 1e3,
43
+ slowQueryMs: 200,
44
+ maxRequests: 200,
45
+ maxQueriesPerRequest: 200,
46
+ maxShapes: 500,
47
+ maxRoutes: 300,
48
+ maxErrorGroups: 100,
49
+ requestRetentionHours: 24,
50
+ maxStoredSamplesPerMinute: 120,
51
+ reportIntervalMs: 1e4,
52
+ requireHttps: true,
53
+ session: {
54
+ idleMinutes: 30,
55
+ maxHours: 8,
56
+ pendingMinutes: 10
57
+ },
58
+ twoFactor: "admins",
59
+ passwords: {
60
+ minLength: 8,
61
+ rejectCommon: true
62
+ },
63
+ rateLimits: {
64
+ windowMinutes: 15,
65
+ account: 5,
66
+ ip: 20,
67
+ global: 100,
68
+ lockMinutes: 15
69
+ },
70
+ explain: { executing: false },
71
+ logLevels: ["warn", "error"],
72
+ auditRetentionDays: 90,
73
+ passkeys: { rpName: "Warlock monitor" },
74
+ share: {
75
+ enabled: false,
76
+ maxDays: 30
77
+ }
78
+ };
79
+ /** The environment variables production mode reads. */
80
+ const DEVTOOLS_ENV = {
81
+ path: "DEVTOOLS_PATH",
82
+ adminEmail: "DEVTOOLS_ADMIN_EMAIL",
83
+ adminPassword: "DEVTOOLS_ADMIN_PASSWORD",
84
+ setupToken: "DEVTOOLS_SETUP_TOKEN"
85
+ };
86
+ const LOG_LEVELS = [
87
+ "debug",
88
+ "info",
89
+ "warn",
90
+ "error",
91
+ "success"
92
+ ];
93
+ const PATH_CHARACTERS = /^[A-Za-z0-9._~/-]+$/;
94
+ const MIN_PATH_LENGTH = 8;
95
+ const MIN_SETUP_TOKEN_LENGTH = 32;
96
+ function invalid(option, expected) {
97
+ throw new require_errors.DevtoolsProductionConfigError("DT007", `Option "devtools.production.${option}" is not valid: ${expected}.`);
98
+ }
99
+ function present(value) {
100
+ return value === void 0 || value === "" ? null : value;
101
+ }
102
+ function integerAtLeastOne(option, value, fallback) {
103
+ if (value === void 0) return fallback;
104
+ if (!Number.isInteger(value) || value < 1) invalid(option, "use a whole number of 1 or more");
105
+ return value;
106
+ }
107
+ function networkList(option, value) {
108
+ if (value === void 0) return [];
109
+ if (!Array.isArray(value)) invalid(option, "use a list of IPs, CIDR ranges, \"loopback\" or \"private\"");
110
+ for (const entry of value) if (!require_ip.isValidNetworkEntry(entry)) invalid(option, `"${String(entry)}" is not an IP, a CIDR range, "loopback" or "private"`);
111
+ return [...value];
112
+ }
113
+ /** The dashboard path without a trailing slash, or a DT001/DT002 error. */
114
+ function resolvePath(value) {
115
+ const given = present(value);
116
+ if (given === null) throw new require_errors.DevtoolsProductionConfigError("DT001");
117
+ const path = given.replace(/\/+$/, "");
118
+ const segments = path.split("/").slice(1);
119
+ const lower = path.toLowerCase();
120
+ if (!path.startsWith("/") || path.length < MIN_PATH_LENGTH || !PATH_CHARACTERS.test(path) || segments.some((segment) => segment === "" || segment === "." || segment === "..") || lower === "/__warlock" || lower.startsWith("/__warlock/")) throw new require_errors.DevtoolsProductionConfigError("DT002");
121
+ return path;
122
+ }
123
+ /**
124
+ * Applies the defaults to `options`, reads the path and first admin from
125
+ * `env`, and validates everything.
126
+ *
127
+ * Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),
128
+ * DT007 (an option out of range: sampleRate outside 0–1, share.maxDays outside 1–365, a non-positive
129
+ * limit, an unknown twoFactor value, a bad CIDR, an origin that is not
130
+ * `https://host[:port]`), DT009 (both a password and a setup token), DT010
131
+ * (setup token shorter than 32 characters). DT003/DT004 (admin) are checked
132
+ * later by `ensureFirstAdmin`, which needs the database.
133
+ */
134
+ function resolveProductionOptions(options, env) {
135
+ const given = options ?? {};
136
+ const defaults = DEVTOOLS_PRODUCTION_DEFAULTS;
137
+ const path = resolvePath(given.path ?? env[DEVTOOLS_ENV.path]);
138
+ const sampleRate = given.sampleRate ?? defaults.sampleRate;
139
+ if (typeof sampleRate !== "number" || !Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) invalid("sampleRate", "use a number from 0 to 1");
140
+ const requireHttps = given.requireHttps ?? defaults.requireHttps;
141
+ if (typeof requireHttps !== "boolean") invalid("requireHttps", "use true or false");
142
+ const twoFactor = given.twoFactor ?? defaults.twoFactor;
143
+ if (twoFactor !== "off" && twoFactor !== "admins" && twoFactor !== "everyone") invalid("twoFactor", "use \"off\", \"admins\" or \"everyone\"");
144
+ const minLength = given.passwords?.minLength ?? defaults.passwords.minLength;
145
+ if (!Number.isInteger(minLength) || minLength < 8 || minLength > 72) invalid("passwords.minLength", "use a whole number from 8 to 72 (passwords are limited to 72 bytes, so a longer minimum would refuse every password)");
146
+ const rejectCommon = given.passwords?.rejectCommon ?? defaults.passwords.rejectCommon;
147
+ if (typeof rejectCommon !== "boolean") invalid("passwords.rejectCommon", "use true or false");
148
+ const origin = given.origin ?? null;
149
+ if (origin !== null) {
150
+ if (typeof origin !== "string" || !(requireHttps ? /^https:\/\/[^/\s]+$/ : /^https?:\/\/[^/\s]+$/).test(origin)) invalid("origin", requireHttps ? "use an origin such as https://app.example.com, without a path or a trailing slash" : "use an origin such as http://localhost:3000, without a path or a trailing slash");
151
+ }
152
+ const panels = given.panels ?? {};
153
+ if (panels === null || typeof panels !== "object" || Array.isArray(panels)) invalid("panels", "use an object of tab ids and true or false");
154
+ for (const [id, enabled] of Object.entries(panels)) if (typeof enabled !== "boolean") invalid(`panels.${id}`, "use true or false");
155
+ const logLevels = given.logLevels ?? defaults.logLevels;
156
+ if (!Array.isArray(logLevels) || logLevels.some((level) => !LOG_LEVELS.includes(level))) invalid("logLevels", `use a list of ${LOG_LEVELS.join(", ")}`);
157
+ const executing = given.explain?.executing ?? defaults.explain.executing;
158
+ if (typeof executing !== "boolean") invalid("explain.executing", "use true or false");
159
+ const rpName = given.passkeys?.rpName ?? defaults.passkeys.rpName;
160
+ const rpId = given.passkeys?.rpId ?? null;
161
+ if (typeof rpName !== "string" || rpName.trim() === "") invalid("passkeys.rpName", "use a non-empty name");
162
+ if (rpId !== null && (typeof rpId !== "string" || rpId.trim() === "")) invalid("passkeys.rpId", "use a host name such as app.example.com");
163
+ const shareEnabled = given.share?.enabled ?? defaults.share.enabled;
164
+ const shareMaxDays = given.share?.maxDays ?? defaults.share.maxDays;
165
+ if (typeof shareEnabled !== "boolean") invalid("share.enabled", "use true or false");
166
+ if (!Number.isInteger(shareMaxDays) || shareMaxDays < 1 || shareMaxDays > 365) invalid("share.maxDays", "use a whole number of days from 1 to 365");
167
+ const limits = given.rateLimits ?? {};
168
+ const session = given.session ?? {};
169
+ const resolved = {
170
+ path,
171
+ admin: {
172
+ email: present(env[DEVTOOLS_ENV.adminEmail]),
173
+ password: present(env[DEVTOOLS_ENV.adminPassword]),
174
+ setupToken: present(env[DEVTOOLS_ENV.setupToken])
175
+ },
176
+ sampleRate,
177
+ slowRequestMs: integerAtLeastOne("slowRequestMs", given.slowRequestMs, defaults.slowRequestMs),
178
+ slowQueryMs: integerAtLeastOne("slowQueryMs", given.slowQueryMs, defaults.slowQueryMs),
179
+ maxRequests: integerAtLeastOne("maxRequests", given.maxRequests, defaults.maxRequests),
180
+ maxQueriesPerRequest: defaults.maxQueriesPerRequest,
181
+ maxShapes: defaults.maxShapes,
182
+ maxRoutes: defaults.maxRoutes,
183
+ maxErrorGroups: defaults.maxErrorGroups,
184
+ requestRetentionHours: integerAtLeastOne("requestRetentionHours", given.requestRetentionHours, defaults.requestRetentionHours),
185
+ maxStoredSamplesPerMinute: integerAtLeastOne("maxStoredSamplesPerMinute", given.maxStoredSamplesPerMinute, defaults.maxStoredSamplesPerMinute),
186
+ reportIntervalMs: integerAtLeastOne("reportIntervalMs", given.reportIntervalMs, defaults.reportIntervalMs),
187
+ trustedProxies: networkList("trustedProxies", given.trustedProxies),
188
+ requireHttps,
189
+ allowedIps: networkList("allowedIps", given.allowedIps),
190
+ origin,
191
+ session: {
192
+ idleMinutes: integerAtLeastOne("session.idleMinutes", session.idleMinutes, defaults.session.idleMinutes),
193
+ maxHours: integerAtLeastOne("session.maxHours", session.maxHours, defaults.session.maxHours),
194
+ pendingMinutes: defaults.session.pendingMinutes
195
+ },
196
+ twoFactor,
197
+ passwords: {
198
+ minLength,
199
+ rejectCommon
200
+ },
201
+ rateLimits: {
202
+ windowMinutes: integerAtLeastOne("rateLimits.windowMinutes", limits.windowMinutes, defaults.rateLimits.windowMinutes),
203
+ account: integerAtLeastOne("rateLimits.account", limits.account, defaults.rateLimits.account),
204
+ ip: integerAtLeastOne("rateLimits.ip", limits.ip, defaults.rateLimits.ip),
205
+ global: integerAtLeastOne("rateLimits.global", limits.global, defaults.rateLimits.global),
206
+ lockMinutes: integerAtLeastOne("rateLimits.lockMinutes", limits.lockMinutes, defaults.rateLimits.lockMinutes)
207
+ },
208
+ explain: { executing },
209
+ panels: { ...panels },
210
+ logLevels: [...logLevels],
211
+ auditRetentionDays: integerAtLeastOne("auditRetentionDays", given.auditRetentionDays, defaults.auditRetentionDays),
212
+ passkeys: {
213
+ rpName,
214
+ rpId
215
+ },
216
+ share: {
217
+ enabled: shareEnabled,
218
+ maxDays: shareMaxDays
219
+ }
220
+ };
221
+ if (resolved.admin.password !== null && resolved.admin.setupToken !== null) throw new require_errors.DevtoolsProductionConfigError("DT009");
222
+ if (resolved.admin.setupToken !== null && resolved.admin.setupToken.length < MIN_SETUP_TOKEN_LENGTH) throw new require_errors.DevtoolsProductionConfigError("DT010");
223
+ return resolved;
224
+ }
225
+
226
+ //#endregion
227
+ //#region ../../packages/devtools/src/ai/reports/aggregate.ts
228
+ /**
229
+ * Pure folds from rollup rows (stored records plus pending deltas) to the
230
+ * report shapes in `production/contracts.ts`. No I/O, no clock.
231
+ */
232
+ const MAX_NAMED_SERIES = 5;
233
+ const OTHER_KEY = "__other";
234
+ /** `provider/model`, the key the UI filters and colours models by. */
235
+ function modelKey(row) {
236
+ return `${row.provider}/${row.model}`;
237
+ }
238
+ /** Sums rows into totals (latency from the merged histogram). */
239
+ function totalsOf(rows) {
240
+ const totals = {
241
+ runs: 0,
242
+ completed: 0,
243
+ failed: 0,
244
+ incomplete: 0,
245
+ cancelled: 0,
246
+ errorRate: 0,
247
+ tokens: {
248
+ input: 0,
249
+ output: 0,
250
+ cached: 0,
251
+ cacheWrite: 0,
252
+ reasoning: 0
253
+ },
254
+ cost: {
255
+ estimatedUsd: 0,
256
+ pricedRuns: 0,
257
+ unpricedRuns: 0,
258
+ unpricedTokens: 0
259
+ },
260
+ latency: {
261
+ p50Ms: null,
262
+ p95Ms: null,
263
+ meanMs: null
264
+ },
265
+ fallbackRuns: 0,
266
+ refusals: 0
267
+ };
268
+ const histogram = require_extract.emptyAiLatency();
269
+ let latencyCount = 0;
270
+ let latencySumMs = 0;
271
+ for (const row of rows) {
272
+ totals.runs += row.runs;
273
+ totals.completed += row.completed;
274
+ totals.failed += row.failed;
275
+ totals.incomplete += row.incomplete;
276
+ totals.cancelled += row.cancelled;
277
+ totals.tokens.input += row.inputTokens;
278
+ totals.tokens.output += row.outputTokens;
279
+ totals.tokens.cached += row.cachedTokens;
280
+ totals.tokens.cacheWrite += row.cacheWriteTokens;
281
+ totals.tokens.reasoning += row.reasoningTokens;
282
+ totals.cost.estimatedUsd += row.costUsd;
283
+ totals.cost.pricedRuns += row.pricedRuns;
284
+ totals.cost.unpricedRuns += row.unpricedRuns;
285
+ totals.cost.unpricedTokens += row.unpricedTokens;
286
+ totals.fallbackRuns += row.fallbackRuns;
287
+ totals.refusals += row.refusals;
288
+ require_extract.addAiLatency(histogram, row.latency);
289
+ latencyCount += row.latencyCount;
290
+ latencySumMs += row.latencySumMs;
291
+ }
292
+ totals.errorRate = totals.runs > 0 ? (totals.failed + totals.incomplete) / totals.runs : 0;
293
+ totals.latency = {
294
+ p50Ms: require_extract.aiLatencyQuantile(histogram, .5),
295
+ p95Ms: require_extract.aiLatencyQuantile(histogram, .95),
296
+ meanMs: latencyCount > 0 ? latencySumMs / latencyCount : null
297
+ };
298
+ return totals;
299
+ }
300
+ /** The bucket index of an hour inside `range` (`-1` outside). */
301
+ function bucketOf(hour, range) {
302
+ if (hour < range.from || hour >= range.to) return -1;
303
+ return Math.floor((hour - range.from) / range.stepMs);
304
+ }
305
+ /** Bucket starts of a range, oldest first. */
306
+ function bucketStarts(range) {
307
+ const count = Math.max(0, Math.ceil((range.to - range.from) / range.stepMs));
308
+ return Array.from({ length: count }, (_, index) => range.from + index * range.stepMs);
309
+ }
310
+ /** Top five keys by sum become series, the rest are summed into `__other`. */
311
+ function buildSeries(range, entries) {
312
+ const buckets = bucketStarts(range);
313
+ const byKey = /* @__PURE__ */ new Map();
314
+ for (const entry of entries) {
315
+ if (entry.bucket < 0 || entry.bucket >= buckets.length) continue;
316
+ let item = byKey.get(entry.key);
317
+ if (!item) {
318
+ item = {
319
+ label: entry.label,
320
+ sum: 0,
321
+ values: new Array(buckets.length).fill(0)
322
+ };
323
+ byKey.set(entry.key, item);
324
+ }
325
+ item.values[entry.bucket] = (item.values[entry.bucket] ?? 0) + entry.value;
326
+ item.sum += entry.value;
327
+ }
328
+ const ranked = [...byKey.entries()].sort((a, b) => b[1].sum - a[1].sum || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
329
+ const series = ranked.slice(0, MAX_NAMED_SERIES).map(([key, item]) => ({
330
+ key,
331
+ label: item.label,
332
+ values: item.values,
333
+ other: false
334
+ }));
335
+ const rest = ranked.slice(MAX_NAMED_SERIES);
336
+ if (rest.length > 0) {
337
+ const values = new Array(buckets.length).fill(0);
338
+ for (const [, item] of rest) item.values.forEach((value, index) => {
339
+ values[index] = (values[index] ?? 0) + value;
340
+ });
341
+ series.push({
342
+ key: OTHER_KEY,
343
+ label: "Other",
344
+ values,
345
+ other: true
346
+ });
347
+ }
348
+ return {
349
+ buckets,
350
+ series
351
+ };
352
+ }
353
+ /**
354
+ * A stacked series set: `value(row)` per bucket, grouped by `keyOf(row)`; the
355
+ * five keys with the largest sum are named, the rest summed into `other`
356
+ * (key `__other`, label "Other"). Buckets with no rows are 0.
357
+ */
358
+ function seriesBy(rows, range, keyOf, labelOf, value) {
359
+ return buildSeries(range, rows.map((row) => {
360
+ const key = keyOf(row);
361
+ return {
362
+ bucket: bucketOf(row.hour, range),
363
+ key,
364
+ label: labelOf(key),
365
+ value: value(row)
366
+ };
367
+ }));
368
+ }
369
+ /** Tokens per bucket: `uncached` (input − cached), `cached`, `output`. */
370
+ function tokenSeries(rows, range) {
371
+ const buckets = bucketStarts(range);
372
+ const uncached = new Array(buckets.length).fill(0);
373
+ const cached = new Array(buckets.length).fill(0);
374
+ const output = new Array(buckets.length).fill(0);
375
+ for (const row of rows) {
376
+ const bucket = bucketOf(row.hour, range);
377
+ if (bucket < 0 || bucket >= buckets.length) continue;
378
+ uncached[bucket] = (uncached[bucket] ?? 0) + Math.max(0, row.inputTokens - row.cachedTokens);
379
+ cached[bucket] = (cached[bucket] ?? 0) + row.cachedTokens;
380
+ output[bucket] = (output[bucket] ?? 0) + row.outputTokens;
381
+ }
382
+ return {
383
+ buckets,
384
+ series: [
385
+ {
386
+ key: "uncached",
387
+ label: "Uncached input",
388
+ values: uncached,
389
+ other: false
390
+ },
391
+ {
392
+ key: "cached",
393
+ label: "Cached input",
394
+ values: cached,
395
+ other: false
396
+ },
397
+ {
398
+ key: "output",
399
+ label: "Output",
400
+ values: output,
401
+ other: false
402
+ }
403
+ ]
404
+ };
405
+ }
406
+ /** The error rate per bucket; `rate: null` where a bucket has no runs. */
407
+ function errorRateSeries(rows, range) {
408
+ const points = bucketStarts(range).map((at) => ({
409
+ at,
410
+ runs: 0,
411
+ errors: 0,
412
+ rate: null
413
+ }));
414
+ for (const row of rows) {
415
+ const point = points[bucketOf(row.hour, range)];
416
+ if (!point) continue;
417
+ point.runs += row.runs;
418
+ point.errors += row.failed + row.incomplete;
419
+ }
420
+ for (const point of points) point.rate = point.runs > 0 ? point.errors / point.runs : null;
421
+ return points;
422
+ }
423
+ /** Failed runs per bucket by category (top five plus Other). */
424
+ function errorSeries(rows, range) {
425
+ const entries = [];
426
+ for (const row of rows) {
427
+ const bucket = bucketOf(row.hour, range);
428
+ for (const category of require_errors.DEVTOOLS_AI_ERROR_CATEGORIES) {
429
+ const value = row.errors[category];
430
+ if (value > 0) entries.push({
431
+ bucket,
432
+ key: category,
433
+ label: require_extract.DEVTOOLS_AI_ERROR_LABELS[category],
434
+ value
435
+ });
436
+ }
437
+ }
438
+ return buildSeries(range, entries);
439
+ }
440
+ function groupRows(rows, keyOf) {
441
+ const groups = /* @__PURE__ */ new Map();
442
+ for (const row of rows) {
443
+ const key = keyOf(row);
444
+ const group = groups.get(key);
445
+ if (group) group.push(row);
446
+ else groups.set(key, [row]);
447
+ }
448
+ return groups;
449
+ }
450
+ const byKey = (a, b) => a < b ? -1 : a > b ? 1 : 0;
451
+ /** Top rows by estimated cost (by runs when nothing was priced), at most `limit`. */
452
+ function breakdown(rows, by, limit) {
453
+ const items = [...groupRows(rows, (row) => by === "agent" ? row.agent : modelKey(row)).entries()].map(([key, group]) => ({
454
+ key,
455
+ group,
456
+ totals: totalsOf(group)
457
+ }));
458
+ const totalCost = items.reduce((sum, item) => sum + item.totals.cost.estimatedUsd, 0);
459
+ const totalRuns = items.reduce((sum, item) => sum + item.totals.runs, 0);
460
+ const byCost = totalCost > 0;
461
+ 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));
462
+ return items.slice(0, limit).map(({ key, group, totals }) => ({
463
+ key,
464
+ label: key,
465
+ provider: by === "model" ? group[0]?.provider ?? null : null,
466
+ totals,
467
+ share: byCost ? totals.cost.estimatedUsd / totalCost : totalRuns > 0 ? totals.runs / totalRuns : 0
468
+ }));
469
+ }
470
+ function pricingOf(totals) {
471
+ const { pricedRuns, unpricedRuns } = totals.cost;
472
+ if (pricedRuns === 0 && unpricedRuns === 0) return "no-tokens";
473
+ if (unpricedRuns === 0) return "set";
474
+ return pricedRuns === 0 ? "missing" : "partial";
475
+ }
476
+ /** One row per `provider/model`, most runs first. */
477
+ function modelRows(rows) {
478
+ const result = [];
479
+ for (const [key, group] of groupRows(rows, modelKey)) {
480
+ const totals = totalsOf(group);
481
+ const runsByAgent = /* @__PURE__ */ new Map();
482
+ let lastSeenAt = 0;
483
+ for (const row of group) {
484
+ runsByAgent.set(row.agent, (runsByAgent.get(row.agent) ?? 0) + row.runs);
485
+ if (row.runs > 0 && row.hour > lastSeenAt) lastSeenAt = row.hour;
486
+ }
487
+ const first = group[0];
488
+ result.push({
489
+ key,
490
+ model: first?.model ?? "",
491
+ provider: first?.provider ?? "",
492
+ totals,
493
+ pricing: pricingOf(totals),
494
+ costPerRunUsd: totals.cost.pricedRuns > 0 ? totals.cost.estimatedUsd / totals.cost.pricedRuns : null,
495
+ fallbackRate: totals.runs > 0 ? totals.fallbackRuns / totals.runs : 0,
496
+ agents: [...runsByAgent.entries()].sort((a, b) => b[1] - a[1] || byKey(a[0], b[0])).slice(0, 5).map(([agent]) => agent),
497
+ lastSeenAt
498
+ });
499
+ }
500
+ return result.sort((a, b) => b.totals.runs - a.totals.runs || byKey(a.key, b.key));
501
+ }
502
+ function countErrors(rows, category) {
503
+ return rows.reduce((sum, row) => sum + row.errors[category], 0);
504
+ }
505
+ function topCounts(rows, category, keyOf) {
506
+ const counts = /* @__PURE__ */ new Map();
507
+ for (const row of rows) {
508
+ const count = row.errors[category];
509
+ if (count > 0) counts.set(keyOf(row), (counts.get(keyOf(row)) ?? 0) + count);
510
+ }
511
+ return [...counts.entries()].sort((a, b) => b[1] - a[1] || byKey(a[0], b[0])).slice(0, 5).map(([key, count]) => ({
512
+ key,
513
+ count
514
+ }));
515
+ }
516
+ /** Categories with at least one error, most first, with `previousCount` from `previousRows`. */
517
+ function errorGroups(rows, previousRows) {
518
+ const counted = require_errors.DEVTOOLS_AI_ERROR_CATEGORIES.map((category) => ({
519
+ category,
520
+ count: countErrors(rows, category)
521
+ }));
522
+ const total = counted.reduce((sum, item) => sum + item.count, 0);
523
+ return counted.filter((item) => item.count > 0).sort((a, b) => b.count - a.count).map(({ category, count }) => ({
524
+ category,
525
+ label: require_extract.DEVTOOLS_AI_ERROR_LABELS[category],
526
+ count,
527
+ share: total > 0 ? count / total : 0,
528
+ previousCount: countErrors(previousRows, category),
529
+ byModel: topCounts(rows, category, modelKey),
530
+ byAgent: topCounts(rows, category, (row) => row.agent)
531
+ }));
532
+ }
533
+ /** The distinct agents, models and providers, sorted. */
534
+ function filterOptions(rows) {
535
+ const agents = /* @__PURE__ */ new Set();
536
+ const models = /* @__PURE__ */ new Set();
537
+ const providers = /* @__PURE__ */ new Set();
538
+ for (const row of rows) {
539
+ agents.add(row.agent);
540
+ models.add(modelKey(row));
541
+ providers.add(row.provider);
542
+ }
543
+ return {
544
+ agents: [...agents].sort(byKey),
545
+ models: [...models].sort(byKey),
546
+ providers: [...providers].sort(byKey)
547
+ };
548
+ }
549
+
550
+ //#endregion
551
+ //#region ../../packages/devtools/src/ai/reports/range.ts
552
+ const HOUR_MS$1 = 36e5;
553
+ const DAY_MS$2 = 24 * HOUR_MS$1;
554
+ const MAX_FILTER_LENGTH = 200;
555
+ const PRESETS = {
556
+ "24h": {
557
+ length: DAY_MS$2,
558
+ step: HOUR_MS$1
559
+ },
560
+ "7d": {
561
+ length: 7 * DAY_MS$2,
562
+ step: 6 * HOUR_MS$1
563
+ },
564
+ "30d": {
565
+ length: 30 * DAY_MS$2,
566
+ step: DAY_MS$2
567
+ }
568
+ };
569
+ /**
570
+ * Parses and aligns a range:
571
+ *
572
+ * - `24h`: `to` = the next hour boundary after `now`, `from` = `to - 24h`, step 1 hour.
573
+ * - `7d`: `to` as above, `from` = `to - 7d`, step 6 hours.
574
+ * - `30d`: `to` = the next local midnight (by `tz`, rounded down to whole
575
+ * hours), `from` = `to - 30d`, step 1 day.
576
+ * - `custom`: `from` floored and `to` ceiled to hours; at least 1 hour, `from`
577
+ * no older than `retentionDays`, `to` no later than the next hour; step 1
578
+ * hour up to 48 hours, 6 hours up to 8 days, else 1 day (then widened to
579
+ * local midnights, as for `30d`).
580
+ *
581
+ * `previous` is the same length just before `from`; `previousComplete` is
582
+ * `false` when it starts before the retention cut-off. Filters longer than 200
583
+ * characters, an unknown preset, a malformed number or a range outside the
584
+ * rules throw `DevtoolsApiError("ai.range-invalid")`.
585
+ */
586
+ function parseAiReportQuery(query, options) {
587
+ const { now, retentionDays } = options;
588
+ const utcOffsetMinutes = parseOffset(query.tz);
589
+ const nextHour = (Math.floor(now / HOUR_MS$1) + 1) * HOUR_MS$1;
590
+ const offsetMs = Math.floor(utcOffsetMinutes / 60) * HOUR_MS$1;
591
+ const localMidnight = (at, round) => round((at + offsetMs) / DAY_MS$2) * DAY_MS$2 - offsetMs;
592
+ const preset = query.range === void 0 || query.range === "" ? "24h" : query.range;
593
+ let from;
594
+ let to;
595
+ let stepMs;
596
+ if (preset === "24h" || preset === "7d") {
597
+ to = nextHour;
598
+ from = to - PRESETS[preset].length;
599
+ stepMs = PRESETS[preset].step;
600
+ } else if (preset === "30d") {
601
+ to = (Math.floor((now + offsetMs) / DAY_MS$2) + 1) * DAY_MS$2 - offsetMs;
602
+ from = to - PRESETS["30d"].length;
603
+ stepMs = PRESETS["30d"].step;
604
+ } else if (preset === "custom") {
605
+ const rawFrom = parseEpoch(query.from);
606
+ const rawTo = parseEpoch(query.to);
607
+ if (rawTo <= rawFrom) throw new require_errors.DevtoolsApiError("ai.range-invalid");
608
+ from = Math.floor(rawFrom / HOUR_MS$1) * HOUR_MS$1;
609
+ to = Math.ceil(rawTo / HOUR_MS$1) * HOUR_MS$1;
610
+ const oldest = Math.floor(now / HOUR_MS$1) * HOUR_MS$1 - retentionDays * DAY_MS$2;
611
+ if (from < oldest || to > nextHour) throw new require_errors.DevtoolsApiError("ai.range-invalid");
612
+ const length = to - from;
613
+ stepMs = length <= 48 * HOUR_MS$1 ? HOUR_MS$1 : length <= 8 * DAY_MS$2 ? 6 * HOUR_MS$1 : DAY_MS$2;
614
+ if (stepMs === DAY_MS$2) {
615
+ from = Math.max(localMidnight(from, Math.floor), localMidnight(oldest, Math.ceil));
616
+ to = localMidnight(to, Math.ceil);
617
+ }
618
+ } else throw new require_errors.DevtoolsApiError("ai.range-invalid");
619
+ const agent = parseFilter(query.agent);
620
+ const provider = parseFilter(query.provider);
621
+ const modelKey = parseFilter(query.model);
622
+ let model;
623
+ if (modelKey !== void 0) {
624
+ const slash = modelKey.indexOf("/");
625
+ if (slash <= 0 || slash === modelKey.length - 1) throw new require_errors.DevtoolsApiError("ai.range-invalid");
626
+ model = {
627
+ provider: modelKey.slice(0, slash),
628
+ model: modelKey.slice(slash + 1)
629
+ };
630
+ }
631
+ const previousFrom = from - (to - from);
632
+ return {
633
+ range: {
634
+ preset,
635
+ from,
636
+ to,
637
+ stepMs,
638
+ utcOffsetMinutes
639
+ },
640
+ previous: {
641
+ from: previousFrom,
642
+ to: from
643
+ },
644
+ previousComplete: previousFrom >= Math.floor(now / HOUR_MS$1) * HOUR_MS$1 - retentionDays * DAY_MS$2,
645
+ ...agent === void 0 ? {} : { agent },
646
+ ...model === void 0 ? {} : { model },
647
+ ...provider === void 0 ? {} : { provider }
648
+ };
649
+ }
650
+ function parseOffset(value) {
651
+ if (value === void 0 || value === "") return 0;
652
+ const offset = /^-?\d{1,4}$/.test(value) ? Number(value) : NaN;
653
+ if (!Number.isInteger(offset) || offset < -840 || offset > 840) throw new require_errors.DevtoolsApiError("ai.range-invalid");
654
+ return offset;
655
+ }
656
+ function parseEpoch(value) {
657
+ const epoch = value !== void 0 && /^\d{1,15}$/.test(value) ? Number(value) : NaN;
658
+ if (!Number.isSafeInteger(epoch)) throw new require_errors.DevtoolsApiError("ai.range-invalid");
659
+ return epoch;
660
+ }
661
+ function parseFilter(value) {
662
+ if (value === void 0 || value === "") return void 0;
663
+ if (value.length > MAX_FILTER_LENGTH) throw new require_errors.DevtoolsApiError("ai.range-invalid");
664
+ return value;
665
+ }
666
+
667
+ //#endregion
668
+ //#region ../../packages/devtools/src/ai/reports/service.ts
669
+ const CACHE_MS = 15e3;
670
+ const MAX_CACHE_ENTRIES = 20;
671
+ const TOP_LIMIT = 10;
672
+ const RECENT_LIMIT = 50;
673
+ function createAiReportService(input) {
674
+ const now = input.now ?? Date.now;
675
+ const cache = /* @__PURE__ */ new Map();
676
+ /** The rows of the previous period and the range, stored plus unsaved, before the filters. */
677
+ async function load(parsed) {
678
+ const { range, previous } = parsed;
679
+ const all = [...await input.store.list({
680
+ fromHour: previous.from,
681
+ toHour: range.to
682
+ }), ...input.pending()].filter((row) => row.hour >= previous.from && row.hour < range.to);
683
+ const inRange = all.filter((row) => row.hour >= range.from);
684
+ const matches = (row) => (parsed.agent === void 0 || row.agent === parsed.agent) && (parsed.provider === void 0 || row.provider === parsed.provider) && (parsed.model === void 0 || row.provider === parsed.model.provider && row.model === parsed.model.model);
685
+ return {
686
+ rows: inRange,
687
+ previousRows: all.filter((row) => row.hour < range.from && matches(row)),
688
+ scoped: inRange.filter(matches)
689
+ };
690
+ }
691
+ /** Parses first (so a bad range throws and is never cached), then answers from the cache or `build`. */
692
+ async function answer(view, query, build) {
693
+ const at = now();
694
+ const parsed = parseAiReportQuery(query, {
695
+ now: at,
696
+ retentionDays: input.retentionDays
697
+ });
698
+ const key = `${view}|${JSON.stringify([
699
+ query.range ?? "",
700
+ query.from ?? "",
701
+ query.to ?? "",
702
+ query.tz ?? "",
703
+ query.agent ?? "",
704
+ query.model ?? "",
705
+ query.provider ?? ""
706
+ ])}`;
707
+ const cached = cache.get(key);
708
+ if (cached && at - cached.at < CACHE_MS) return cached.value;
709
+ const value = await build(parsed);
710
+ cache.delete(key);
711
+ cache.set(key, {
712
+ at,
713
+ value
714
+ });
715
+ for (const oldest of cache.keys()) {
716
+ if (cache.size <= MAX_CACHE_ENTRIES) break;
717
+ cache.delete(oldest);
718
+ }
719
+ return value;
720
+ }
721
+ return {
722
+ report: (query) => answer("report", query, async (parsed) => {
723
+ const { rows, previousRows, scoped } = await load(parsed);
724
+ const { range } = parsed;
725
+ const unpriced = /* @__PURE__ */ new Set();
726
+ for (const row of scoped) if (row.unpricedRuns > 0) unpriced.add(`${row.provider}/${row.model}`);
727
+ return {
728
+ available: true,
729
+ range,
730
+ previousRange: parsed.previous,
731
+ previousComplete: parsed.previousComplete,
732
+ totals: totalsOf(scoped),
733
+ previous: totalsOf(previousRows),
734
+ costByModel: seriesBy(scoped, range, (row) => `${row.provider}/${row.model}`, (key) => key, (row) => row.costUsd),
735
+ tokens: tokenSeries(scoped, range),
736
+ errorRate: errorRateSeries(scoped, range),
737
+ topAgents: breakdown(scoped, "agent", TOP_LIMIT),
738
+ topModels: breakdown(scoped, "model", TOP_LIMIT),
739
+ unpricedModels: [...unpriced].sort(),
740
+ filters: filterOptions(rows),
741
+ observationOff: input.observationOff(),
742
+ generatedAt: now()
743
+ };
744
+ }),
745
+ models: (query) => answer("models", query, async (parsed) => {
746
+ const { rows, scoped } = await load(parsed);
747
+ return {
748
+ available: true,
749
+ range: parsed.range,
750
+ totals: totalsOf(scoped),
751
+ models: modelRows(scoped),
752
+ runsByModel: seriesBy(scoped, parsed.range, (row) => `${row.provider}/${row.model}`, (key) => key, (row) => row.runs),
753
+ filters: filterOptions(rows),
754
+ observationOff: input.observationOff(),
755
+ generatedAt: now()
756
+ };
757
+ }),
758
+ async errors(query) {
759
+ const view = await answer("errors", query, async (parsed) => {
760
+ const { rows, previousRows, scoped } = await load(parsed);
761
+ return {
762
+ available: true,
763
+ range: parsed.range,
764
+ totals: totalsOf(scoped),
765
+ previous: totalsOf(previousRows),
766
+ previousComplete: parsed.previousComplete,
767
+ groups: errorGroups(scoped, previousRows),
768
+ overTime: errorSeries(scoped, parsed.range),
769
+ recent: null,
770
+ filters: filterOptions(rows),
771
+ observationOff: input.observationOff(),
772
+ generatedAt: now()
773
+ };
774
+ });
775
+ if (!input.recentFailures) return view;
776
+ const { range, agent, provider, model } = parseAiReportQuery(query, {
777
+ now: now(),
778
+ retentionDays: input.retentionDays
779
+ });
780
+ return {
781
+ ...view,
782
+ recent: input.recentFailures({
783
+ from: range.from,
784
+ to: range.to,
785
+ ...agent === void 0 ? {} : { agent },
786
+ ...provider === void 0 ? {} : { provider },
787
+ ...model === void 0 ? {} : { model }
788
+ }).slice(0, RECENT_LIMIT)
789
+ };
790
+ }
791
+ };
792
+ }
793
+
794
+ //#endregion
795
+ //#region ../../packages/devtools/src/ai/rollup/mapping.ts
796
+ /** The numeric counters and their column names (errors and latency are mapped separately). */
797
+ const COUNTER_COLUMNS = [
798
+ ["runs", "runs"],
799
+ ["completed", "completed"],
800
+ ["failed", "failed"],
801
+ ["incomplete", "incomplete"],
802
+ ["cancelled", "cancelled"],
803
+ ["inputTokens", "input_tokens"],
804
+ ["outputTokens", "output_tokens"],
805
+ ["cachedTokens", "cached_tokens"],
806
+ ["cacheWriteTokens", "cache_write_tokens"],
807
+ ["reasoningTokens", "reasoning_tokens"],
808
+ ["costUsd", "cost_usd"],
809
+ ["pricedRuns", "priced_runs"],
810
+ ["unpricedRuns", "unpriced_runs"],
811
+ ["unpricedTokens", "unpriced_tokens"],
812
+ ["fallbackRuns", "fallback_runs"],
813
+ ["refusals", "refusals"],
814
+ ["latencyCount", "latency_count"],
815
+ ["latencySumMs", "latency_sum_ms"]
816
+ ];
817
+ const BUCKET_COUNT = require_errors.DEVTOOLS_AI_LATENCY_BUCKETS_MS.length + 1;
818
+ /** The column of an error category: `err_` plus the category with dashes as underscores. */
819
+ function errorColumn(category) {
820
+ return `err_${category.replaceAll("-", "_")}`;
821
+ }
822
+ function number(value) {
823
+ const parsed = typeof value === "number" ? value : Number(value);
824
+ return Number.isFinite(parsed) ? parsed : 0;
825
+ }
826
+ /** Every counter column with its amount; counters at 0 are left out. */
827
+ function allCounters(delta) {
828
+ const columns = {};
829
+ for (const [field, column] of COUNTER_COLUMNS) columns[column] = delta[field];
830
+ for (const category of require_errors.DEVTOOLS_AI_ERROR_CATEGORIES) columns[errorColumn(category)] = delta.errors[category] ?? 0;
831
+ for (let index = 0; index < BUCKET_COUNT; index++) columns[`lat_${index}`] = delta.latency[index] ?? 0;
832
+ return columns;
833
+ }
834
+ /** The `$inc` part of a delta: every counter column with its amount (zero counters left out). */
835
+ function deltaToIncrements(delta) {
836
+ const increments = {};
837
+ for (const [column, amount] of Object.entries(allCounters(delta))) if (amount !== 0) increments[column] = amount;
838
+ return increments;
839
+ }
840
+ /** A record from a row; numbers a driver returns as strings are converted. */
841
+ function rowToRecord(row) {
842
+ const record = {
843
+ ...require_extract.emptyRollupDelta({
844
+ hour: number(row.hour),
845
+ agent: String(row.agent ?? ""),
846
+ model: String(row.model ?? ""),
847
+ provider: String(row.provider ?? "")
848
+ }),
849
+ id: String(row.id ?? ""),
850
+ updatedAt: number(row.updated_at)
851
+ };
852
+ for (const [field, column] of COUNTER_COLUMNS) record[field] = number(row[column]);
853
+ for (const category of require_errors.DEVTOOLS_AI_ERROR_CATEGORIES) record.errors[category] = number(row[errorColumn(category)]);
854
+ for (let index = 0; index < BUCKET_COUNT; index++) record.latency[index] = number(row[`lat_${index}`]);
855
+ return record;
856
+ }
857
+
858
+ //#endregion
859
+ //#region ../../packages/devtools/src/ai/rollup/increment-error.ts
860
+ /**
861
+ * Thrown by `DevtoolsAiRollupStore.increment` when only part of the deltas
862
+ * were written. `unwritten` lists the deltas that were not saved, so the
863
+ * writer retries those alone and never adds a saved delta twice. A store that
864
+ * throws any other error is treated as having written nothing.
865
+ */
866
+ var DevtoolsAiRollupIncrementError = class extends Error {
867
+ constructor(unwritten, options) {
868
+ const reason = options.cause instanceof Error ? options.cause.message : String(options.cause);
869
+ super(`${unwritten.length} of ${unwritten.length + options.written} AI totals were not saved (${reason})`, { cause: options.cause });
870
+ this.name = "DevtoolsAiRollupIncrementError";
871
+ this.unwritten = unwritten;
872
+ }
873
+ };
874
+
875
+ //#endregion
876
+ //#region ../../packages/devtools/src/ai/rollup/cascade-store.ts
877
+ /** Rows written in one go; each row is its own atomic statement, so this only bounds open queries. */
878
+ const INCREMENT_CONCURRENCY = 10;
879
+ /**
880
+ * The production `DevtoolsAiRollupStore`: table/collection
881
+ * `devtools_ai_rollups` in the app database through `@warlock.js/cascade`
882
+ * (model `DevtoolsAiRollupRow`, migration `DevtoolsAiRollupsMigration`).
883
+ * `increment` runs one atomic `$inc` upsert per delta keyed by `id`
884
+ * (`$setOnInsert` the dimensions, `$set` `updated_at`), so every process adds
885
+ * into the same rows. When some upserts fail it throws
886
+ * `DevtoolsAiRollupIncrementError` with the unsaved deltas. `verify` checks the table exists and answers `false`
887
+ * when it does not. Imports cascade lazily.
888
+ *
889
+ * Both drivers support the upsert: MongoDB natively, PostgreSQL as
890
+ * `INSERT … ON CONFLICT (id) DO UPDATE` (the id is the primary key, the filter
891
+ * names it, and the inserted row takes the `$inc` amounts as its values).
892
+ */
893
+ async function createCascadeAiRollupStore(options = {}) {
894
+ const now = options.now ?? Date.now;
895
+ const { DevtoolsAiRollupRow: Rollups } = await Promise.resolve().then(() => require("./models-DF1agAm4.cjs")).then((n) => n.models_exports);
896
+ Rollups.getDataSource();
897
+ const query = () => Rollups.query();
898
+ return {
899
+ async verify() {
900
+ try {
901
+ return await Rollups.getDriver().blueprint.tableExists(Rollups.table);
902
+ } catch {
903
+ return false;
904
+ }
905
+ },
906
+ async increment(deltas) {
907
+ const unwritten = [];
908
+ let firstError;
909
+ for (let start = 0; start < deltas.length; start += INCREMENT_CONCURRENCY) {
910
+ const chunk = deltas.slice(start, start + INCREMENT_CONCURRENCY);
911
+ (await Promise.allSettled(chunk.map(async (delta) => {
912
+ const increments = deltaToIncrements(delta);
913
+ const operations = {
914
+ $set: { updated_at: now() },
915
+ $setOnInsert: {
916
+ hour: delta.hour,
917
+ agent: delta.agent,
918
+ model: delta.model,
919
+ provider: delta.provider
920
+ }
921
+ };
922
+ if (Object.keys(increments).length > 0) operations.$inc = increments;
923
+ await Rollups.atomic({ id: require_extract.rollupId(delta) }, operations, {
924
+ upsert: true,
925
+ trustedFilter: true
926
+ });
927
+ }))).forEach((outcome, index) => {
928
+ if (outcome.status === "fulfilled") return;
929
+ firstError ??= outcome.reason;
930
+ unwritten.push(chunk[index]);
931
+ });
932
+ }
933
+ if (unwritten.length === 0) return;
934
+ if (unwritten.length === deltas.length) throw firstError;
935
+ throw new DevtoolsAiRollupIncrementError(unwritten, {
936
+ written: deltas.length - unwritten.length,
937
+ cause: firstError
938
+ });
939
+ },
940
+ async list(filter) {
941
+ const target = query().lean().where("hour", ">=", filter.fromHour).where("hour", "<", filter.toHour);
942
+ if (filter.agent !== void 0) target.where("agent", "=", filter.agent);
943
+ if (filter.model !== void 0) target.where("model", "=", filter.model);
944
+ if (filter.provider !== void 0) target.where("provider", "=", filter.provider);
945
+ return (await target.get()).map(rowToRecord);
946
+ },
947
+ async prune(beforeHour) {
948
+ return query().where("hour", "<", beforeHour).delete();
949
+ }
950
+ };
951
+ }
952
+
953
+ //#endregion
954
+ //#region ../../packages/devtools/src/ai/rollup/memory-store.ts
955
+ /** Whether a record passes the filter (shared by the memory and file stores). */
956
+ function matchesAiRollupFilter(record, filter) {
957
+ return record.hour >= filter.fromHour && record.hour < filter.toHour && (filter.agent === void 0 || record.agent === filter.agent) && (filter.model === void 0 || record.model === filter.model) && (filter.provider === void 0 || record.provider === filter.provider);
958
+ }
959
+ /** Adds a delta into `rows` (creating the record when missing); shared by the memory and file stores. */
960
+ function applyAiRollupDelta(rows, delta, at) {
961
+ const id = require_extract.rollupId(delta);
962
+ const existing = rows.get(id);
963
+ if (existing) {
964
+ require_extract.addRollupCounters(existing, delta);
965
+ existing.updatedAt = at;
966
+ return;
967
+ }
968
+ rows.set(id, {
969
+ ...structuredClone(delta),
970
+ id,
971
+ updatedAt: at
972
+ });
973
+ }
974
+
975
+ //#endregion
976
+ //#region ../../packages/devtools/src/ai/rollup/file-store.ts
977
+ const DAY_MS$1 = 864e5;
978
+ const DAY_FILE = /^(\d{4}-\d{2}-\d{2})\.json$/;
979
+ function dayName(hour) {
980
+ return new Date(hour).toISOString().slice(0, 10);
981
+ }
982
+ function dayStart(name) {
983
+ return Date.parse(`${name}T00:00:00.000Z`);
984
+ }
985
+ /**
986
+ * The development `DevtoolsAiRollupStore`: one JSON file per UTC day
987
+ * (`YYYY-MM-DD.json`, an array of records) in `directory`. Development runs
988
+ * one process, so `increment` reads the day's file, adds, and writes it back
989
+ * through a temporary file and a rename (a failed day is reported with
990
+ * `DevtoolsAiRollupIncrementError`, the other days stay saved). `prune` deletes whole day files
991
+ * before the cut-off and rewrites the boundary day. `verify` is `true` when
992
+ * the folder exists or can be created. A corrupt file is renamed to
993
+ * `<name>.corrupt-<time>` and treated as empty.
994
+ */
995
+ function createFileAiRollupStore(options) {
996
+ const { directory } = options;
997
+ const now = options.now ?? Date.now;
998
+ let queue = Promise.resolve();
999
+ const serial = (task) => {
1000
+ const run = queue.then(task, task);
1001
+ queue = run.catch(() => void 0);
1002
+ return run;
1003
+ };
1004
+ const fileOf = (name) => node_path.default.join(directory, `${name}.json`);
1005
+ async function readDay(name) {
1006
+ const file = fileOf(name);
1007
+ let text;
1008
+ try {
1009
+ text = await (0, node_fs_promises.readFile)(file, "utf8");
1010
+ } catch (error) {
1011
+ if (error.code === "ENOENT") return [];
1012
+ throw error;
1013
+ }
1014
+ try {
1015
+ const parsed = JSON.parse(text);
1016
+ if (!Array.isArray(parsed)) throw new Error("not an array");
1017
+ return parsed;
1018
+ } catch {
1019
+ await (0, node_fs_promises.rename)(file, `${file}.corrupt-${now()}`).catch(() => void 0);
1020
+ return [];
1021
+ }
1022
+ }
1023
+ async function writeDay(name, records) {
1024
+ await (0, node_fs_promises.mkdir)(directory, { recursive: true });
1025
+ const file = fileOf(name);
1026
+ const temporary = `${file}.tmp-${process.pid}`;
1027
+ await (0, node_fs_promises.writeFile)(temporary, JSON.stringify(records), "utf8");
1028
+ await (0, node_fs_promises.rename)(temporary, file);
1029
+ }
1030
+ return {
1031
+ async verify() {
1032
+ try {
1033
+ await (0, node_fs_promises.mkdir)(directory, { recursive: true });
1034
+ return true;
1035
+ } catch {
1036
+ return false;
1037
+ }
1038
+ },
1039
+ increment(deltas) {
1040
+ return serial(async () => {
1041
+ const byDay = /* @__PURE__ */ new Map();
1042
+ for (const delta of deltas) {
1043
+ const name = dayName(delta.hour);
1044
+ byDay.set(name, [...byDay.get(name) ?? [], delta]);
1045
+ }
1046
+ const unwritten = [];
1047
+ let firstError;
1048
+ for (const [name, dayDeltas] of byDay) try {
1049
+ const rows = new Map((await readDay(name)).map((record) => [record.id, record]));
1050
+ for (const delta of dayDeltas) applyAiRollupDelta(rows, delta, now());
1051
+ await writeDay(name, [...rows.values()]);
1052
+ } catch (error) {
1053
+ firstError ??= error;
1054
+ unwritten.push(...dayDeltas);
1055
+ }
1056
+ if (unwritten.length === 0) return;
1057
+ if (unwritten.length === deltas.length) throw firstError;
1058
+ throw new DevtoolsAiRollupIncrementError(unwritten, {
1059
+ written: deltas.length - unwritten.length,
1060
+ cause: firstError
1061
+ });
1062
+ });
1063
+ },
1064
+ async list(filter) {
1065
+ if (filter.toHour <= filter.fromHour) return [];
1066
+ const found = [];
1067
+ const first = dayStart(dayName(filter.fromHour));
1068
+ let names;
1069
+ try {
1070
+ names = await (0, node_fs_promises.readdir)(directory);
1071
+ } catch {
1072
+ return [];
1073
+ }
1074
+ for (const file of names.sort()) {
1075
+ const name = DAY_FILE.exec(file)?.[1];
1076
+ if (!name) continue;
1077
+ const start = dayStart(name);
1078
+ if (start < first || start >= filter.toHour) continue;
1079
+ for (const record of await readDay(name)) if (matchesAiRollupFilter(record, filter)) found.push(record);
1080
+ }
1081
+ return found;
1082
+ },
1083
+ prune(beforeHour) {
1084
+ return serial(async () => {
1085
+ let names;
1086
+ try {
1087
+ names = await (0, node_fs_promises.readdir)(directory);
1088
+ } catch {
1089
+ return 0;
1090
+ }
1091
+ let removed = 0;
1092
+ for (const file of names) {
1093
+ const name = DAY_FILE.exec(file)?.[1];
1094
+ if (!name) continue;
1095
+ const start = dayStart(name);
1096
+ if (start >= beforeHour) continue;
1097
+ const records = await readDay(name);
1098
+ if (start + DAY_MS$1 <= beforeHour) {
1099
+ await (0, node_fs_promises.rm)(fileOf(name), { force: true });
1100
+ removed += records.length;
1101
+ continue;
1102
+ }
1103
+ const kept = records.filter((record) => record.hour >= beforeHour);
1104
+ if (kept.length !== records.length) {
1105
+ removed += records.length - kept.length;
1106
+ await writeDay(name, kept);
1107
+ }
1108
+ }
1109
+ return removed;
1110
+ });
1111
+ }
1112
+ };
1113
+ }
1114
+
1115
+ //#endregion
1116
+ //#region ../../packages/devtools/src/ai/rollup/writer.ts
1117
+ const HOUR_MS = 36e5;
1118
+ const DAY_MS = 24 * HOUR_MS;
1119
+ const PRUNE_EVERY_MS = 6e5;
1120
+ const WARN_EVERY_MS = 6e4;
1121
+ const STOP_GRACE_MS = 5e3;
1122
+ const DEFAULT_MAX_KEYS = 2e3;
1123
+ /**
1124
+ * Starts the rollup writer: `record(trace)` adds the trace's deltas to an
1125
+ * in-memory map keyed by `rollupId`; every `options.flushIntervalMs` the map
1126
+ * is swapped out and written with `store.increment` (a failed write merges
1127
+ * the unsaved deltas back for the next try, only those when the store says
1128
+ * which, and warns at most once a minute); every
1129
+ * 10 minutes it prunes hours older than `options.retentionDays`. Timers are
1130
+ * `unref`ed and writes are serialised (never two at once). `stop()` clears
1131
+ * the timers and flushes, giving up after 5 seconds.
1132
+ */
1133
+ function startAiRollupWriter(input) {
1134
+ const { store, totalCost, options } = input;
1135
+ const now = input.now ?? Date.now;
1136
+ const warn = input.warn ?? ((message) => console.warn(message));
1137
+ const maxKeys = input.maxKeys ?? DEFAULT_MAX_KEYS;
1138
+ let pending = /* @__PURE__ */ new Map();
1139
+ let writing = [];
1140
+ let inflight = Promise.resolve();
1141
+ let lastWarnAt;
1142
+ const warnOnce = (task, error) => {
1143
+ const at = now();
1144
+ if (lastWarnAt !== void 0 && at - lastWarnAt < WARN_EVERY_MS) return;
1145
+ lastWarnAt = at;
1146
+ const reason = error instanceof Error ? error.message : String(error);
1147
+ warn(`Devtools could not ${task}: ${reason}. It will try again.`);
1148
+ };
1149
+ /** Adds a delta, folding a new key into agent `(other)` once `maxKeys` is reached. */
1150
+ const add = (delta) => {
1151
+ let id = require_extract.rollupId(delta);
1152
+ let target = pending.get(id);
1153
+ let source = delta;
1154
+ if (!target && pending.size >= maxKeys) {
1155
+ source = {
1156
+ ...structuredClone(delta),
1157
+ agent: "(other)"
1158
+ };
1159
+ id = require_extract.rollupId(source);
1160
+ target = pending.get(id);
1161
+ }
1162
+ if (target) require_extract.addRollupCounters(target, source);
1163
+ else pending.set(id, structuredClone(source));
1164
+ };
1165
+ const writeNow = async () => {
1166
+ if (pending.size === 0) return;
1167
+ const batch = [...pending.values()];
1168
+ pending = /* @__PURE__ */ new Map();
1169
+ writing = batch;
1170
+ try {
1171
+ await store.increment(batch);
1172
+ } catch (error) {
1173
+ const unsaved = error instanceof DevtoolsAiRollupIncrementError ? error.unwritten : batch;
1174
+ for (const delta of unsaved) add(delta);
1175
+ warnOnce("save AI totals", error);
1176
+ } finally {
1177
+ writing = [];
1178
+ }
1179
+ };
1180
+ const flush = () => {
1181
+ inflight = inflight.then(writeNow);
1182
+ return inflight;
1183
+ };
1184
+ const prune = async () => {
1185
+ try {
1186
+ const cutoff = Math.floor(now() / HOUR_MS) * HOUR_MS - options.retentionDays * DAY_MS;
1187
+ await store.prune(cutoff);
1188
+ } catch (error) {
1189
+ warnOnce("remove old AI totals", error);
1190
+ }
1191
+ };
1192
+ const flushTimer = setInterval(() => void flush(), options.flushIntervalMs);
1193
+ const pruneTimer = setInterval(() => void prune(), PRUNE_EVERY_MS);
1194
+ flushTimer.unref();
1195
+ pruneTimer.unref();
1196
+ return {
1197
+ record(trace) {
1198
+ try {
1199
+ for (const delta of require_extract.traceToRollupDeltas(trace, totalCost)) add(delta);
1200
+ } catch {}
1201
+ },
1202
+ pending() {
1203
+ return [...writing, ...pending.values()].map((delta) => structuredClone(delta));
1204
+ },
1205
+ flush,
1206
+ async stop() {
1207
+ clearInterval(flushTimer);
1208
+ clearInterval(pruneTimer);
1209
+ let timer;
1210
+ const giveUp = new Promise((resolve) => {
1211
+ timer = setTimeout(resolve, STOP_GRACE_MS);
1212
+ timer.unref();
1213
+ });
1214
+ try {
1215
+ await Promise.race([flush(), giveUp]);
1216
+ } finally {
1217
+ clearTimeout(timer);
1218
+ }
1219
+ }
1220
+ };
1221
+ }
1222
+
1223
+ //#endregion
1224
+ //#region ../../packages/devtools/src/ai/attach.ts
1225
+ /**
1226
+ * Loads Panoptic's trace feed (`subscribeTraces`, `totalCostUsd`) and
1227
+ * `@warlock.js/ai`'s observer registry lazily, plus the Runs helpers. Returns
1228
+ * `{ unavailable }` (`ai-missing`, `panoptic-missing`, `panoptic-failed`)
1229
+ * when they do not load. Shared by the development and production wiring.
1230
+ */
1231
+ async function loadAiFeed(deps) {
1232
+ const loaded = await require_extract.loadAiPackages(deps);
1233
+ if ("unavailable" in loaded) return { unavailable: require_extract.toAiUnavailableView(loaded.unavailable) };
1234
+ const { panoptic, observationOff } = loaded;
1235
+ return {
1236
+ feed: {
1237
+ subscribe: (listener) => panoptic.subscribeTraces(listener),
1238
+ totalCost: (usage) => panoptic.totalCostUsd(usage),
1239
+ observationOff
1240
+ },
1241
+ helpers: {
1242
+ filterTraces: panoptic.filterTraces,
1243
+ groupBySession: panoptic.groupBySession,
1244
+ groupByPrompt: panoptic.groupByPrompt,
1245
+ groupByType: panoptic.groupByType,
1246
+ percentile: panoptic.percentile,
1247
+ tracePromptKey: panoptic.tracePromptKey
1248
+ }
1249
+ };
1250
+ }
1251
+ const TABLE_MISSING_WARNING = "AI reports are off: the devtools_ai_rollups table is missing. Run the devtools migrations (warlock migrate), then restart.";
1252
+ /**
1253
+ * Starts the AI reports of this process: with `options.reports` off answers
1254
+ * `reports-off`; otherwise builds the store for the mode (development: the
1255
+ * file store in `directory`; production: the cascade store, `table-missing`
1256
+ * when `verify()` is false, logged once with the migration hint), starts the
1257
+ * rollup writer on `feed.subscribe`, and builds the report service.
1258
+ * `dispose` unsubscribes and stops the writer (final flush).
1259
+ */
1260
+ async function attachAiReports(input) {
1261
+ const { feed, options, warn } = input;
1262
+ const off = (reason) => ({
1263
+ ...require_extract.toAiUnavailableView(require_extract.describeAiUnavailable(reason)),
1264
+ async dispose() {}
1265
+ });
1266
+ if (!options.reports) return off("reports-off");
1267
+ const production = options.mode === "production";
1268
+ let store;
1269
+ try {
1270
+ store = production ? await createCascadeAiRollupStore() : createFileAiRollupStore({ directory: input.directory ?? node_path.default.join(process.cwd(), "storage", "devtools", "ai-rollups") });
1271
+ if (!await store.verify()) {
1272
+ warn(TABLE_MISSING_WARNING);
1273
+ return off("table-missing");
1274
+ }
1275
+ } catch (error) {
1276
+ warn(`${TABLE_MISSING_WARNING} (${error instanceof Error ? error.message : String(error)})`);
1277
+ return off("table-missing");
1278
+ }
1279
+ const writer = startAiRollupWriter({
1280
+ store,
1281
+ totalCost: feed.totalCost,
1282
+ options,
1283
+ warn
1284
+ });
1285
+ const unsubscribe = feed.subscribe((trace) => writer.record(trace));
1286
+ return {
1287
+ available: true,
1288
+ service: createAiReportService({
1289
+ store,
1290
+ pending: () => writer.pending(),
1291
+ retentionDays: options.retentionDays,
1292
+ observationOff: () => feed.observationOff(),
1293
+ ...input.recentFailures ? { recentFailures: input.recentFailures } : {}
1294
+ }),
1295
+ writer,
1296
+ async dispose() {
1297
+ unsubscribe();
1298
+ await writer.stop();
1299
+ }
1300
+ };
1301
+ }
1302
+ /** The global key devtools publishes once mounted, read by Panoptic to keep its own dashboard off. */
1303
+ const DEVTOOLS_MOUNTED_KEY = Symbol.for("@warlock.js/devtools.mounted");
1304
+
1305
+ //#endregion
1306
+ Object.defineProperty(exports, "DEVTOOLS_MOUNTED_KEY", {
1307
+ enumerable: true,
1308
+ get: function () {
1309
+ return DEVTOOLS_MOUNTED_KEY;
1310
+ }
1311
+ });
1312
+ Object.defineProperty(exports, "DEVTOOLS_PRODUCTION_DEFAULTS", {
1313
+ enumerable: true,
1314
+ get: function () {
1315
+ return DEVTOOLS_PRODUCTION_DEFAULTS;
1316
+ }
1317
+ });
1318
+ Object.defineProperty(exports, "attachAiReports", {
1319
+ enumerable: true,
1320
+ get: function () {
1321
+ return attachAiReports;
1322
+ }
1323
+ });
1324
+ Object.defineProperty(exports, "loadAiFeed", {
1325
+ enumerable: true,
1326
+ get: function () {
1327
+ return loadAiFeed;
1328
+ }
1329
+ });
1330
+ Object.defineProperty(exports, "resolveDevtoolsAiOptions", {
1331
+ enumerable: true,
1332
+ get: function () {
1333
+ return resolveDevtoolsAiOptions;
1334
+ }
1335
+ });
1336
+ Object.defineProperty(exports, "resolveProductionOptions", {
1337
+ enumerable: true,
1338
+ get: function () {
1339
+ return resolveProductionOptions;
1340
+ }
1341
+ });
1342
+ //# sourceMappingURL=attach-D5aMqUnA.cjs.map