@warlock.js/devtools 5.59.0 → 5.61.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 (154) hide show
  1. package/CHANGELOG.md +30 -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-D0nF-7w3.cjs} +78 -14
  9. package/cjs/boot-D0nF-7w3.cjs.map +1 -0
  10. package/cjs/{capture-CuyT8Vab.cjs → capture-D2k0GnBN.cjs} +23 -422
  11. package/cjs/capture-D2k0GnBN.cjs.map +1 -0
  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/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
  15. package/cjs/collector-BfC4v87v.cjs.map +1 -0
  16. package/cjs/{current-request-id-CeQhRz9Q.cjs → current-request-id-Badec-TH.cjs} +2 -2
  17. package/cjs/{current-request-id-CeQhRz9Q.cjs.map → current-request-id-Badec-TH.cjs.map} +1 -1
  18. package/cjs/{errors-BadbSDX8.cjs → errors-DNQ-g49I.cjs} +198 -1
  19. package/cjs/errors-DNQ-g49I.cjs.map +1 -0
  20. package/cjs/extract-8kaX_cUV.cjs +1103 -0
  21. package/cjs/extract-8kaX_cUV.cjs.map +1 -0
  22. package/cjs/{http-Biauhqi0.cjs → http-1nnpAoI7.cjs} +33 -10
  23. package/cjs/http-1nnpAoI7.cjs.map +1 -0
  24. package/cjs/index.cjs +1 -1
  25. package/cjs/{insights-BjJA6Ret.cjs → insights-COA3u37q.cjs} +54 -22
  26. package/cjs/insights-COA3u37q.cjs.map +1 -0
  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/query-shape-DShKQa0x.cjs +45 -0
  35. package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
  36. package/cjs/redact-DQ28mDzr.cjs +533 -0
  37. package/cjs/redact-DQ28mDzr.cjs.map +1 -0
  38. package/cjs/runs-DECWPGnq.cjs +390 -0
  39. package/cjs/runs-DECWPGnq.cjs.map +1 -0
  40. package/cjs/{server-D3XRbSSb.cjs → server-DLT3uPef.cjs} +8 -7
  41. package/cjs/{server-D3XRbSSb.cjs.map → server-DLT3uPef.cjs.map} +1 -1
  42. package/cjs/{src-QcNghoYN.cjs → src-BZiSv8A1.cjs} +182 -24
  43. package/cjs/src-BZiSv8A1.cjs.map +1 -0
  44. package/cjs/{store-CNFv3wVp.cjs → store-EFn4wp0T.cjs} +2 -2
  45. package/cjs/{stream-route-BqyAlfxQ.cjs → stream-route-B6WAjbPG.cjs} +111 -22
  46. package/cjs/stream-route-B6WAjbPG.cjs.map +1 -0
  47. package/esm/ai/attach.mjs +92 -0
  48. package/esm/ai/attach.mjs.map +1 -0
  49. package/esm/ai/options.mjs +31 -0
  50. package/esm/ai/options.mjs.map +1 -0
  51. package/esm/ai/reports/aggregate.mjs +330 -0
  52. package/esm/ai/reports/aggregate.mjs.map +1 -0
  53. package/esm/ai/reports/evaluate.mjs +108 -0
  54. package/esm/ai/reports/evaluate.mjs.map +1 -0
  55. package/esm/ai/reports/range.mjs +121 -0
  56. package/esm/ai/reports/range.mjs.map +1 -0
  57. package/esm/ai/reports/runs.d.mts +2 -0
  58. package/esm/ai/reports/runs.mjs +212 -0
  59. package/esm/ai/reports/runs.mjs.map +1 -0
  60. package/esm/ai/reports/service.mjs +132 -0
  61. package/esm/ai/reports/service.mjs.map +1 -0
  62. package/esm/ai/rollup/cascade-store.mjs +84 -0
  63. package/esm/ai/rollup/cascade-store.mjs.map +1 -0
  64. package/esm/ai/rollup/categories.mjs +67 -0
  65. package/esm/ai/rollup/categories.mjs.map +1 -0
  66. package/esm/ai/rollup/extract.mjs +225 -0
  67. package/esm/ai/rollup/extract.mjs.map +1 -0
  68. package/esm/ai/rollup/file-store.mjs +147 -0
  69. package/esm/ai/rollup/file-store.mjs.map +1 -0
  70. package/esm/ai/rollup/histogram.mjs +42 -0
  71. package/esm/ai/rollup/histogram.mjs.map +1 -0
  72. package/esm/ai/rollup/increment-error.mjs +19 -0
  73. package/esm/ai/rollup/increment-error.mjs.map +1 -0
  74. package/esm/ai/rollup/index.mjs +9 -0
  75. package/esm/ai/rollup/mapping.mjs +69 -0
  76. package/esm/ai/rollup/mapping.mjs.map +1 -0
  77. package/esm/ai/rollup/memory-store.mjs +26 -0
  78. package/esm/ai/rollup/memory-store.mjs.map +1 -0
  79. package/esm/ai/rollup/writer.mjs +113 -0
  80. package/esm/ai/rollup/writer.mjs.map +1 -0
  81. package/esm/ai/types.d.mts +29 -0
  82. package/esm/ai/types.d.mts.map +1 -0
  83. package/esm/devtools-connector.d.mts.map +1 -1
  84. package/esm/devtools-connector.mjs +58 -3
  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/boot.mjs +70 -3
  90. package/esm/production/boot.mjs.map +1 -1
  91. package/esm/production/contracts.d.mts +388 -6
  92. package/esm/production/contracts.d.mts.map +1 -1
  93. package/esm/production/contracts.mjs +64 -2
  94. package/esm/production/contracts.mjs.map +1 -1
  95. package/esm/production/errors.mjs +8 -0
  96. package/esm/production/errors.mjs.map +1 -1
  97. package/esm/production/http/access.mjs +6 -0
  98. package/esm/production/http/access.mjs.map +1 -1
  99. package/esm/production/http/mount.mjs +21 -2
  100. package/esm/production/http/mount.mjs.map +1 -1
  101. package/esm/production/http/share.mjs.map +1 -1
  102. package/esm/production/index.d.mts +2 -2
  103. package/esm/production/insights/jobs.mjs +45 -11
  104. package/esm/production/insights/jobs.mjs.map +1 -1
  105. package/esm/production/store/migrations.d.mts +1 -1
  106. package/esm/production/store/migrations.d.mts.map +1 -1
  107. package/esm/production/store/migrations.mjs +4 -2
  108. package/esm/production/store/migrations.mjs.map +1 -1
  109. package/esm/production/store/models/ai-rollup.migration.mjs +48 -0
  110. package/esm/production/store/models/ai-rollup.migration.mjs.map +1 -0
  111. package/esm/production/store/models/ai-rollup.model.mjs +13 -0
  112. package/esm/production/store/models/ai-rollup.model.mjs.map +1 -0
  113. package/esm/production/store/models/index.mjs +3 -1
  114. package/esm/server/ai-report-routes.mjs +72 -0
  115. package/esm/server/ai-report-routes.mjs.map +1 -0
  116. package/esm/server/ai-routes.mjs +22 -1
  117. package/esm/server/ai-routes.mjs.map +1 -1
  118. package/esm/server/index.mjs +2 -0
  119. package/esm/server/index.mjs.map +1 -1
  120. package/esm/server/panel-routes.mjs.map +1 -1
  121. package/esm/server/ui-assets.mjs +4 -7
  122. package/esm/server/ui-assets.mjs.map +1 -1
  123. package/esm/sources/agent-trace-source.d.mts.map +1 -1
  124. package/esm/sources/agent-trace-source.mjs.map +1 -1
  125. package/esm/sources/ai-source.d.mts +2 -0
  126. package/esm/sources/ai-source.d.mts.map +1 -1
  127. package/esm/sources/ai-source.mjs +58 -17
  128. package/esm/sources/ai-source.mjs.map +1 -1
  129. package/esm/types.d.mts +13 -3
  130. package/esm/types.d.mts.map +1 -1
  131. package/llms-full.txt +61 -22
  132. package/package.json +8 -8
  133. package/skills/SKILL.md +61 -22
  134. package/ui/dashboard/assets/app.css +1 -1
  135. package/ui/dashboard/assets/app.js +12 -5
  136. package/ui/dashboard/build-info.json +7 -7
  137. package/cjs/ai-source-BdvMfyKw.cjs +0 -448
  138. package/cjs/ai-source-BdvMfyKw.cjs.map +0 -1
  139. package/cjs/app-versions-DfpPZOI2.cjs.map +0 -1
  140. package/cjs/boot-nczSvJ_F.cjs.map +0 -1
  141. package/cjs/capture-CuyT8Vab.cjs.map +0 -1
  142. package/cjs/collector-CJbQbzzK.cjs.map +0 -1
  143. package/cjs/errors-BadbSDX8.cjs.map +0 -1
  144. package/cjs/histogram-DTOGnNBW.cjs +0 -102
  145. package/cjs/histogram-DTOGnNBW.cjs.map +0 -1
  146. package/cjs/http-Biauhqi0.cjs.map +0 -1
  147. package/cjs/insights-BjJA6Ret.cjs.map +0 -1
  148. package/cjs/migrations-BP4cYTGo.cjs.map +0 -1
  149. package/cjs/options-B9FHbRAJ.cjs +0 -205
  150. package/cjs/options-B9FHbRAJ.cjs.map +0 -1
  151. package/cjs/panels-D1ITm-jc.cjs +0 -384
  152. package/cjs/panels-D1ITm-jc.cjs.map +0 -1
  153. package/cjs/src-QcNghoYN.cjs.map +0 -1
  154. package/cjs/stream-route-BqyAlfxQ.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach-D5aMqUnA.cjs","names":["DevtoolsProductionConfigError","isValidNetworkEntry","emptyAiLatency","aiLatencyQuantile","DEVTOOLS_AI_ERROR_CATEGORIES","DEVTOOLS_AI_ERROR_LABELS","HOUR_MS","DAY_MS","DevtoolsApiError","DEVTOOLS_AI_LATENCY_BUCKETS_MS","DEVTOOLS_AI_ERROR_CATEGORIES","emptyRollupDelta","rollupId","rollupId","DAY_MS","path","readFile","rename","mkdir","writeFile","readdir","rm","rollupId","traceToRollupDeltas","loadAiPackages","toAiUnavailableView","describeAiUnavailable","path"],"sources":["../../../../../../../packages/devtools/src/ai/options.ts","../../../../../../../packages/devtools/src/production/options.ts","../../../../../../../packages/devtools/src/ai/reports/aggregate.ts","../../../../../../../packages/devtools/src/ai/reports/range.ts","../../../../../../../packages/devtools/src/ai/reports/service.ts","../../../../../../../packages/devtools/src/ai/rollup/mapping.ts","../../../../../../../packages/devtools/src/ai/rollup/increment-error.ts","../../../../../../../packages/devtools/src/ai/rollup/cascade-store.ts","../../../../../../../packages/devtools/src/ai/rollup/memory-store.ts","../../../../../../../packages/devtools/src/ai/rollup/file-store.ts","../../../../../../../packages/devtools/src/ai/rollup/writer.ts","../../../../../../../packages/devtools/src/ai/attach.ts"],"sourcesContent":["import type { DevtoolsMode } from \"../production/contracts\";\nimport type { DevtoolsAiOptions, ResolvedDevtoolsAiOptions } from \"./types\";\n\n/** Default `retentionDays` per mode. */\nexport const DEVTOOLS_AI_RETENTION_DAYS: Readonly<Record<DevtoolsMode, number>> = {\n development: 30,\n production: 90,\n};\n\n/** Default `flushIntervalMs`. */\nexport const DEVTOOLS_AI_FLUSH_INTERVAL_MS = 60_000;\n\n/**\n * Applies the defaults of `devtools.ai` for `mode`. Throws an `Error` naming\n * the option when `retentionDays` is not a whole number from 1 to 400 or\n * `flushIntervalMs` is below 5000 (the same style as `resolveDevtoolsOptions`).\n */\nexport function resolveDevtoolsAiOptions(\n options: DevtoolsAiOptions | undefined,\n mode: DevtoolsMode,\n): ResolvedDevtoolsAiOptions {\n const reports = options?.reports ?? true;\n const retentionDays = options?.retentionDays ?? DEVTOOLS_AI_RETENTION_DAYS[mode];\n const flushIntervalMs = options?.flushIntervalMs ?? DEVTOOLS_AI_FLUSH_INTERVAL_MS;\n\n if (typeof reports !== \"boolean\") {\n throw new Error('Devtools option \"ai.reports\" must be true or false.');\n }\n\n if (!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 400) {\n throw new Error('Devtools option \"ai.retentionDays\" must be a whole number from 1 to 400.');\n }\n\n if (\n typeof flushIntervalMs !== \"number\" ||\n !Number.isFinite(flushIntervalMs) ||\n flushIntervalMs < 5000\n ) {\n throw new Error('Devtools option \"ai.flushIntervalMs\" must be at least 5000.');\n }\n\n return { reports, retentionDays, flushIntervalMs, mode };\n}\n","import type { DevtoolsLogEntry, DevtoolsProductionOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport { isValidNetworkEntry } from \"./http/ip\";\n\n/**\n * `DevtoolsProductionOptions` with every default applied and the environment\n * read. Built once at boot by `resolveProductionOptions`.\n */\nexport type ResolvedDevtoolsProductionOptions = {\n /** The dashboard path, without a trailing slash. */\n path: string;\n /** The first admin from the environment; every field `null` when unset. */\n admin: { email: string | null; password: string | null; setupToken: string | null };\n sampleRate: number;\n slowRequestMs: number;\n slowQueryMs: number;\n maxRequests: number;\n /** Queries kept per sampled request; the rest are counted in `droppedQueries`. */\n maxQueriesPerRequest: number;\n /** Query shapes kept in memory per process (least recently seen evicted). */\n maxShapes: number;\n /** Route keys kept in memory per process. */\n maxRoutes: number;\n /** Error groups kept in memory per process. */\n maxErrorGroups: number;\n requestRetentionHours: number;\n maxStoredSamplesPerMinute: number;\n reportIntervalMs: number;\n trustedProxies: readonly string[];\n requireHttps: boolean;\n allowedIps: readonly string[];\n origin: string | null;\n session: { idleMinutes: number; maxHours: number; pendingMinutes: number };\n twoFactor: \"off\" | \"admins\" | \"everyone\";\n passwords: { minLength: number; rejectCommon: boolean };\n rateLimits: {\n windowMinutes: number;\n account: number;\n ip: number;\n global: number;\n lockMinutes: number;\n };\n explain: { executing: boolean };\n panels: Readonly<Record<string, boolean>>;\n logLevels: readonly DevtoolsLogEntry[\"level\"][];\n auditRetentionDays: number;\n passkeys: { rpName: string; rpId: string | null };\n /** Read-only share links. */\n share: { enabled: boolean; maxDays: number };\n};\n\n/** The defaults `resolveProductionOptions` applies (environment values excluded). */\nexport const DEVTOOLS_PRODUCTION_DEFAULTS = {\n sampleRate: 0.1,\n slowRequestMs: 1000,\n slowQueryMs: 200,\n maxRequests: 200,\n maxQueriesPerRequest: 200,\n maxShapes: 500,\n maxRoutes: 300,\n maxErrorGroups: 100,\n requestRetentionHours: 24,\n maxStoredSamplesPerMinute: 120,\n reportIntervalMs: 10_000,\n requireHttps: true,\n session: { idleMinutes: 30, maxHours: 8, pendingMinutes: 10 },\n twoFactor: \"admins\",\n passwords: { minLength: 8, rejectCommon: true },\n rateLimits: { windowMinutes: 15, account: 5, ip: 20, global: 100, lockMinutes: 15 },\n explain: { executing: false },\n logLevels: [\"warn\", \"error\"],\n auditRetentionDays: 90,\n passkeys: { rpName: \"Warlock monitor\" },\n share: { enabled: false, maxDays: 30 },\n} as const;\n\n/** The environment variables production mode reads. */\nexport const DEVTOOLS_ENV = {\n path: \"DEVTOOLS_PATH\",\n adminEmail: \"DEVTOOLS_ADMIN_EMAIL\",\n adminPassword: \"DEVTOOLS_ADMIN_PASSWORD\",\n setupToken: \"DEVTOOLS_SETUP_TOKEN\",\n} as const;\n\nconst LOG_LEVELS: readonly DevtoolsLogEntry[\"level\"][] = [\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"success\",\n];\n\nconst PATH_CHARACTERS = /^[A-Za-z0-9._~/-]+$/;\nconst MIN_PATH_LENGTH = 8;\nconst MIN_SETUP_TOKEN_LENGTH = 32;\n\nfunction invalid(option: string, expected: string): never {\n throw new DevtoolsProductionConfigError(\n \"DT007\",\n `Option \"devtools.production.${option}\" is not valid: ${expected}.`,\n );\n}\n\nfunction present(value: string | undefined): string | null {\n return value === undefined || value === \"\" ? null : value;\n}\n\nfunction integerAtLeastOne(option: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n\n if (!Number.isInteger(value) || value < 1) invalid(option, \"use a whole number of 1 or more\");\n\n return value;\n}\n\nfunction networkList(option: string, value: readonly string[] | undefined): readonly string[] {\n if (value === undefined) return [];\n\n if (!Array.isArray(value)) {\n invalid(option, 'use a list of IPs, CIDR ranges, \"loopback\" or \"private\"');\n }\n\n for (const entry of value as readonly unknown[]) {\n if (!isValidNetworkEntry(entry)) {\n invalid(option, `\"${String(entry)}\" is not an IP, a CIDR range, \"loopback\" or \"private\"`);\n }\n }\n\n return [...value];\n}\n\n/** The dashboard path without a trailing slash, or a DT001/DT002 error. */\nfunction resolvePath(value: string | undefined): string {\n const given = present(value);\n\n if (given === null) throw new DevtoolsProductionConfigError(\"DT001\");\n\n const path = given.replace(/\\/+$/, \"\");\n const segments = path.split(\"/\").slice(1);\n const lower = path.toLowerCase();\n\n if (\n !path.startsWith(\"/\") ||\n path.length < MIN_PATH_LENGTH ||\n !PATH_CHARACTERS.test(path) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n lower === \"/__warlock\" ||\n lower.startsWith(\"/__warlock/\")\n ) {\n throw new DevtoolsProductionConfigError(\"DT002\");\n }\n\n return path;\n}\n\n/**\n * Applies the defaults to `options`, reads the path and first admin from\n * `env`, and validates everything.\n *\n * Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),\n * DT007 (an option out of range: sampleRate outside 0–1, share.maxDays outside 1–365, a non-positive\n * limit, an unknown twoFactor value, a bad CIDR, an origin that is not\n * `https://host[:port]`), DT009 (both a password and a setup token), DT010\n * (setup token shorter than 32 characters). DT003/DT004 (admin) are checked\n * later by `ensureFirstAdmin`, which needs the database.\n */\nexport function resolveProductionOptions(\n options: DevtoolsProductionOptions | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): ResolvedDevtoolsProductionOptions {\n const given = options ?? {};\n const defaults = DEVTOOLS_PRODUCTION_DEFAULTS;\n const path = resolvePath(given.path ?? env[DEVTOOLS_ENV.path]);\n\n const sampleRate = given.sampleRate ?? defaults.sampleRate;\n\n if (\n typeof sampleRate !== \"number\" ||\n !Number.isFinite(sampleRate) ||\n sampleRate < 0 ||\n sampleRate > 1\n ) {\n invalid(\"sampleRate\", \"use a number from 0 to 1\");\n }\n\n const requireHttps: boolean = given.requireHttps ?? defaults.requireHttps;\n\n if (typeof requireHttps !== \"boolean\") invalid(\"requireHttps\", \"use true or false\");\n\n const twoFactor = given.twoFactor ?? defaults.twoFactor;\n\n if (twoFactor !== \"off\" && twoFactor !== \"admins\" && twoFactor !== \"everyone\") {\n invalid(\"twoFactor\", 'use \"off\", \"admins\" or \"everyone\"');\n }\n\n const minLength: number = given.passwords?.minLength ?? defaults.passwords.minLength;\n\n if (!Number.isInteger(minLength) || minLength < 8 || minLength > 72) {\n invalid(\n \"passwords.minLength\",\n \"use a whole number from 8 to 72 (passwords are limited to 72 bytes, so a longer minimum would refuse every password)\",\n );\n }\n\n const rejectCommon: boolean = given.passwords?.rejectCommon ?? defaults.passwords.rejectCommon;\n\n if (typeof rejectCommon !== \"boolean\") invalid(\"passwords.rejectCommon\", \"use true or false\");\n\n const origin = given.origin ?? null;\n\n if (origin !== null) {\n const pattern = requireHttps ? /^https:\\/\\/[^/\\s]+$/ : /^https?:\\/\\/[^/\\s]+$/;\n\n if (typeof origin !== \"string\" || !pattern.test(origin)) {\n invalid(\n \"origin\",\n requireHttps\n ? \"use an origin such as https://app.example.com, without a path or a trailing slash\"\n : \"use an origin such as http://localhost:3000, without a path or a trailing slash\",\n );\n }\n }\n\n const panels: Readonly<Record<string, unknown>> = given.panels ?? {};\n\n if (panels === null || typeof panels !== \"object\" || Array.isArray(panels)) {\n invalid(\"panels\", \"use an object of tab ids and true or false\");\n }\n\n for (const [id, enabled] of Object.entries(panels)) {\n if (typeof enabled !== \"boolean\") invalid(`panels.${id}`, \"use true or false\");\n }\n\n const logLevels = given.logLevels ?? defaults.logLevels;\n\n if (!Array.isArray(logLevels) || logLevels.some((level) => !LOG_LEVELS.includes(level))) {\n invalid(\"logLevels\", `use a list of ${LOG_LEVELS.join(\", \")}`);\n }\n\n const executing: boolean = given.explain?.executing ?? defaults.explain.executing;\n\n if (typeof executing !== \"boolean\") invalid(\"explain.executing\", \"use true or false\");\n\n const rpName: string = given.passkeys?.rpName ?? defaults.passkeys.rpName;\n const rpId = given.passkeys?.rpId ?? null;\n\n if (typeof rpName !== \"string\" || rpName.trim() === \"\") {\n invalid(\"passkeys.rpName\", \"use a non-empty name\");\n }\n\n if (rpId !== null && (typeof rpId !== \"string\" || rpId.trim() === \"\")) {\n invalid(\"passkeys.rpId\", \"use a host name such as app.example.com\");\n }\n\n const shareEnabled: boolean = given.share?.enabled ?? defaults.share.enabled;\n const shareMaxDays: number = given.share?.maxDays ?? defaults.share.maxDays;\n\n if (typeof shareEnabled !== \"boolean\") invalid(\"share.enabled\", \"use true or false\");\n\n if (!Number.isInteger(shareMaxDays) || shareMaxDays < 1 || shareMaxDays > 365) {\n invalid(\"share.maxDays\", \"use a whole number of days from 1 to 365\");\n }\n\n const limits = given.rateLimits ?? {};\n const session = given.session ?? {};\n\n const resolved: ResolvedDevtoolsProductionOptions = {\n path,\n admin: {\n email: present(env[DEVTOOLS_ENV.adminEmail]),\n password: present(env[DEVTOOLS_ENV.adminPassword]),\n setupToken: present(env[DEVTOOLS_ENV.setupToken]),\n },\n sampleRate,\n slowRequestMs: integerAtLeastOne(\"slowRequestMs\", given.slowRequestMs, defaults.slowRequestMs),\n slowQueryMs: integerAtLeastOne(\"slowQueryMs\", given.slowQueryMs, defaults.slowQueryMs),\n maxRequests: integerAtLeastOne(\"maxRequests\", given.maxRequests, defaults.maxRequests),\n maxQueriesPerRequest: defaults.maxQueriesPerRequest,\n maxShapes: defaults.maxShapes,\n maxRoutes: defaults.maxRoutes,\n maxErrorGroups: defaults.maxErrorGroups,\n requestRetentionHours: integerAtLeastOne(\n \"requestRetentionHours\",\n given.requestRetentionHours,\n defaults.requestRetentionHours,\n ),\n maxStoredSamplesPerMinute: integerAtLeastOne(\n \"maxStoredSamplesPerMinute\",\n given.maxStoredSamplesPerMinute,\n defaults.maxStoredSamplesPerMinute,\n ),\n reportIntervalMs: integerAtLeastOne(\n \"reportIntervalMs\",\n given.reportIntervalMs,\n defaults.reportIntervalMs,\n ),\n trustedProxies: networkList(\"trustedProxies\", given.trustedProxies),\n requireHttps,\n allowedIps: networkList(\"allowedIps\", given.allowedIps),\n origin,\n session: {\n idleMinutes: integerAtLeastOne(\n \"session.idleMinutes\",\n session.idleMinutes,\n defaults.session.idleMinutes,\n ),\n maxHours: integerAtLeastOne(\"session.maxHours\", session.maxHours, defaults.session.maxHours),\n pendingMinutes: defaults.session.pendingMinutes,\n },\n twoFactor,\n passwords: { minLength, rejectCommon },\n rateLimits: {\n windowMinutes: integerAtLeastOne(\n \"rateLimits.windowMinutes\",\n limits.windowMinutes,\n defaults.rateLimits.windowMinutes,\n ),\n account: integerAtLeastOne(\"rateLimits.account\", limits.account, defaults.rateLimits.account),\n ip: integerAtLeastOne(\"rateLimits.ip\", limits.ip, defaults.rateLimits.ip),\n global: integerAtLeastOne(\"rateLimits.global\", limits.global, defaults.rateLimits.global),\n lockMinutes: integerAtLeastOne(\n \"rateLimits.lockMinutes\",\n limits.lockMinutes,\n defaults.rateLimits.lockMinutes,\n ),\n },\n explain: { executing },\n panels: { ...(panels as Readonly<Record<string, boolean>>) },\n logLevels: [...logLevels],\n auditRetentionDays: integerAtLeastOne(\n \"auditRetentionDays\",\n given.auditRetentionDays,\n defaults.auditRetentionDays,\n ),\n passkeys: { rpName, rpId },\n share: { enabled: shareEnabled, maxDays: shareMaxDays },\n };\n\n if (resolved.admin.password !== null && resolved.admin.setupToken !== null) {\n throw new DevtoolsProductionConfigError(\"DT009\");\n }\n\n if (\n resolved.admin.setupToken !== null &&\n resolved.admin.setupToken.length < MIN_SETUP_TOKEN_LENGTH\n ) {\n throw new DevtoolsProductionConfigError(\"DT010\");\n }\n\n return resolved;\n}\n","import type {\n DevtoolsAiBreakdownRow,\n DevtoolsAiErrorCategory,\n DevtoolsAiErrorGroup,\n DevtoolsAiFilterOptions,\n DevtoolsAiModelRow,\n DevtoolsAiPricingState,\n DevtoolsAiRatePoint,\n DevtoolsAiResolvedRange,\n DevtoolsAiSeriesSet,\n DevtoolsAiTotals,\n} from \"../../production/contracts\";\nimport { DEVTOOLS_AI_ERROR_CATEGORIES } from \"../../production/contracts\";\nimport { DEVTOOLS_AI_ERROR_LABELS } from \"../rollup/categories\";\nimport { addAiLatency, aiLatencyQuantile, emptyAiLatency } from \"../rollup/histogram\";\nimport type { DevtoolsAiRollupDelta } from \"../types\";\n\n/**\n * Pure folds from rollup rows (stored records plus pending deltas) to the\n * report shapes in `production/contracts.ts`. No I/O, no clock.\n */\n\nconst MAX_NAMED_SERIES = 5;\nconst OTHER_KEY = \"__other\";\n\n/** `provider/model`, the key the UI filters and colours models by. */\nfunction modelKey(row: { provider: string; model: string }): string {\n return `${row.provider}/${row.model}`;\n}\n\n/** Sums rows into totals (latency from the merged histogram). */\nexport function totalsOf(rows: readonly DevtoolsAiRollupDelta[]): DevtoolsAiTotals {\n const totals: DevtoolsAiTotals = {\n runs: 0,\n completed: 0,\n failed: 0,\n incomplete: 0,\n cancelled: 0,\n errorRate: 0,\n tokens: { input: 0, output: 0, cached: 0, cacheWrite: 0, reasoning: 0 },\n cost: { estimatedUsd: 0, pricedRuns: 0, unpricedRuns: 0, unpricedTokens: 0 },\n latency: { p50Ms: null, p95Ms: null, meanMs: null },\n fallbackRuns: 0,\n refusals: 0,\n };\n const histogram = emptyAiLatency();\n let latencyCount = 0;\n let latencySumMs = 0;\n\n for (const row of rows) {\n totals.runs += row.runs;\n totals.completed += row.completed;\n totals.failed += row.failed;\n totals.incomplete += row.incomplete;\n totals.cancelled += row.cancelled;\n totals.tokens.input += row.inputTokens;\n totals.tokens.output += row.outputTokens;\n totals.tokens.cached += row.cachedTokens;\n totals.tokens.cacheWrite += row.cacheWriteTokens;\n totals.tokens.reasoning += row.reasoningTokens;\n totals.cost.estimatedUsd += row.costUsd;\n totals.cost.pricedRuns += row.pricedRuns;\n totals.cost.unpricedRuns += row.unpricedRuns;\n totals.cost.unpricedTokens += row.unpricedTokens;\n totals.fallbackRuns += row.fallbackRuns;\n totals.refusals += row.refusals;\n addAiLatency(histogram, row.latency);\n latencyCount += row.latencyCount;\n latencySumMs += row.latencySumMs;\n }\n\n totals.errorRate = totals.runs > 0 ? (totals.failed + totals.incomplete) / totals.runs : 0;\n totals.latency = {\n p50Ms: aiLatencyQuantile(histogram, 0.5),\n p95Ms: aiLatencyQuantile(histogram, 0.95),\n meanMs: latencyCount > 0 ? latencySumMs / latencyCount : null,\n };\n\n return totals;\n}\n\n/** The bucket index of an hour inside `range` (`-1` outside). */\nexport function bucketOf(hour: number, range: DevtoolsAiResolvedRange): number {\n if (hour < range.from || hour >= range.to) return -1;\n\n return Math.floor((hour - range.from) / range.stepMs);\n}\n\n/** Bucket starts of a range, oldest first. */\nfunction bucketStarts(range: DevtoolsAiResolvedRange): number[] {\n const count = Math.max(0, Math.ceil((range.to - range.from) / range.stepMs));\n\n return Array.from({ length: count }, (_, index) => range.from + index * range.stepMs);\n}\n\ntype SeriesEntry = { bucket: number; key: string; label: string; value: number };\n\n/** Top five keys by sum become series, the rest are summed into `__other`. */\nfunction buildSeries(range: DevtoolsAiResolvedRange, entries: SeriesEntry[]): DevtoolsAiSeriesSet {\n const buckets = bucketStarts(range);\n const byKey = new Map<string, { label: string; sum: number; values: number[] }>();\n\n for (const entry of entries) {\n if (entry.bucket < 0 || entry.bucket >= buckets.length) continue;\n\n let item = byKey.get(entry.key);\n\n if (!item) {\n item = { label: entry.label, sum: 0, values: new Array<number>(buckets.length).fill(0) };\n byKey.set(entry.key, item);\n }\n\n item.values[entry.bucket] = (item.values[entry.bucket] ?? 0) + entry.value;\n item.sum += entry.value;\n }\n\n const ranked = [...byKey.entries()].sort(\n (a, b) => b[1].sum - a[1].sum || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0),\n );\n const series: DevtoolsAiSeriesSet[\"series\"] = ranked\n .slice(0, MAX_NAMED_SERIES)\n .map(([key, item]) => ({ key, label: item.label, values: item.values, other: false }));\n const rest = ranked.slice(MAX_NAMED_SERIES);\n\n if (rest.length > 0) {\n const values = new Array<number>(buckets.length).fill(0);\n\n for (const [, item] of rest) {\n item.values.forEach((value, index) => {\n values[index] = (values[index] ?? 0) + value;\n });\n }\n\n series.push({ key: OTHER_KEY, label: \"Other\", values, other: true });\n }\n\n return { buckets, series };\n}\n\n/**\n * A stacked series set: `value(row)` per bucket, grouped by `keyOf(row)`; the\n * five keys with the largest sum are named, the rest summed into `other`\n * (key `__other`, label \"Other\"). Buckets with no rows are 0.\n */\nexport function seriesBy(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n keyOf: (row: DevtoolsAiRollupDelta) => string,\n labelOf: (key: string) => string,\n value: (row: DevtoolsAiRollupDelta) => number,\n): DevtoolsAiSeriesSet {\n return buildSeries(\n range,\n rows.map((row) => {\n const key = keyOf(row);\n\n return { bucket: bucketOf(row.hour, range), key, label: labelOf(key), value: value(row) };\n }),\n );\n}\n\n/** Tokens per bucket: `uncached` (input − cached), `cached`, `output`. */\nexport function tokenSeries(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n): DevtoolsAiSeriesSet {\n const buckets = bucketStarts(range);\n const uncached = new Array<number>(buckets.length).fill(0);\n const cached = new Array<number>(buckets.length).fill(0);\n const output = new Array<number>(buckets.length).fill(0);\n\n for (const row of rows) {\n const bucket = bucketOf(row.hour, range);\n\n if (bucket < 0 || bucket >= buckets.length) continue;\n\n uncached[bucket] = (uncached[bucket] ?? 0) + Math.max(0, row.inputTokens - row.cachedTokens);\n cached[bucket] = (cached[bucket] ?? 0) + row.cachedTokens;\n output[bucket] = (output[bucket] ?? 0) + row.outputTokens;\n }\n\n return {\n buckets,\n series: [\n { key: \"uncached\", label: \"Uncached input\", values: uncached, other: false },\n { key: \"cached\", label: \"Cached input\", values: cached, other: false },\n { key: \"output\", label: \"Output\", values: output, other: false },\n ],\n };\n}\n\n/** The error rate per bucket; `rate: null` where a bucket has no runs. */\nexport function errorRateSeries(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n): DevtoolsAiRatePoint[] {\n const points = bucketStarts(range).map((at) => ({\n at,\n runs: 0,\n errors: 0,\n rate: null as number | null,\n }));\n\n for (const row of rows) {\n const point = points[bucketOf(row.hour, range)];\n\n if (!point) continue;\n\n point.runs += row.runs;\n point.errors += row.failed + row.incomplete;\n }\n\n for (const point of points) point.rate = point.runs > 0 ? point.errors / point.runs : null;\n\n return points;\n}\n\n/** Failed runs per bucket by category (top five plus Other). */\nexport function errorSeries(\n rows: readonly DevtoolsAiRollupDelta[],\n range: DevtoolsAiResolvedRange,\n): DevtoolsAiSeriesSet {\n const entries: SeriesEntry[] = [];\n\n for (const row of rows) {\n const bucket = bucketOf(row.hour, range);\n\n for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) {\n const value = row.errors[category];\n\n if (value > 0) {\n entries.push({ bucket, key: category, label: DEVTOOLS_AI_ERROR_LABELS[category], value });\n }\n }\n }\n\n return buildSeries(range, entries);\n}\n\nfunction groupRows(\n rows: readonly DevtoolsAiRollupDelta[],\n keyOf: (row: DevtoolsAiRollupDelta) => string,\n): Map<string, DevtoolsAiRollupDelta[]> {\n const groups = new Map<string, DevtoolsAiRollupDelta[]>();\n\n for (const row of rows) {\n const key = keyOf(row);\n const group = groups.get(key);\n\n if (group) group.push(row);\n else groups.set(key, [row]);\n }\n\n return groups;\n}\n\nconst byKey = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/** Top rows by estimated cost (by runs when nothing was priced), at most `limit`. */\nexport function breakdown(\n rows: readonly DevtoolsAiRollupDelta[],\n by: \"agent\" | \"model\",\n limit: number,\n): DevtoolsAiBreakdownRow[] {\n const groups = groupRows(rows, (row) => (by === \"agent\" ? row.agent : modelKey(row)));\n const items = [...groups.entries()].map(([key, group]) => ({\n key,\n group,\n totals: totalsOf(group),\n }));\n const totalCost = items.reduce((sum, item) => sum + item.totals.cost.estimatedUsd, 0);\n const totalRuns = items.reduce((sum, item) => sum + item.totals.runs, 0);\n const byCost = totalCost > 0;\n\n items.sort(\n (a, b) =>\n (byCost ? b.totals.cost.estimatedUsd - a.totals.cost.estimatedUsd : 0) ||\n b.totals.runs - a.totals.runs ||\n byKey(a.key, b.key),\n );\n\n return items.slice(0, limit).map(({ key, group, totals }) => ({\n key,\n label: key,\n provider: by === \"model\" ? (group[0]?.provider ?? null) : null,\n totals,\n share: byCost\n ? totals.cost.estimatedUsd / totalCost\n : totalRuns > 0\n ? totals.runs / totalRuns\n : 0,\n }));\n}\n\nfunction pricingOf(totals: DevtoolsAiTotals): DevtoolsAiPricingState {\n const { pricedRuns, unpricedRuns } = totals.cost;\n\n // No run used tokens (all failed before the first call): nothing to price yet.\n if (pricedRuns === 0 && unpricedRuns === 0) return \"no-tokens\";\n\n if (unpricedRuns === 0) return \"set\";\n\n return pricedRuns === 0 ? \"missing\" : \"partial\";\n}\n\n/** One row per `provider/model`, most runs first. */\nexport function modelRows(rows: readonly DevtoolsAiRollupDelta[]): DevtoolsAiModelRow[] {\n const result: DevtoolsAiModelRow[] = [];\n\n for (const [key, group] of groupRows(rows, modelKey)) {\n const totals = totalsOf(group);\n const runsByAgent = new Map<string, number>();\n let lastSeenAt = 0;\n\n for (const row of group) {\n runsByAgent.set(row.agent, (runsByAgent.get(row.agent) ?? 0) + row.runs);\n\n if (row.runs > 0 && row.hour > lastSeenAt) lastSeenAt = row.hour;\n }\n\n const first = group[0];\n\n result.push({\n key,\n model: first?.model ?? \"\",\n provider: first?.provider ?? \"\",\n totals,\n pricing: pricingOf(totals),\n costPerRunUsd:\n totals.cost.pricedRuns > 0 ? totals.cost.estimatedUsd / totals.cost.pricedRuns : null,\n fallbackRate: totals.runs > 0 ? totals.fallbackRuns / totals.runs : 0,\n agents: [...runsByAgent.entries()]\n .sort((a, b) => b[1] - a[1] || byKey(a[0], b[0]))\n .slice(0, 5)\n .map(([agent]) => agent),\n lastSeenAt,\n });\n }\n\n return result.sort((a, b) => b.totals.runs - a.totals.runs || byKey(a.key, b.key));\n}\n\nfunction countErrors(\n rows: readonly DevtoolsAiRollupDelta[],\n category: DevtoolsAiErrorCategory,\n): number {\n return rows.reduce((sum, row) => sum + row.errors[category], 0);\n}\n\nfunction topCounts(\n rows: readonly DevtoolsAiRollupDelta[],\n category: DevtoolsAiErrorCategory,\n keyOf: (row: DevtoolsAiRollupDelta) => string,\n): { key: string; count: number }[] {\n const counts = new Map<string, number>();\n\n for (const row of rows) {\n const count = row.errors[category];\n\n if (count > 0) counts.set(keyOf(row), (counts.get(keyOf(row)) ?? 0) + count);\n }\n\n return [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || byKey(a[0], b[0]))\n .slice(0, 5)\n .map(([key, count]) => ({ key, count }));\n}\n\n/** Categories with at least one error, most first, with `previousCount` from `previousRows`. */\nexport function errorGroups(\n rows: readonly DevtoolsAiRollupDelta[],\n previousRows: readonly DevtoolsAiRollupDelta[],\n): DevtoolsAiErrorGroup[] {\n const counted = DEVTOOLS_AI_ERROR_CATEGORIES.map((category) => ({\n category,\n count: countErrors(rows, category),\n }));\n const total = counted.reduce((sum, item) => sum + item.count, 0);\n\n return counted\n .filter((item) => item.count > 0)\n .sort((a, b) => b.count - a.count)\n .map(({ category, count }) => ({\n category,\n label: DEVTOOLS_AI_ERROR_LABELS[category],\n count,\n share: total > 0 ? count / total : 0,\n previousCount: countErrors(previousRows, category),\n byModel: topCounts(rows, category, modelKey),\n byAgent: topCounts(rows, category, (row) => row.agent),\n }));\n}\n\n/** The distinct agents, models and providers, sorted. */\nexport function filterOptions(rows: readonly DevtoolsAiRollupDelta[]): DevtoolsAiFilterOptions {\n const agents = new Set<string>();\n const models = new Set<string>();\n const providers = new Set<string>();\n\n for (const row of rows) {\n agents.add(row.agent);\n models.add(modelKey(row));\n providers.add(row.provider);\n }\n\n return {\n agents: [...agents].sort(byKey),\n models: [...models].sort(byKey),\n providers: [...providers].sort(byKey),\n };\n}\n","import type { DevtoolsAiResolvedRange } from \"../../production/contracts\";\nimport { DevtoolsApiError } from \"../../production/errors\";\n\nconst HOUR_MS = 3_600_000;\nconst DAY_MS = 24 * HOUR_MS;\nconst MAX_FILTER_LENGTH = 200;\nconst PRESETS = {\n \"24h\": { length: DAY_MS, step: HOUR_MS },\n \"7d\": { length: 7 * DAY_MS, step: 6 * HOUR_MS },\n \"30d\": { length: 30 * DAY_MS, step: DAY_MS },\n} as const;\n\n/** The query string the Reports, Models and Errors routes read. */\nexport type DevtoolsAiRangeQuery = {\n /** `24h` (default), `7d`, `30d` or `custom`. */\n range?: string;\n /** Epoch ms; required with `custom`. */\n from?: string;\n /** Epoch ms; required with `custom`. */\n to?: string;\n /** The browser's `-new Date().getTimezoneOffset()`: minutes east of UTC, -840 to 840. Default 0. */\n tz?: string;\n agent?: string;\n /** `provider/model`. */\n model?: string;\n provider?: string;\n};\n\n/** A parsed range plus the filters, ready for the service. */\nexport type DevtoolsAiReportQuery = {\n range: DevtoolsAiResolvedRange;\n previous: { from: number; to: number };\n /** `false` when part of the previous period is older than the kept history, so its totals are partial. */\n previousComplete: boolean;\n agent?: string;\n /** Split from `provider/model`. */\n model?: { provider: string; model: string };\n provider?: string;\n};\n\n/**\n * Parses and aligns a range:\n *\n * - `24h`: `to` = the next hour boundary after `now`, `from` = `to - 24h`, step 1 hour.\n * - `7d`: `to` as above, `from` = `to - 7d`, step 6 hours.\n * - `30d`: `to` = the next local midnight (by `tz`, rounded down to whole\n * hours), `from` = `to - 30d`, step 1 day.\n * - `custom`: `from` floored and `to` ceiled to hours; at least 1 hour, `from`\n * no older than `retentionDays`, `to` no later than the next hour; step 1\n * hour up to 48 hours, 6 hours up to 8 days, else 1 day (then widened to\n * local midnights, as for `30d`).\n *\n * `previous` is the same length just before `from`; `previousComplete` is\n * `false` when it starts before the retention cut-off. Filters longer than 200\n * characters, an unknown preset, a malformed number or a range outside the\n * rules throw `DevtoolsApiError(\"ai.range-invalid\")`.\n */\nexport function parseAiReportQuery(\n query: DevtoolsAiRangeQuery,\n options: { now: number; retentionDays: number },\n): DevtoolsAiReportQuery {\n const { now, retentionDays } = options;\n const utcOffsetMinutes = parseOffset(query.tz);\n const nextHour = (Math.floor(now / HOUR_MS) + 1) * HOUR_MS;\n // Whole-hour offsets only, so every day bucket starts on an hour boundary.\n const offsetMs = Math.floor(utcOffsetMinutes / 60) * HOUR_MS;\n const localMidnight = (at: number, round: (value: number) => number) =>\n round((at + offsetMs) / DAY_MS) * DAY_MS - offsetMs;\n const preset = query.range === undefined || query.range === \"\" ? \"24h\" : query.range;\n let from: number;\n let to: number;\n let stepMs: number;\n\n if (preset === \"24h\" || preset === \"7d\") {\n to = nextHour;\n from = to - PRESETS[preset].length;\n stepMs = PRESETS[preset].step;\n } else if (preset === \"30d\") {\n to = (Math.floor((now + offsetMs) / DAY_MS) + 1) * DAY_MS - offsetMs;\n from = to - PRESETS[\"30d\"].length;\n stepMs = PRESETS[\"30d\"].step;\n } else if (preset === \"custom\") {\n const rawFrom = parseEpoch(query.from);\n const rawTo = parseEpoch(query.to);\n\n if (rawTo <= rawFrom) throw new DevtoolsApiError(\"ai.range-invalid\");\n\n from = Math.floor(rawFrom / HOUR_MS) * HOUR_MS;\n to = Math.ceil(rawTo / HOUR_MS) * HOUR_MS;\n\n const oldest = Math.floor(now / HOUR_MS) * HOUR_MS - retentionDays * DAY_MS;\n\n if (from < oldest || to > nextHour) throw new DevtoolsApiError(\"ai.range-invalid\");\n\n const length = to - from;\n\n stepMs = length <= 48 * HOUR_MS ? HOUR_MS : length <= 8 * DAY_MS ? 6 * HOUR_MS : DAY_MS;\n\n if (stepMs === DAY_MS) {\n // Day buckets are labelled by date, so they run from local midnight to local midnight\n // (the start no earlier than the kept history, the end at most the coming midnight).\n from = Math.max(localMidnight(from, Math.floor), localMidnight(oldest, Math.ceil));\n to = localMidnight(to, Math.ceil);\n }\n } else {\n throw new DevtoolsApiError(\"ai.range-invalid\");\n }\n\n const agent = parseFilter(query.agent);\n const provider = parseFilter(query.provider);\n const modelKey = parseFilter(query.model);\n let model: DevtoolsAiReportQuery[\"model\"];\n\n if (modelKey !== undefined) {\n // The provider is everything before the first slash; model names may contain slashes themselves.\n const slash = modelKey.indexOf(\"/\");\n\n if (slash <= 0 || slash === modelKey.length - 1) throw new DevtoolsApiError(\"ai.range-invalid\");\n\n model = { provider: modelKey.slice(0, slash), model: modelKey.slice(slash + 1) };\n }\n\n const previousFrom = from - (to - from);\n\n return {\n range: { preset, from, to, stepMs, utcOffsetMinutes },\n previous: { from: previousFrom, to: from },\n previousComplete: previousFrom >= Math.floor(now / HOUR_MS) * HOUR_MS - retentionDays * DAY_MS,\n ...(agent === undefined ? {} : { agent }),\n ...(model === undefined ? {} : { model }),\n ...(provider === undefined ? {} : { provider }),\n };\n}\n\nfunction parseOffset(value: string | undefined): number {\n if (value === undefined || value === \"\") return 0;\n\n const offset = /^-?\\d{1,4}$/.test(value) ? Number(value) : Number.NaN;\n\n if (!Number.isInteger(offset) || offset < -840 || offset > 840) {\n throw new DevtoolsApiError(\"ai.range-invalid\");\n }\n\n return offset;\n}\n\nfunction parseEpoch(value: string | undefined): number {\n const epoch = value !== undefined && /^\\d{1,15}$/.test(value) ? Number(value) : Number.NaN;\n\n if (!Number.isSafeInteger(epoch)) throw new DevtoolsApiError(\"ai.range-invalid\");\n\n return epoch;\n}\n\nfunction parseFilter(value: string | undefined): string | undefined {\n if (value === undefined || value === \"\") return undefined;\n\n if (value.length > MAX_FILTER_LENGTH) throw new DevtoolsApiError(\"ai.range-invalid\");\n\n return value;\n}\n","import type {\n DevtoolsAiErrorsView,\n DevtoolsAiFailedRun,\n DevtoolsAiModelsView,\n DevtoolsAiReportView,\n} from \"../../production/contracts\";\nimport type { DevtoolsAiRollupDelta, DevtoolsAiRollupStore } from \"../types\";\nimport {\n breakdown,\n errorGroups,\n errorRateSeries,\n errorSeries,\n filterOptions,\n modelRows,\n seriesBy,\n tokenSeries,\n totalsOf,\n} from \"./aggregate\";\nimport { type DevtoolsAiRangeQuery, type DevtoolsAiReportQuery, parseAiReportQuery } from \"./range\";\nimport type { DevtoolsAiRecentFailuresFilter } from \"./runs\";\n\nconst CACHE_MS = 15_000;\nconst MAX_CACHE_ENTRIES = 20;\nconst TOP_LIMIT = 10;\nconst RECENT_LIMIT = 50;\n\n/** What the report service reads. */\nexport type DevtoolsAiReportServiceInput = {\n store: DevtoolsAiRollupStore;\n /** The writer's unsaved deltas, added to the stored rows. */\n pending: () => DevtoolsAiRollupDelta[];\n retentionDays: number;\n observationOff: () => boolean;\n /**\n * Development: recent failed runs from the trace store, newest first, scoped\n * to the page's range and filters; absent in production (`recent: null`).\n */\n recentFailures?: (filter: DevtoolsAiRecentFailuresFilter) => DevtoolsAiFailedRun[];\n now?: () => number;\n};\n\n/**\n * Answers the Reports, Models and Errors routes. Each call parses the query\n * (`parseAiReportQuery`, which throws `ai.range-invalid`), lists the stored\n * rows of the range (and of the previous period where the view needs it),\n * adds the matching pending deltas, and folds them with `aggregate.ts`.\n * Answers are cached for 15 seconds per query (at most 20 entries).\n */\nexport type DevtoolsAiReportService = {\n report(query: DevtoolsAiRangeQuery): Promise<DevtoolsAiReportView>;\n models(query: DevtoolsAiRangeQuery): Promise<DevtoolsAiModelsView>;\n errors(query: DevtoolsAiRangeQuery): Promise<DevtoolsAiErrorsView>;\n};\n\nexport function createAiReportService(\n input: DevtoolsAiReportServiceInput,\n): DevtoolsAiReportService {\n const now = input.now ?? Date.now;\n const cache = new Map<string, { at: number; value: unknown }>();\n\n /** The rows of the previous period and the range, stored plus unsaved, before the filters. */\n async function load(parsed: DevtoolsAiReportQuery): Promise<{\n rows: DevtoolsAiRollupDelta[];\n previousRows: DevtoolsAiRollupDelta[];\n scoped: DevtoolsAiRollupDelta[];\n }> {\n const { range, previous } = parsed;\n const stored: DevtoolsAiRollupDelta[] = await input.store.list({\n fromHour: previous.from,\n toHour: range.to,\n });\n const all = [...stored, ...input.pending()].filter(\n (row) => row.hour >= previous.from && row.hour < range.to,\n );\n const inRange = all.filter((row) => row.hour >= range.from);\n const matches = (row: DevtoolsAiRollupDelta): boolean =>\n (parsed.agent === undefined || row.agent === parsed.agent) &&\n (parsed.provider === undefined || row.provider === parsed.provider) &&\n (parsed.model === undefined ||\n (row.provider === parsed.model.provider && row.model === parsed.model.model));\n\n return {\n // Unfiltered rows of the range: the filter row offers every value that exists, not only the chosen ones.\n rows: inRange,\n previousRows: all.filter((row) => row.hour < range.from && matches(row)),\n scoped: inRange.filter(matches),\n };\n }\n\n /** Parses first (so a bad range throws and is never cached), then answers from the cache or `build`. */\n async function answer<T>(\n view: string,\n query: DevtoolsAiRangeQuery,\n build: (parsed: DevtoolsAiReportQuery) => Promise<T>,\n ): Promise<T> {\n const at = now();\n const parsed = parseAiReportQuery(query, { now: at, retentionDays: input.retentionDays });\n const key = `${view}|${JSON.stringify([\n query.range ?? \"\",\n query.from ?? \"\",\n query.to ?? \"\",\n query.tz ?? \"\",\n query.agent ?? \"\",\n query.model ?? \"\",\n query.provider ?? \"\",\n ])}`;\n const cached = cache.get(key);\n\n if (cached && at - cached.at < CACHE_MS) return cached.value as T;\n\n const value = await build(parsed);\n\n cache.delete(key);\n cache.set(key, { at, value });\n\n for (const oldest of cache.keys()) {\n if (cache.size <= MAX_CACHE_ENTRIES) break;\n\n cache.delete(oldest);\n }\n\n return value;\n }\n\n return {\n report: (query) =>\n answer(\"report\", query, async (parsed) => {\n const { rows, previousRows, scoped } = await load(parsed);\n const { range } = parsed;\n const unpriced = new Set<string>();\n\n for (const row of scoped) {\n if (row.unpricedRuns > 0) unpriced.add(`${row.provider}/${row.model}`);\n }\n\n return {\n available: true as const,\n range,\n previousRange: parsed.previous,\n previousComplete: parsed.previousComplete,\n totals: totalsOf(scoped),\n previous: totalsOf(previousRows),\n costByModel: seriesBy(\n scoped,\n range,\n (row) => `${row.provider}/${row.model}`,\n (key) => key,\n (row) => row.costUsd,\n ),\n tokens: tokenSeries(scoped, range),\n errorRate: errorRateSeries(scoped, range),\n topAgents: breakdown(scoped, \"agent\", TOP_LIMIT),\n topModels: breakdown(scoped, \"model\", TOP_LIMIT),\n unpricedModels: [...unpriced].sort(),\n filters: filterOptions(rows),\n observationOff: input.observationOff(),\n generatedAt: now(),\n };\n }),\n\n models: (query) =>\n answer(\"models\", query, async (parsed) => {\n const { rows, scoped } = await load(parsed);\n\n return {\n available: true as const,\n range: parsed.range,\n totals: totalsOf(scoped),\n models: modelRows(scoped),\n runsByModel: seriesBy(\n scoped,\n parsed.range,\n (row) => `${row.provider}/${row.model}`,\n (key) => key,\n (row) => row.runs,\n ),\n filters: filterOptions(rows),\n observationOff: input.observationOff(),\n generatedAt: now(),\n };\n }),\n\n async errors(query) {\n const view = await answer(\"errors\", query, async (parsed) => {\n const { rows, previousRows, scoped } = await load(parsed);\n\n return {\n available: true as const,\n range: parsed.range,\n totals: totalsOf(scoped),\n previous: totalsOf(previousRows),\n previousComplete: parsed.previousComplete,\n groups: errorGroups(scoped, previousRows),\n overTime: errorSeries(scoped, parsed.range),\n recent: null,\n filters: filterOptions(rows),\n observationOff: input.observationOff(),\n generatedAt: now(),\n };\n });\n\n if (!input.recentFailures) return view;\n\n // Recent failures are read fresh (a failed run shows at once) and scoped like every other table.\n const { range, agent, provider, model } = parseAiReportQuery(query, {\n now: now(),\n retentionDays: input.retentionDays,\n });\n\n return {\n ...view,\n recent: input\n .recentFailures({\n from: range.from,\n to: range.to,\n ...(agent === undefined ? {} : { agent }),\n ...(provider === undefined ? {} : { provider }),\n ...(model === undefined ? {} : { model }),\n })\n .slice(0, RECENT_LIMIT),\n };\n },\n };\n}\n","import {\n DEVTOOLS_AI_ERROR_CATEGORIES,\n DEVTOOLS_AI_LATENCY_BUCKETS_MS,\n} from \"../../production/contracts\";\nimport type { DevtoolsAiRollupDelta, DevtoolsAiRollupRecord } from \"../types\";\nimport { emptyRollupDelta } from \"./extract\";\n\n/** A row of `devtools_ai_rollups`: snake_case columns, `err_*` and `lat_<n>` columns spelled out. */\nexport type DevtoolsAiRollupRow = Record<string, unknown>;\n\n/** The numeric counters and their column names (errors and latency are mapped separately). */\nconst COUNTER_COLUMNS = [\n [\"runs\", \"runs\"],\n [\"completed\", \"completed\"],\n [\"failed\", \"failed\"],\n [\"incomplete\", \"incomplete\"],\n [\"cancelled\", \"cancelled\"],\n [\"inputTokens\", \"input_tokens\"],\n [\"outputTokens\", \"output_tokens\"],\n [\"cachedTokens\", \"cached_tokens\"],\n [\"cacheWriteTokens\", \"cache_write_tokens\"],\n [\"reasoningTokens\", \"reasoning_tokens\"],\n [\"costUsd\", \"cost_usd\"],\n [\"pricedRuns\", \"priced_runs\"],\n [\"unpricedRuns\", \"unpriced_runs\"],\n [\"unpricedTokens\", \"unpriced_tokens\"],\n [\"fallbackRuns\", \"fallback_runs\"],\n [\"refusals\", \"refusals\"],\n [\"latencyCount\", \"latency_count\"],\n [\"latencySumMs\", \"latency_sum_ms\"],\n] as const;\n\nconst BUCKET_COUNT = DEVTOOLS_AI_LATENCY_BUCKETS_MS.length + 1;\n\n/** The column of an error category: `err_` plus the category with dashes as underscores. */\nfunction errorColumn(category: string): string {\n return `err_${category.replaceAll(\"-\", \"_\")}`;\n}\n\nfunction number(value: unknown): number {\n const parsed = typeof value === \"number\" ? value : Number(value);\n\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\n/** Every counter column with its amount; counters at 0 are left out. */\nfunction allCounters(delta: DevtoolsAiRollupDelta): Record<string, number> {\n const columns: Record<string, number> = {};\n\n for (const [field, column] of COUNTER_COLUMNS) columns[column] = delta[field];\n\n for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) {\n columns[errorColumn(category)] = delta.errors[category] ?? 0;\n }\n\n for (let index = 0; index < BUCKET_COUNT; index++) {\n columns[`lat_${index}`] = delta.latency[index] ?? 0;\n }\n\n return columns;\n}\n\n/** The `$inc` part of a delta: every counter column with its amount (zero counters left out). */\nexport function deltaToIncrements(delta: DevtoolsAiRollupDelta): Record<string, number> {\n const increments: Record<string, number> = {};\n\n for (const [column, amount] of Object.entries(allCounters(delta))) {\n if (amount !== 0) increments[column] = amount;\n }\n\n return increments;\n}\n\n/** A full row for a record (inserts and the memory/file stores' round-trip specs). */\nexport function recordToRow(record: DevtoolsAiRollupRecord): DevtoolsAiRollupRow {\n return {\n id: record.id,\n hour: record.hour,\n agent: record.agent,\n model: record.model,\n provider: record.provider,\n ...allCounters(record),\n updated_at: record.updatedAt,\n };\n}\n\n/** A record from a row; numbers a driver returns as strings are converted. */\nexport function rowToRecord(row: DevtoolsAiRollupRow): DevtoolsAiRollupRecord {\n const record: DevtoolsAiRollupRecord = {\n ...emptyRollupDelta({\n hour: number(row.hour),\n agent: String(row.agent ?? \"\"),\n model: String(row.model ?? \"\"),\n provider: String(row.provider ?? \"\"),\n }),\n id: String(row.id ?? \"\"),\n updatedAt: number(row.updated_at),\n };\n\n for (const [field, column] of COUNTER_COLUMNS) record[field] = number(row[column]);\n\n for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) {\n record.errors[category] = number(row[errorColumn(category)]);\n }\n\n for (let index = 0; index < BUCKET_COUNT; index++) {\n record.latency[index] = number(row[`lat_${index}`]);\n }\n\n return record;\n}\n","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","import type { DevtoolsAiRollupDelta, DevtoolsAiRollupStore } from \"../types\";\nimport { deltaToIncrements, rowToRecord, type DevtoolsAiRollupRow } from \"./mapping\";\nimport { rollupId } from \"./extract\";\nimport { DevtoolsAiRollupIncrementError } from \"./increment-error\";\n\n/** The part of cascade's query builder this store uses. */\ninterface RowQuery {\n where(field: string, operator: string, value: unknown): RowQuery;\n lean(): RowQuery;\n get(): Promise<DevtoolsAiRollupRow[]>;\n delete(): Promise<number>;\n}\n\n/** Rows written in one go; each row is its own atomic statement, so this only bounds open queries. */\nconst INCREMENT_CONCURRENCY = 10;\n\n/**\n * The production `DevtoolsAiRollupStore`: table/collection\n * `devtools_ai_rollups` in the app database through `@warlock.js/cascade`\n * (model `DevtoolsAiRollupRow`, migration `DevtoolsAiRollupsMigration`).\n * `increment` runs one atomic `$inc` upsert per delta keyed by `id`\n * (`$setOnInsert` the dimensions, `$set` `updated_at`), so every process adds\n * into the same rows. When some upserts fail it throws\n * `DevtoolsAiRollupIncrementError` with the unsaved deltas. `verify` checks the table exists and answers `false`\n * when it does not. Imports cascade lazily.\n *\n * Both drivers support the upsert: MongoDB natively, PostgreSQL as\n * `INSERT … ON CONFLICT (id) DO UPDATE` (the id is the primary key, the filter\n * names it, and the inserted row takes the `$inc` amounts as its values).\n */\nexport async function createCascadeAiRollupStore(\n options: { now?: () => number } = {},\n): Promise<DevtoolsAiRollupStore> {\n const now = options.now ?? Date.now;\n const { DevtoolsAiRollupRow: Rollups } = await import(\"../../production/store/models\");\n\n // Throws when the app has no data source.\n Rollups.getDataSource();\n\n const query = () => Rollups.query() as unknown as RowQuery;\n\n return {\n async verify() {\n try {\n return await Rollups.getDriver().blueprint.tableExists(Rollups.table);\n } catch {\n return false;\n }\n },\n async increment(deltas) {\n // Every delta is tried; the ones that failed are reported so a retry never adds a saved one twice.\n const unwritten: DevtoolsAiRollupDelta[] = [];\n let firstError: unknown;\n\n for (let start = 0; start < deltas.length; start += INCREMENT_CONCURRENCY) {\n const chunk = deltas.slice(start, start + INCREMENT_CONCURRENCY);\n const settled = await Promise.allSettled(\n chunk.map(async (delta) => {\n const increments = deltaToIncrements(delta);\n const operations: Record<string, Record<string, unknown>> = {\n $set: { updated_at: now() },\n $setOnInsert: {\n hour: delta.hour,\n agent: delta.agent,\n model: delta.model,\n provider: delta.provider,\n },\n };\n\n // An empty `$inc` is an error on MongoDB.\n if (Object.keys(increments).length > 0) operations.$inc = increments;\n\n await Rollups.atomic({ id: rollupId(delta) }, operations as never, {\n upsert: true,\n trustedFilter: true,\n });\n }),\n );\n\n settled.forEach((outcome, index) => {\n if (outcome.status === \"fulfilled\") return;\n\n firstError ??= outcome.reason;\n unwritten.push(chunk[index]!);\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 async list(filter) {\n const target = query()\n .lean()\n .where(\"hour\", \">=\", filter.fromHour)\n .where(\"hour\", \"<\", filter.toHour);\n\n if (filter.agent !== undefined) target.where(\"agent\", \"=\", filter.agent);\n if (filter.model !== undefined) target.where(\"model\", \"=\", filter.model);\n if (filter.provider !== undefined) target.where(\"provider\", \"=\", filter.provider);\n\n return (await target.get()).map(rowToRecord);\n },\n async prune(beforeHour) {\n return query().where(\"hour\", \"<\", beforeHour).delete();\n },\n };\n}\n","import type {\n DevtoolsAiRollupDelta,\n DevtoolsAiRollupFilter,\n DevtoolsAiRollupRecord,\n DevtoolsAiRollupStore,\n} from \"../types\";\nimport { addRollupCounters, rollupId } from \"./extract\";\n\n/** Whether a record passes the filter (shared by the memory and file stores). */\nexport function matchesAiRollupFilter(\n record: DevtoolsAiRollupRecord,\n filter: DevtoolsAiRollupFilter,\n): boolean {\n return (\n record.hour >= filter.fromHour &&\n record.hour < filter.toHour &&\n (filter.agent === undefined || record.agent === filter.agent) &&\n (filter.model === undefined || record.model === filter.model) &&\n (filter.provider === undefined || record.provider === filter.provider)\n );\n}\n\n/** Adds a delta into `rows` (creating the record when missing); shared by the memory and file stores. */\nexport function applyAiRollupDelta(\n rows: Map<string, DevtoolsAiRollupRecord>,\n delta: DevtoolsAiRollupDelta,\n at: number,\n): void {\n const id = rollupId(delta);\n const existing = rows.get(id);\n\n if (existing) {\n addRollupCounters(existing, delta);\n existing.updatedAt = at;\n\n return;\n }\n\n rows.set(id, { ...structuredClone(delta), id, updatedAt: at });\n}\n\n/** An in-memory `DevtoolsAiRollupStore` for specs (and the report service's own specs). */\nexport function createMemoryAiRollupStore(\n options: { now?: () => number } = {},\n): DevtoolsAiRollupStore {\n const now = options.now ?? Date.now;\n const rows = new Map<string, DevtoolsAiRollupRecord>();\n\n return {\n async verify() {\n return true;\n },\n async increment(deltas) {\n for (const delta of deltas) applyAiRollupDelta(rows, delta, now());\n },\n async list(filter) {\n return [...rows.values()]\n .filter((row) => matchesAiRollupFilter(row, filter))\n .map((row) => structuredClone(row));\n },\n async prune(beforeHour) {\n let removed = 0;\n\n for (const [id, row] of rows) {\n if (row.hour < beforeHour) {\n rows.delete(id);\n removed++;\n }\n }\n\n return removed;\n },\n };\n}\n","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","import type {\n DevtoolsAiRollupDelta,\n DevtoolsAiRollupWriter,\n DevtoolsAiRollupWriterInput,\n} from \"../types\";\nimport { addRollupCounters, rollupId, traceToRollupDeltas } from \"./extract\";\nimport { DevtoolsAiRollupIncrementError } from \"./increment-error\";\n\nconst HOUR_MS = 3_600_000;\nconst DAY_MS = 24 * HOUR_MS;\nconst PRUNE_EVERY_MS = 10 * 60_000;\nconst WARN_EVERY_MS = 60_000;\nconst STOP_GRACE_MS = 5000;\nconst DEFAULT_MAX_KEYS = 2000;\n\n/**\n * Starts the rollup writer: `record(trace)` adds the trace's deltas to an\n * in-memory map keyed by `rollupId`; every `options.flushIntervalMs` the map\n * is swapped out and written with `store.increment` (a failed write merges\n * the unsaved deltas back for the next try, only those when the store says\n * which, and warns at most once a minute); every\n * 10 minutes it prunes hours older than `options.retentionDays`. Timers are\n * `unref`ed and writes are serialised (never two at once). `stop()` clears\n * the timers and flushes, giving up after 5 seconds.\n */\nexport function startAiRollupWriter(input: DevtoolsAiRollupWriterInput): DevtoolsAiRollupWriter {\n const { store, totalCost, options } = input;\n const now = input.now ?? Date.now;\n const warn = input.warn ?? ((message: string) => console.warn(message));\n const maxKeys = input.maxKeys ?? DEFAULT_MAX_KEYS;\n\n let pending = new Map<string, DevtoolsAiRollupDelta>();\n // The batch being written: still shown by `pending()` until the write settles, so reports never dip.\n let writing: readonly DevtoolsAiRollupDelta[] = [];\n let inflight: Promise<void> = Promise.resolve();\n let lastWarnAt: number | undefined;\n\n const warnOnce = (task: string, error: unknown): void => {\n const at = now();\n\n if (lastWarnAt !== undefined && at - lastWarnAt < WARN_EVERY_MS) return;\n\n lastWarnAt = at;\n\n const reason = error instanceof Error ? error.message : String(error);\n\n warn(`Devtools could not ${task}: ${reason}. It will try again.`);\n };\n\n /** Adds a delta, folding a new key into agent `(other)` once `maxKeys` is reached. */\n const add = (delta: DevtoolsAiRollupDelta): void => {\n let id = rollupId(delta);\n let target = pending.get(id);\n let source = delta;\n\n if (!target && pending.size >= maxKeys) {\n source = { ...structuredClone(delta), agent: \"(other)\" };\n id = rollupId(source);\n target = pending.get(id);\n }\n\n if (target) {\n addRollupCounters(target, source);\n } else {\n pending.set(id, structuredClone(source));\n }\n };\n\n const writeNow = async (): Promise<void> => {\n if (pending.size === 0) return;\n\n const batch = [...pending.values()];\n\n pending = new Map();\n writing = batch;\n\n try {\n await store.increment(batch);\n } catch (error) {\n // Only what was not saved goes back: a partly saved batch must never be added twice.\n const unsaved = error instanceof DevtoolsAiRollupIncrementError ? error.unwritten : batch;\n\n for (const delta of unsaved) add(delta);\n\n warnOnce(\"save AI totals\", error);\n } finally {\n writing = [];\n }\n };\n\n const flush = (): Promise<void> => {\n inflight = inflight.then(writeNow);\n\n return inflight;\n };\n\n const prune = async (): Promise<void> => {\n try {\n const cutoff = Math.floor(now() / HOUR_MS) * HOUR_MS - options.retentionDays * DAY_MS;\n\n await store.prune(cutoff);\n } catch (error) {\n warnOnce(\"remove old AI totals\", error);\n }\n };\n\n const flushTimer = setInterval(() => void flush(), options.flushIntervalMs);\n const pruneTimer = setInterval(() => void prune(), PRUNE_EVERY_MS);\n\n flushTimer.unref();\n pruneTimer.unref();\n\n return {\n record(trace) {\n try {\n for (const delta of traceToRollupDeltas(trace, totalCost)) add(delta);\n } catch {\n // A trace that cannot be summarised must never reach the trace publisher.\n }\n },\n pending() {\n return [...writing, ...pending.values()].map((delta) => structuredClone(delta));\n },\n flush,\n async stop() {\n clearInterval(flushTimer);\n clearInterval(pruneTimer);\n\n let timer: NodeJS.Timeout | undefined;\n const giveUp = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, STOP_GRACE_MS);\n timer.unref();\n });\n\n try {\n await Promise.race([flush(), giveUp]);\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n","import path from \"node:path\";\nimport type { DevtoolsAiFailedRun, DevtoolsAiUnavailableView } from \"../production/contracts\";\nimport { describeAiUnavailable, loadAiPackages, toAiUnavailableView } from \"../sources/ai-source\";\nimport { createAiReportService, type DevtoolsAiReportService } from \"./reports/service\";\nimport type { DevtoolsAiRecentFailuresFilter, DevtoolsAiRunHelpers } from \"./reports/runs\";\nimport { createCascadeAiRollupStore, createFileAiRollupStore, startAiRollupWriter } from \"./rollup\";\nimport type {\n DevtoolsAiFeed,\n DevtoolsAiRollupStore,\n DevtoolsAiRollupWriter,\n ResolvedDevtoolsAiOptions,\n} from \"./types\";\n\n/** The AI reports wiring of one process, as the routes receive it. */\nexport type DevtoolsAiReports =\n | {\n available: true;\n service: DevtoolsAiReportService;\n writer: DevtoolsAiRollupWriter;\n dispose(): Promise<void>;\n }\n | (DevtoolsAiUnavailableView & { dispose(): Promise<void> });\n\n/**\n * Loads Panoptic's trace feed (`subscribeTraces`, `totalCostUsd`) and\n * `@warlock.js/ai`'s observer registry lazily, plus the Runs helpers. Returns\n * `{ unavailable }` (`ai-missing`, `panoptic-missing`, `panoptic-failed`)\n * when they do not load. Shared by the development and production wiring.\n */\nexport async function loadAiFeed(deps?: {\n load?: (name: string) => Promise<unknown>;\n version?: (name: string) => string | null;\n}): Promise<\n | { feed: DevtoolsAiFeed; helpers: DevtoolsAiRunHelpers }\n | { unavailable: DevtoolsAiUnavailableView }\n> {\n const loaded = await loadAiPackages(deps);\n\n if (\"unavailable\" in loaded) return { unavailable: toAiUnavailableView(loaded.unavailable) };\n\n const { panoptic, observationOff } = loaded;\n\n return {\n feed: {\n subscribe: (listener) => panoptic.subscribeTraces(listener),\n totalCost: (usage) => panoptic.totalCostUsd(usage),\n observationOff,\n },\n helpers: {\n filterTraces: panoptic.filterTraces,\n groupBySession: panoptic.groupBySession,\n groupByPrompt: panoptic.groupByPrompt,\n groupByType: panoptic.groupByType,\n percentile: panoptic.percentile,\n tracePromptKey: panoptic.tracePromptKey,\n },\n };\n}\n\nconst TABLE_MISSING_WARNING =\n \"AI reports are off: the devtools_ai_rollups table is missing. Run the devtools migrations (warlock migrate), then restart.\";\n\n/**\n * Starts the AI reports of this process: with `options.reports` off answers\n * `reports-off`; otherwise builds the store for the mode (development: the\n * file store in `directory`; production: the cascade store, `table-missing`\n * when `verify()` is false, logged once with the migration hint), starts the\n * rollup writer on `feed.subscribe`, and builds the report service.\n * `dispose` unsubscribes and stops the writer (final flush).\n */\nexport async function attachAiReports(input: {\n feed: DevtoolsAiFeed;\n options: ResolvedDevtoolsAiOptions;\n /** Development only: where the file store writes (core's `storagePath(\"devtools/ai-rollups\")`). */\n directory?: string;\n /** Development only: recent failures from the Runs store, scoped to a page's range and filters. */\n recentFailures?: (filter: DevtoolsAiRecentFailuresFilter) => DevtoolsAiFailedRun[];\n warn: (message: string) => void;\n}): Promise<DevtoolsAiReports> {\n const { feed, options, warn } = input;\n const off = (reason: \"reports-off\" | \"table-missing\"): DevtoolsAiReports => ({\n ...toAiUnavailableView(describeAiUnavailable(reason)),\n async dispose() {},\n });\n\n if (!options.reports) return off(\"reports-off\");\n\n const production = options.mode === \"production\";\n let store: DevtoolsAiRollupStore;\n\n try {\n store = production\n ? await createCascadeAiRollupStore()\n : createFileAiRollupStore({\n directory:\n input.directory ?? path.join(process.cwd(), \"storage\", \"devtools\", \"ai-rollups\"),\n });\n\n if (!(await store.verify())) {\n warn(TABLE_MISSING_WARNING);\n\n return off(\"table-missing\");\n }\n } catch (error) {\n warn(`${TABLE_MISSING_WARNING} (${error instanceof Error ? error.message : String(error)})`);\n\n return off(\"table-missing\");\n }\n\n const writer = startAiRollupWriter({ store, totalCost: feed.totalCost, options, warn });\n const unsubscribe = feed.subscribe((trace) => writer.record(trace));\n const service = createAiReportService({\n store,\n pending: () => writer.pending(),\n retentionDays: options.retentionDays,\n observationOff: () => feed.observationOff(),\n ...(input.recentFailures ? { recentFailures: input.recentFailures } : {}),\n });\n\n return {\n available: true,\n service,\n writer,\n async dispose() {\n unsubscribe();\n await writer.stop();\n },\n };\n}\n\n/** The global key devtools publishes once mounted, read by Panoptic to keep its own dashboard off. */\nexport const DEVTOOLS_MOUNTED_KEY = Symbol.for(\"@warlock.js/devtools.mounted\");\n\n/** What is published under `DEVTOOLS_MOUNTED_KEY`. */\nexport type DevtoolsMountedMarker = { path: string; mode: \"development\" | \"production\" };\n"],"mappings":";;;;;;;;;;AAIA,MAAa,6BAAqE;CAChF,aAAa;CACb,YAAY;AACd;;AAGA,MAAa,gCA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AAE,EAAE;EAE3F,OAAO,IAAI,eAAe;CAC5B;CAEA,MAAM,SAAS,oBAAoB;EAAE;EAAO,WAAW,KAAK;EAAW;EAAS;CAAK,CAAC;CACtF,MAAM,cAAc,KAAK,WAAW,UAAU,OAAO,OAAO,KAAK,CAAC;CASlE,OAAO;EACL,WAAW;EACX,SAVc,sBAAsB;GACpC;GACA,eAAe,OAAO,QAAQ;GAC9B,eAAe,QAAQ;GACvB,sBAAsB,KAAK,eAAe;GAC1C,GAAI,MAAM,iBAAiB,EAAE,gBAAgB,MAAM,eAAe,IAAI,CAAC;EACzE,CAIQ;EACN;EACA,MAAM,UAAU;GACd,YAAY;GACZ,MAAM,OAAO,KAAK;EACpB;CACF;AACF;;AAGA,MAAa,uBAAuB,OAAO,IAAI,8BAA8B"}
@@ -1,5 +1,5 @@
1
- const require_app_versions = require("./app-versions-DfpPZOI2.cjs");
2
- const require_errors = require("./errors-BadbSDX8.cjs");
1
+ const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
2
+ const require_errors = require("./errors-DNQ-g49I.cjs");
3
3
  const require_ip = require("./ip-DbNhPOzi.cjs");
4
4
  const require_helpers = require("./helpers-BcMBFy9v.cjs");
5
5
  let node_crypto = require("node:crypto");
@@ -197,7 +197,7 @@ function createDevtoolsAuth(deps) {
197
197
  const cached = blockedIps.get(client);
198
198
  if (cached && now() < cached.until && cached.checkedAt >= stateResetAt) return true;
199
199
  if (await store.audit.count({
200
- types: require_app_versions.DEVTOOLS_FAILURE_AUDIT_TYPES,
200
+ types: require_errors.DEVTOOLS_FAILURE_AUDIT_TYPES,
201
201
  since,
202
202
  ip
203
203
  }) < limits.ip) {
@@ -232,7 +232,7 @@ function createDevtoolsAuth(deps) {
232
232
  const locked = state.lockedUntil !== null && state.lockedUntil > at;
233
233
  const overIp = await ipOverLimit(ip, since, stateResetAt);
234
234
  const accountCount = await store.audit.count({
235
- types: require_app_versions.DEVTOOLS_FAILURE_AUDIT_TYPES,
235
+ types: require_errors.DEVTOOLS_FAILURE_AUDIT_TYPES,
236
236
  since: accountSince,
237
237
  accountId: account?.id ?? "-"
238
238
  });
@@ -247,7 +247,7 @@ function createDevtoolsAuth(deps) {
247
247
  if (state.lockedUntil !== null && state.lockedUntil > at) return;
248
248
  const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);
249
249
  const count = await store.audit.count({
250
- types: require_app_versions.DEVTOOLS_FAILURE_AUDIT_TYPES,
250
+ types: require_errors.DEVTOOLS_FAILURE_AUDIT_TYPES,
251
251
  since
252
252
  });
253
253
  if (count < limits.global) return;
@@ -1289,4 +1289,4 @@ exports.generateTemporaryPassword = require_helpers.generateTemporaryPassword;
1289
1289
  exports.generateToken = require_helpers.generateToken;
1290
1290
  exports.hashToken = require_helpers.hashToken;
1291
1291
  exports.loadDevtoolsPasskeys = loadDevtoolsPasskeys;
1292
- //# sourceMappingURL=auth-B3wyjJnQ.cjs.map
1292
+ //# sourceMappingURL=auth-ChHh5E7j.cjs.map