@warlock.js/devtools 5.59.0 → 5.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/cjs/{app-versions-DfpPZOI2.cjs → app-versions-C_ZyzuvD.cjs} +1 -116
  3. package/cjs/app-versions-C_ZyzuvD.cjs.map +1 -0
  4. package/cjs/attach-D5aMqUnA.cjs +1342 -0
  5. package/cjs/attach-D5aMqUnA.cjs.map +1 -0
  6. package/cjs/{auth-B3wyjJnQ.cjs → auth-ChHh5E7j.cjs} +6 -6
  7. package/cjs/{auth-B3wyjJnQ.cjs.map → auth-ChHh5E7j.cjs.map} +1 -1
  8. package/cjs/{boot-nczSvJ_F.cjs → boot-Dg5YZGGR.cjs} +77 -14
  9. package/cjs/boot-Dg5YZGGR.cjs.map +1 -0
  10. package/cjs/{capture-CuyT8Vab.cjs → capture-CBgONYhk.cjs} +4 -4
  11. package/cjs/{capture-CuyT8Vab.cjs.map → capture-CBgONYhk.cjs.map} +1 -1
  12. package/cjs/{cascade-store-CuRRYzt_.cjs → cascade-store-DUT2Laha.cjs} +3 -3
  13. package/cjs/{cascade-store-CuRRYzt_.cjs.map → cascade-store-DUT2Laha.cjs.map} +1 -1
  14. package/cjs/{current-request-id-CeQhRz9Q.cjs → current-request-id-Badec-TH.cjs} +2 -2
  15. package/cjs/{current-request-id-CeQhRz9Q.cjs.map → current-request-id-Badec-TH.cjs.map} +1 -1
  16. package/cjs/{errors-BadbSDX8.cjs → errors-DNQ-g49I.cjs} +198 -1
  17. package/cjs/errors-DNQ-g49I.cjs.map +1 -0
  18. package/cjs/extract-8kaX_cUV.cjs +1103 -0
  19. package/cjs/extract-8kaX_cUV.cjs.map +1 -0
  20. package/cjs/{histogram-DTOGnNBW.cjs → histogram-CkoVizdf.cjs} +6 -6
  21. package/cjs/{histogram-DTOGnNBW.cjs.map → histogram-CkoVizdf.cjs.map} +1 -1
  22. package/cjs/{http-Biauhqi0.cjs → http-DCVCf44M.cjs} +25 -8
  23. package/cjs/http-DCVCf44M.cjs.map +1 -0
  24. package/cjs/index.cjs +1 -1
  25. package/cjs/{insights-BjJA6Ret.cjs → insights-CFof59kF.cjs} +3 -3
  26. package/cjs/{insights-BjJA6Ret.cjs.map → insights-CFof59kF.cjs.map} +1 -1
  27. package/cjs/migrations-BQdNOL5_.cjs +30 -0
  28. package/cjs/migrations-BQdNOL5_.cjs.map +1 -0
  29. package/cjs/{migrations-BP4cYTGo.cjs → models-DF1agAm4.cjs} +106 -24
  30. package/cjs/models-DF1agAm4.cjs.map +1 -0
  31. package/cjs/{process-panel-DskSA7Cm.cjs → process-panel-D3D9Y_dc.cjs} +4 -4
  32. package/cjs/{process-panel-DskSA7Cm.cjs.map → process-panel-D3D9Y_dc.cjs.map} +1 -1
  33. package/cjs/production/index.cjs +4 -4
  34. package/cjs/runs-DECWPGnq.cjs +390 -0
  35. package/cjs/runs-DECWPGnq.cjs.map +1 -0
  36. package/cjs/{server-D3XRbSSb.cjs → server-CC5DpObz.cjs} +8 -7
  37. package/cjs/{server-D3XRbSSb.cjs.map → server-CC5DpObz.cjs.map} +1 -1
  38. package/cjs/{src-QcNghoYN.cjs → src-VyOjEEAo.cjs} +178 -23
  39. package/cjs/src-VyOjEEAo.cjs.map +1 -0
  40. package/cjs/{store-CNFv3wVp.cjs → store-EFn4wp0T.cjs} +2 -2
  41. package/cjs/{stream-route-BqyAlfxQ.cjs → stream-route-DFHuIWgg.cjs} +107 -15
  42. package/cjs/stream-route-DFHuIWgg.cjs.map +1 -0
  43. package/esm/ai/attach.mjs +92 -0
  44. package/esm/ai/attach.mjs.map +1 -0
  45. package/esm/ai/options.mjs +31 -0
  46. package/esm/ai/options.mjs.map +1 -0
  47. package/esm/ai/reports/aggregate.mjs +330 -0
  48. package/esm/ai/reports/aggregate.mjs.map +1 -0
  49. package/esm/ai/reports/evaluate.mjs +108 -0
  50. package/esm/ai/reports/evaluate.mjs.map +1 -0
  51. package/esm/ai/reports/range.mjs +121 -0
  52. package/esm/ai/reports/range.mjs.map +1 -0
  53. package/esm/ai/reports/runs.d.mts +2 -0
  54. package/esm/ai/reports/runs.mjs +212 -0
  55. package/esm/ai/reports/runs.mjs.map +1 -0
  56. package/esm/ai/reports/service.mjs +132 -0
  57. package/esm/ai/reports/service.mjs.map +1 -0
  58. package/esm/ai/rollup/cascade-store.mjs +84 -0
  59. package/esm/ai/rollup/cascade-store.mjs.map +1 -0
  60. package/esm/ai/rollup/categories.mjs +67 -0
  61. package/esm/ai/rollup/categories.mjs.map +1 -0
  62. package/esm/ai/rollup/extract.mjs +225 -0
  63. package/esm/ai/rollup/extract.mjs.map +1 -0
  64. package/esm/ai/rollup/file-store.mjs +147 -0
  65. package/esm/ai/rollup/file-store.mjs.map +1 -0
  66. package/esm/ai/rollup/histogram.mjs +42 -0
  67. package/esm/ai/rollup/histogram.mjs.map +1 -0
  68. package/esm/ai/rollup/increment-error.mjs +19 -0
  69. package/esm/ai/rollup/increment-error.mjs.map +1 -0
  70. package/esm/ai/rollup/index.mjs +9 -0
  71. package/esm/ai/rollup/mapping.mjs +69 -0
  72. package/esm/ai/rollup/mapping.mjs.map +1 -0
  73. package/esm/ai/rollup/memory-store.mjs +26 -0
  74. package/esm/ai/rollup/memory-store.mjs.map +1 -0
  75. package/esm/ai/rollup/writer.mjs +113 -0
  76. package/esm/ai/rollup/writer.mjs.map +1 -0
  77. package/esm/ai/types.d.mts +29 -0
  78. package/esm/ai/types.d.mts.map +1 -0
  79. package/esm/devtools-connector.d.mts.map +1 -1
  80. package/esm/devtools-connector.mjs +54 -2
  81. package/esm/devtools-connector.mjs.map +1 -1
  82. package/esm/index.d.mts +3 -2
  83. package/esm/options.mjs +4 -0
  84. package/esm/options.mjs.map +1 -1
  85. package/esm/production/boot.mjs +69 -3
  86. package/esm/production/boot.mjs.map +1 -1
  87. package/esm/production/contracts.d.mts +371 -2
  88. package/esm/production/contracts.d.mts.map +1 -1
  89. package/esm/production/contracts.mjs +64 -2
  90. package/esm/production/contracts.mjs.map +1 -1
  91. package/esm/production/errors.mjs +8 -0
  92. package/esm/production/errors.mjs.map +1 -1
  93. package/esm/production/http/access.mjs +6 -0
  94. package/esm/production/http/access.mjs.map +1 -1
  95. package/esm/production/http/mount.mjs +13 -0
  96. package/esm/production/http/mount.mjs.map +1 -1
  97. package/esm/production/index.d.mts +2 -2
  98. package/esm/production/store/migrations.d.mts +1 -1
  99. package/esm/production/store/migrations.d.mts.map +1 -1
  100. package/esm/production/store/migrations.mjs +4 -2
  101. package/esm/production/store/migrations.mjs.map +1 -1
  102. package/esm/production/store/models/ai-rollup.migration.mjs +48 -0
  103. package/esm/production/store/models/ai-rollup.migration.mjs.map +1 -0
  104. package/esm/production/store/models/ai-rollup.model.mjs +13 -0
  105. package/esm/production/store/models/ai-rollup.model.mjs.map +1 -0
  106. package/esm/production/store/models/index.mjs +3 -1
  107. package/esm/server/ai-report-routes.mjs +72 -0
  108. package/esm/server/ai-report-routes.mjs.map +1 -0
  109. package/esm/server/ai-routes.mjs +22 -1
  110. package/esm/server/ai-routes.mjs.map +1 -1
  111. package/esm/server/index.mjs +2 -0
  112. package/esm/server/index.mjs.map +1 -1
  113. package/esm/sources/agent-trace-source.d.mts.map +1 -1
  114. package/esm/sources/agent-trace-source.mjs.map +1 -1
  115. package/esm/sources/ai-source.d.mts +2 -0
  116. package/esm/sources/ai-source.d.mts.map +1 -1
  117. package/esm/sources/ai-source.mjs +58 -17
  118. package/esm/sources/ai-source.mjs.map +1 -1
  119. package/esm/types.d.mts +13 -3
  120. package/esm/types.d.mts.map +1 -1
  121. package/llms-full.txt +56 -17
  122. package/package.json +8 -8
  123. package/skills/SKILL.md +56 -17
  124. package/ui/dashboard/assets/app.css +1 -1
  125. package/ui/dashboard/assets/app.js +12 -5
  126. package/ui/dashboard/build-info.json +7 -7
  127. package/cjs/ai-source-BdvMfyKw.cjs +0 -448
  128. package/cjs/ai-source-BdvMfyKw.cjs.map +0 -1
  129. package/cjs/app-versions-DfpPZOI2.cjs.map +0 -1
  130. package/cjs/boot-nczSvJ_F.cjs.map +0 -1
  131. package/cjs/errors-BadbSDX8.cjs.map +0 -1
  132. package/cjs/http-Biauhqi0.cjs.map +0 -1
  133. package/cjs/migrations-BP4cYTGo.cjs.map +0 -1
  134. package/cjs/options-B9FHbRAJ.cjs +0 -205
  135. package/cjs/options-B9FHbRAJ.cjs.map +0 -1
  136. package/cjs/panels-D1ITm-jc.cjs +0 -384
  137. package/cjs/panels-D1ITm-jc.cjs.map +0 -1
  138. package/cjs/src-QcNghoYN.cjs.map +0 -1
  139. package/cjs/stream-route-BqyAlfxQ.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract-8kaX_cUV.cjs","names":["path","fileURLToPath","existsSync","statSync","pathToFileURL","readFileSync","createRequire","DEVTOOLS_BUILT_IN_PANELS","installedVersion","DEVTOOLS_AI_ERROR_CATEGORIES","DEVTOOLS_AI_LATENCY_BUCKETS_MS","createHash"],"sources":["../../../../../../../packages/devtools/src/panels.ts","../../../../../../../packages/devtools/src/safe-value.ts","../../../../../../../packages/devtools/src/sources/ai-source.ts","../../../../../../../packages/devtools/src/ai/rollup/categories.ts","../../../../../../../packages/devtools/src/ai/rollup/histogram.ts","../../../../../../../packages/devtools/src/ai/rollup/extract.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { DEVTOOLS_BUILT_IN_PANELS } from \"./production/contracts\";\nimport type { DevtoolsMode, DevtoolsPanelInfo } from \"./production/contracts\";\nimport type {\n DevtoolsPanel,\n DevtoolsPanelEntry,\n DevtoolsPanelErrorSummary,\n DevtoolsPanelExport,\n DevtoolsPanelMethod,\n DevtoolsPanelRoute,\n} from \"./types\";\n\n/**\n * A validated panel: file paths are absolute strings and every list is\n * present, so the server never re-checks them per request.\n */\nexport type MountedDevtoolsPanel = {\n id: string;\n title: string;\n view: string;\n routes: readonly (DevtoolsPanelRoute & { method: DevtoolsPanelMethod })[];\n assets: Readonly<Record<string, string>>;\n /** The folder of images the panel serves; `null` when it declared none. */\n files: MountedPanelFiles | null;\n /** What a read-only share link of the panel opens; `null` when the panel cannot be shared. */\n share: MountedPanelShare | null;\n /** Whether the panel declared itself safe for the production monitor. */\n production: boolean;\n};\n\n/** A panel's folder of images, validated: an absolute directory and lower-case extensions. */\nexport type MountedPanelFiles = {\n dir: string;\n extensions: readonly string[];\n};\n\n/** A panel's shared view, validated. */\nexport type MountedPanelShare = {\n /** Absolute path of the shared view module. */\n view: string;\n /** Paths of the GET routes the shared page may call. */\n routes: readonly string[];\n /** Served names from `assets` the shared page may load. */\n assets: readonly string[];\n /** Whether the shared page may load images from `files`. */\n files: boolean;\n};\n\n/** The extensions a panel serves from `files` when it lists none. */\nexport const DEFAULT_PANEL_FILE_EXTENSIONS: readonly string[] = [\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".webp\",\n \".gif\",\n];\n\n/** Extensions a panel may never serve from `files`: a browser runs or renders them as a page. */\nconst BLOCKED_FILE_EXTENSIONS = new Set([\".svg\", \".html\", \".htm\", \".js\", \".mjs\"]);\n\n/**\n * Ids the dashboard already uses for its own tabs, API segments and URLs. A\n * panel's routes live under `<path>/api/<id>`, so these would collide.\n */\nconst RESERVED_PANEL_IDS = new Set([\n \"account\",\n \"admin\",\n \"agents\",\n \"ai\",\n \"api\",\n \"assets\",\n \"auth\",\n \"background\",\n \"docs\",\n \"errors\",\n \"health\",\n \"instances\",\n \"jobs\",\n \"logs\",\n \"mail\",\n \"mails\",\n \"panels\",\n \"queries\",\n \"requests\",\n \"resources\",\n \"routes\",\n \"share\",\n \"stream\",\n]);\n\nconst PANEL_ID = /^[a-z][a-z0-9-]*$/;\nconst ASSET_NAME = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;\nconst METHODS = new Set<DevtoolsPanelMethod>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/** Content types for the files a panel may serve; anything else is sent as bytes. */\nconst CONTENT_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".gif\": \"image/gif\",\n \".woff2\": \"font/woff2\",\n};\n\n/** The content type a panel file is served with, from its served name. */\nexport function panelContentType(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** An absolute file path from a path or `file:` URL, or `undefined` for anything else. */\nfunction toFilePath(value: unknown): string | undefined {\n if (value instanceof URL) return value.protocol === \"file:\" ? fileURLToPath(value) : undefined;\n if (typeof value !== \"string\" || value === \"\") return undefined;\n if (value.startsWith(\"file:\")) return fileURLToPath(value);\n\n return path.isAbsolute(value) ? value : undefined;\n}\n\nfunction isFile(file: string): boolean {\n return existsSync(file) && statSync(file).isFile();\n}\n\n/**\n * Validates `value` as a panel and returns it ready to mount. Throws an\n * error that names the panel and what to change; `taken` maps the ids\n * already registered to their titles and receives this panel's id.\n */\nexport function checkDevtoolsPanel(\n value: unknown,\n taken: Map<string, string>,\n): MountedDevtoolsPanel {\n const panel = (value ?? {}) as Partial<DevtoolsPanel>;\n const id = panel.id;\n\n if (typeof id !== \"string\" || !PANEL_ID.test(id)) {\n throw new Error(\n `A devtools panel needs an \"id\" of lower-case letters, digits and dashes that starts with a letter; got ${JSON.stringify(id)}.`,\n );\n }\n\n if (RESERVED_PANEL_IDS.has(id)) {\n throw new Error(\n `Devtools panel id \"${id}\" is used by the dashboard itself; give the panel another id.`,\n );\n }\n\n const existing = taken.get(id);\n\n if (existing !== undefined) {\n throw new Error(\n `Devtools panel id \"${id}\" is already registered by the \"${existing}\" panel; each panel needs its own id.`,\n );\n }\n\n if (typeof panel.title !== \"string\" || panel.title.trim() === \"\") {\n throw new Error(`Devtools panel \"${id}\" needs a \"title\" for its tab.`);\n }\n\n const view = toFilePath(panel.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs a \"view\": an absolute path or file: URL of its browser module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n // Two routes on one method and path would make the server refuse to start.\n const seen = new Set<string>();\n const routes = (panel.routes ?? []).map((route) => {\n const method = route.method ?? \"GET\";\n\n if (!METHODS.has(method)) {\n throw new Error(\n `Devtools panel \"${id}\" has a route with method \"${String(method)}\"; use GET, POST, PUT, PATCH or DELETE.`,\n );\n }\n\n if (typeof route.path !== \"string\" || (route.path !== \"\" && !route.path.startsWith(\"/\"))) {\n throw new Error(\n `Devtools panel \"${id}\" has a route path ${JSON.stringify(route.path)}; use \"\" or a path starting with \"/\".`,\n );\n }\n\n if (typeof route.handler !== \"function\") {\n throw new Error(`Devtools panel \"${id}\" route ${method} \"${route.path}\" has no handler.`);\n }\n\n if (seen.has(`${method} ${route.path}`)) {\n throw new Error(\n `Devtools panel \"${id}\" lists route ${method} \"${route.path}\" twice; keep one.`,\n );\n }\n\n seen.add(`${method} ${route.path}`);\n\n return { ...route, method };\n });\n\n const assets: Record<string, string> = {};\n\n for (const [name, source] of Object.entries(panel.assets ?? {})) {\n if (!ASSET_NAME.test(name) || name === \"view.js\") {\n throw new Error(\n `Devtools panel \"${id}\" has an asset named ${JSON.stringify(name)}; use a plain file name other than \"view.js\".`,\n );\n }\n\n const file = toFilePath(source);\n\n if (file === undefined || !isFile(file)) {\n throw new Error(\n `The asset \"${name}\" of devtools panel \"${id}\" was not found at ${String(source)}; give an absolute path or file: URL.`,\n );\n }\n\n assets[name] = file;\n }\n\n const files = checkPanelFiles(id, panel.files);\n const share = checkPanelShare(id, panel.share, routes, assets, files !== null);\n\n taken.set(id, panel.title);\n\n return {\n id,\n title: panel.title,\n view,\n routes,\n assets,\n files,\n share,\n production: panel.production === true,\n };\n}\n\nconst FILE_EXTENSION = /^\\.[a-z0-9]{1,16}$/;\n\n/** Validates `files`; `null` when the panel declares none. */\nfunction checkPanelFiles(\n id: string,\n value: DevtoolsPanel[\"files\"] | null,\n): MountedPanelFiles | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has files that is not an object; use { dir: \"/absolute/folder\" }.`,\n );\n }\n\n const dir = toFilePath(value.dir);\n\n if (dir === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs files.dir to be an absolute path or a file: URL; got ${String(value.dir)}.`,\n );\n }\n\n const given = value.extensions;\n\n if (given !== undefined && (!Array.isArray(given) || given.length === 0)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions that is not a list; use [\".png\", \".jpg\"] or leave it out.`,\n );\n }\n\n for (const extension of given ?? []) {\n if (typeof extension !== \"string\" || !FILE_EXTENSION.test(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions entry ${JSON.stringify(extension)}; use lower-case extensions that start with a dot, such as \".png\".`,\n );\n }\n\n if (BLOCKED_FILE_EXTENSIONS.has(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" lists files.extensions entry \"${extension}\", which can run as a page or script in the browser; remove it (images such as .png, .jpg, .webp and .gif are fine).`,\n );\n }\n }\n\n return { dir, extensions: [...(given ?? DEFAULT_PANEL_FILE_EXTENSIONS)] };\n}\n\n/** Validates `share` against the panel's own routes, assets and files. */\nfunction checkPanelShare(\n id: string,\n value: DevtoolsPanel[\"share\"] | null,\n routes: readonly { method: DevtoolsPanelMethod; path: string }[],\n assets: Readonly<Record<string, string>>,\n hasFiles: boolean,\n): MountedPanelShare | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has share that is not an object; use { view, routes }.`,\n );\n }\n\n const view = toFilePath(value.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.view: an absolute path or file: URL of the shared view module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The share.view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n if (!Array.isArray(value.routes)) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.routes: a list of the paths of its GET routes the shared page may call.`,\n );\n }\n\n const getPaths = routes.filter((route) => route.method === \"GET\").map((route) => route.path);\n\n for (const route of value.routes) {\n if (typeof route !== \"string\" || !getPaths.includes(route)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.routes entry ${JSON.stringify(route)}, which is not the path of one of its GET routes${getPaths.length > 0 ? `; use one of ${getPaths.map((path) => JSON.stringify(path)).join(\", \")}` : \" (the panel has no GET routes)\"}.`,\n );\n }\n }\n\n for (const name of value.assets ?? []) {\n if (typeof name !== \"string\" || !Object.hasOwn(assets, name)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.assets entry ${JSON.stringify(name)}, which is not a name in its assets; use one of ${Object.keys(assets).join(\", \") || \"(the panel has no assets)\"}.`,\n );\n }\n }\n\n const files = value.files === true;\n\n if (value.files !== undefined && typeof value.files !== \"boolean\") {\n throw new Error(`Devtools panel \"${id}\" needs share.files to be true or false.`);\n }\n\n if (files && !hasFiles) {\n throw new Error(\n `Devtools panel \"${id}\" sets share.files, but the panel has no files folder; add files: { dir } or remove share.files.`,\n );\n }\n\n return { view, routes: [...value.routes], assets: [...(value.assets ?? [])], files };\n}\n\n/** Validates a list of panels; the first invalid or duplicate one throws. */\nexport function checkDevtoolsPanels(panels: readonly unknown[]): MountedDevtoolsPanel[] {\n const taken = new Map<string, string>();\n\n return panels.map((panel) => checkDevtoolsPanel(panel, taken));\n}\n\n/** Hooks `loadDevtoolsPanels` uses; replaced in specs. */\nexport type LoadDevtoolsPanelsOptions = {\n /** The app's root directory: bare specifiers resolve from here, `./` paths are relative to it. */\n root: string;\n /** Receives one line per entry that could not be loaded or was rejected. */\n warn: (message: string) => void;\n /** Ids already taken (the built-in panels), mapped to their titles. */\n taken?: ReadonlyMap<string, string>;\n /** Imports a module URL or specifier; defaults to a dynamic `import()`. */\n importModule?: (specifier: string) => Promise<unknown>;\n /** Where the dashboard runs; panel factories receive it as `context.mode`. @default \"development\" */\n mode?: DevtoolsMode;\n /** The captured error groups of the last hour; panel factories receive it as `context.errors`. */\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\n/** What is wrong with a `[specifier, options]` entry, or `undefined` when it is valid. */\nfunction tupleProblem(entry: readonly unknown[]): string | undefined {\n if (entry.length !== 2) {\n return `it has ${entry.length} item(s); use exactly [specifier, options]`;\n }\n\n if (typeof entry[0] !== \"string\" || entry[0] === \"\") {\n return `its first item is ${JSON.stringify(entry[0])}; use the module specifier as a string`;\n }\n\n if (!isPlainObject(entry[1])) {\n return `its second item is not a plain object; pass the options as { name: value }`;\n }\n\n return undefined;\n}\n\n/** The URL or specifier to import for a `panels` entry. */\nfunction resolvePanelSpecifier(entry: string, root: string): string {\n if (entry.startsWith(\"./\") || entry.startsWith(\"../\") || path.isAbsolute(entry)) {\n return pathToFileURL(path.resolve(root, entry)).href;\n }\n\n return resolveFromNodeModules(entry, root) ?? resolveWithRequire(entry, root) ?? entry;\n}\n\n/** Picks the file an `exports` target names: `import`, then `default`, then `node`. */\nfunction exportTarget(target: unknown): string | undefined {\n if (typeof target === \"string\") return target;\n\n if (Array.isArray(target)) {\n for (const item of target) {\n const found = exportTarget(item);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n }\n\n if (target !== null && typeof target === \"object\") {\n const conditions = target as Record<string, unknown>;\n\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const found = exportTarget(conditions[condition]);\n\n if (found !== undefined) return found;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a package specifier by looking it up in the `node_modules` folders\n * above the app root and reading its `exports` map. `createRequire().resolve`\n * cannot do this for a package that only has an `import` condition.\n */\nfunction resolveFromNodeModules(entry: string, root: string): string | undefined {\n const parts = entry.split(\"/\");\n const nameLength = entry.startsWith(\"@\") ? 2 : 1;\n const name = parts.slice(0, nameLength).join(\"/\");\n const subpath = parts.length > nameLength ? `./${parts.slice(nameLength).join(\"/\")}` : \".\";\n\n if (!name) return undefined;\n\n let directory = path.resolve(root);\n\n for (;;) {\n const packageDirectory = path.join(directory, \"node_modules\", name);\n const manifestFile = path.join(packageDirectory, \"package.json\");\n\n if (existsSync(manifestFile)) {\n try {\n const manifest = JSON.parse(readFileSync(manifestFile, \"utf8\")) as {\n exports?: unknown;\n main?: string;\n };\n const exported = manifest.exports;\n const map =\n exported !== null && typeof exported === \"object\" && !Array.isArray(exported)\n ? (exported as Record<string, unknown>)\n : undefined;\n const hasSubpaths =\n map !== undefined && Object.keys(map).some((key) => key.startsWith(\".\"));\n const target =\n exported === undefined\n ? subpath === \".\"\n ? (manifest.main ?? \"index.js\")\n : subpath\n : hasSubpaths\n ? exportTarget(map?.[subpath])\n : subpath === \".\"\n ? exportTarget(exported)\n : undefined;\n\n if (target === undefined) return undefined;\n\n const file = path.resolve(packageDirectory, target);\n\n return isFile(file) ? pathToFileURL(file).href : undefined;\n } catch {\n return undefined;\n }\n }\n\n const parent = path.dirname(directory);\n\n if (parent === directory) return undefined;\n\n directory = parent;\n }\n}\n\n/** The `require` resolution, for packages the `node_modules` lookup does not understand. */\nfunction resolveWithRequire(entry: string, root: string): string | undefined {\n try {\n return pathToFileURL(createRequire(path.join(root, \"package.json\")).resolve(entry)).href;\n } catch {\n return undefined;\n }\n}\n\n/** The panels a module's default export describes. */\nasync function panelsOf(\n exported: DevtoolsPanelExport,\n root: string,\n mode: DevtoolsMode,\n panelOptions: Readonly<Record<string, unknown>> = {},\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>,\n): Promise<readonly unknown[]> {\n const value =\n typeof exported === \"function\"\n ? await exported({ ...panelOptions, root, mode, ...(errors ? { errors } : {}) })\n : exported;\n\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Loads the devtools `panels` option: imports each module entry, reads its\n * default export, and validates every panel. An entry that fails to load and\n * a panel that is invalid or reuses an id are reported through `warn` and\n * skipped, so one broken panel never stops the dashboard.\n */\nexport async function loadDevtoolsPanels(\n entries: readonly DevtoolsPanelEntry[],\n options: LoadDevtoolsPanelsOptions,\n): Promise<MountedDevtoolsPanel[]> {\n // `src/config/devtools.ts` is a plain object with no types: a single string would be read letter by letter.\n if (!Array.isArray(entries as unknown)) {\n options.warn(\n `The devtools \"panels\" option must be a list, such as panels: [\"@warlock.js/grimoire/devtools\"]; got ${JSON.stringify(entries)}. No panel was added.`,\n );\n\n return [];\n }\n\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const mode = options.mode ?? \"development\";\n const taken = new Map<string, string>(options.taken ?? []);\n const panels: MountedDevtoolsPanel[] = [];\n\n for (const entry of entries) {\n let candidates: readonly unknown[];\n\n try {\n if (Array.isArray(entry as unknown)) {\n const problem = tupleProblem(entry as readonly unknown[]);\n\n if (problem !== undefined) {\n options.warn(\n `Devtools panels entry ${JSON.stringify(entry)} is invalid: ${problem}. Example: [\"@warlock.js/grimoire/devtools\", { ttlMs: 60000 }]. The entry was not added.`,\n );\n continue;\n }\n }\n\n if (typeof entry === \"string\" || Array.isArray(entry as unknown)) {\n const [specifier, panelOptions] =\n typeof entry === \"string\"\n ? [entry, undefined]\n : (entry as readonly [string, Record<string, unknown>]);\n const module = (await importModule(resolvePanelSpecifier(specifier, options.root))) as {\n default?: DevtoolsPanelExport;\n };\n\n if (module.default === undefined) {\n throw new Error(\"the module has no default export\");\n }\n\n candidates = await panelsOf(\n module.default,\n options.root,\n mode,\n panelOptions,\n options.errors,\n );\n } else {\n candidates = [entry];\n }\n } catch (error) {\n options.warn(\n `Devtools panel module \"${String(Array.isArray(entry as unknown) ? (entry as readonly unknown[])[0] : entry)}\" could not be loaded: ${describe(error)}. Check that it is installed and listed correctly in the devtools \"panels\" option.`,\n );\n continue;\n }\n\n for (const candidate of candidates) {\n try {\n panels.push(checkDevtoolsPanel(candidate, taken));\n } catch (error) {\n options.warn(`${describe(error)} The panel was not added.`);\n }\n }\n }\n\n return panels;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** What `productionPanels` decides. */\nexport type DevtoolsProductionPanels = {\n /** Built-in tab ids shown, in display order. */\n builtIn: string[];\n /** Package panels shown. */\n panels: MountedDevtoolsPanel[];\n};\n\n/**\n * Which tabs the production monitor shows. A built-in tab follows\n * `DEVTOOLS_BUILT_IN_PANELS` unless `overrides[id]` says otherwise. A package\n * panel (the Processes panel included) shows when it declares\n * `production: true` or `overrides[id]` is `true`; `overrides[id]: false` turns\n * any tab off.\n */\nexport function productionPanels(\n packagePanels: readonly MountedDevtoolsPanel[],\n overrides: Readonly<Record<string, boolean>> = {},\n): DevtoolsProductionPanels {\n const builtIn = DEVTOOLS_BUILT_IN_PANELS.filter((tab) => overrides[tab.id] ?? tab.production).map(\n (tab) => tab.id,\n );\n const panels = packagePanels.filter((panel) => overrides[panel.id] ?? panel.production);\n\n return { builtIn, panels };\n}\n\n/**\n * The tab list `GET api/panels` answers with: the built-in tabs in\n * `builtIn` (default: every one), in display order, then the package panels\n * in registration order.\n */\nexport function listPanelInfos(\n panels: readonly (Pick<MountedDevtoolsPanel, \"id\" | \"title\"> &\n Partial<Pick<MountedDevtoolsPanel, \"share\">>)[],\n builtIn?: readonly string[],\n): DevtoolsPanelInfo[] {\n const tabs: DevtoolsPanelInfo[] = DEVTOOLS_BUILT_IN_PANELS.filter(\n (tab) => builtIn === undefined || builtIn.includes(tab.id),\n ).map((tab) => ({\n id: tab.id,\n title: tab.title,\n type: \"built-in\" as const,\n shareable: false,\n }));\n\n for (const panel of panels) {\n tabs.push({\n id: panel.id,\n title: panel.title,\n type: \"package\" as const,\n shareable: panel.share !== undefined && panel.share !== null,\n });\n }\n\n return tabs;\n}\n","const MAX_DEPTH = 6;\n\n/**\n * A JSON-safe snapshot of a value devtools keeps for later display.\n *\n * Log contexts and phase attributes are app data: they can hold live objects\n * (a request, its socket) whose graphs are circular and which must not be kept\n * alive by the collector anyway. Plain objects and arrays are copied; anything\n * with a `toJSON()` is serialized through it; other class instances collapse\n * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to\n * `[Object]` / `[Array]`.\n */\nexport function toSafeValue(value: unknown): unknown {\n return snapshot(value, 0, new WeakSet());\n}\n\nfunction snapshot(value: unknown, depth: number, seen: WeakSet<object>): unknown {\n if (value === null || value === undefined) return value;\n\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"symbol\":\n return value.toString();\n case \"function\":\n return undefined;\n }\n\n const object = value as object;\n\n if (seen.has(object)) return \"[Circular]\";\n if (value instanceof Date)\n return Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n if (value instanceof Error) return { name: value.name, message: value.message };\n\n if (depth >= MAX_DEPTH) return Array.isArray(value) ? \"[Array]\" : \"[Object]\";\n\n seen.add(object);\n\n try {\n if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));\n\n const prototype = Object.getPrototypeOf(object);\n\n if (prototype !== Object.prototype && prototype !== null) {\n const toJSON = (object as { toJSON?: unknown }).toJSON;\n\n if (typeof toJSON === \"function\") {\n try {\n return snapshot(toJSON.call(object), depth + 1, seen);\n } catch {\n return `[${constructorName(object)}]`;\n }\n }\n\n return `[${constructorName(object)}]`;\n }\n\n const copy: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(object)) {\n const safe = snapshot(entry, depth + 1, seen);\n if (safe !== undefined) copy[key] = safe;\n }\n\n return copy;\n } finally {\n seen.delete(object);\n }\n}\n\nfunction constructorName(object: object): string {\n return (object as { constructor?: { name?: string } }).constructor?.name || \"Object\";\n}\n","import type { Trace, TraceSpan, TraceStoreContract } from \"@warlock.js/ai-panoptic\";\nimport { installedVersion } from \"../app-versions\";\nimport type { DevtoolsAiRunHelpers } from \"../ai/reports/runs\";\nimport type { DevtoolsAiTotalCost } from \"../ai/types\";\nimport type { DevtoolsAiUnavailableView } from \"../production/contracts\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsDisposer } from \"../types\";\n\nexport type DevtoolsAiUnavailableReason =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** Why the AI tab is empty, as sent to the dashboard: a title, one line and an optional command. */\nexport type DevtoolsAiUnavailable = {\n available: false;\n reason: DevtoolsAiUnavailableReason;\n title: string;\n message: string;\n command?: string;\n detail?: string;\n};\n\n/** Replaces absolute file paths in an error line with their package-relative part, or `<path>`. */\nexport function redactPaths(text: string): string {\n return text.replace(/(?:file:\\/\\/)?(?:[A-Za-z]:)?[\\\\/][^\\s'\"`()]*/g, (match) => {\n const normalized = match.replace(/^file:\\/\\//, \"\").replaceAll(\"\\\\\", \"/\");\n const index = normalized.lastIndexOf(\"node_modules/\");\n\n return index === -1 ? \"<path>\" : normalized.slice(index + \"node_modules/\".length);\n });\n}\n\nconst OBSERVATION_COMMAND = \"ai.config({ panoptic: { observeAll: true } })\";\n\n/** The answer for each reason; `detail` carries the load error and versions for `panoptic-failed`. */\nexport function describeAiUnavailable(\n reason: DevtoolsAiUnavailableReason,\n detail?: string,\n): DevtoolsAiUnavailable {\n switch (reason) {\n case \"ai-missing\":\n return {\n available: false,\n reason,\n title: \"AI isn't installed\",\n message: \"Add @warlock.js/ai to see AI runs here.\",\n command: \"warlock add ai\",\n };\n case \"panoptic-missing\":\n return {\n available: false,\n reason,\n title: \"Panoptic isn't installed\",\n message: \"Your app uses @warlock.js/ai. Add Panoptic to see its runs.\",\n command: \"warlock add ai-panoptic\",\n };\n case \"panoptic-failed\":\n return {\n available: false,\n reason,\n title: \"Panoptic could not be loaded\",\n message:\n \"Panoptic is installed but failed to load. Check that both packages share a version.\",\n detail,\n };\n case \"not-collected\":\n return {\n available: false,\n reason,\n title: \"AI runs are not collected here\",\n message:\n \"Production keeps hourly AI totals, not run details. Open Reports, Models or Errors here, or the Runs tab in development (warlock dev).\",\n };\n case \"table-missing\":\n return {\n available: false,\n reason,\n title: \"AI reports need their table\",\n message: \"Run the devtools migrations to create devtools_ai_rollups, then restart the app.\",\n command: \"warlock migrate\",\n };\n case \"reports-off\":\n return {\n available: false,\n reason,\n title: \"AI reports are off\",\n message:\n \"Set devtools.ai.reports to true in src/config/devtools.ts to keep hourly AI totals.\",\n };\n case \"observation-off\":\n return {\n available: false,\n reason,\n title: \"AI observation is off\",\n message: \"Turn it on in src/config/ai.ts, then restart warlock dev.\",\n command: OBSERVATION_COMMAND,\n };\n }\n}\n\n/** The unavailable answer as the AI routes send it: `command` and `detail` are `null` when absent. */\nexport function toAiUnavailableView(unavailable: DevtoolsAiUnavailable): DevtoolsAiUnavailableView {\n return {\n available: false,\n reason: unavailable.reason,\n title: unavailable.title,\n message: unavailable.message,\n command: unavailable.command ?? null,\n detail: unavailable.detail ?? null,\n };\n}\n\n/** Test seam: how packages are loaded and their versions read. */\nexport type AiSourceDeps = {\n load?: (name: string) => Promise<unknown>;\n version?: (name: string) => string | null;\n};\n\nexport type DevtoolsAiEvent = { traceId: string; requestId?: string };\n\n/** Only the connector's development branch constructs this source. */\nexport type DevtoolsAiSource =\n | (DevtoolsAiUnavailable & { dispose: DevtoolsDisposer })\n | {\n available: true;\n /** True when `@warlock.js/ai` has no `observeAll` and no registered observer (read per request). */\n observationOff?: () => boolean;\n /** Totals a trace's priced usage (Panoptic's `totalCostUsd`). */\n totalCost: DevtoolsAiTotalCost;\n /** Panoptic's trace filter, grouping and percentile helpers for the Runs list. */\n helpers: DevtoolsAiRunHelpers;\n store: TraceStoreContract;\n summarize: (trace: Trace) => DevtoolsAiRun;\n subscribe: (listener: (event: DevtoolsAiEvent) => void) => DevtoolsDisposer;\n dispose: DevtoolsDisposer;\n };\n\nexport type DevtoolsAiRun = {\n traceId: string;\n requestId?: string;\n sessionId?: string;\n name: string;\n status: TraceSpan[\"status\"];\n startedAt: string;\n duration: number;\n usage: Trace[\"usage\"];\n cost?: number;\n models: string[];\n toolCalls: number;\n retries: number;\n cacheHits?: number;\n incomplete: boolean;\n truncatedTrips: number;\n compactions: number;\n skippedCompactions: number;\n providerCompactions: number;\n};\n\n/** Summaries use root usage once: nested spans already roll up into it. */\nexport function summarizeAiTrace(trace: Trace, cost?: number): DevtoolsAiRun {\n const models = new Set<string>();\n let toolCalls = 0;\n let retries = 0;\n let cacheHits: number | undefined;\n let incomplete = false;\n let truncatedTrips = 0;\n let compactions = 0;\n let skippedCompactions = 0;\n let providerCompactions = 0;\n const visit = (span: TraceSpan): void => {\n const attributes = span.attributes ?? {};\n const model = attributes[\"agent.model.name\"];\n const provider = attributes[\"agent.model.provider\"];\n if (typeof model === \"string\")\n models.add(typeof provider === \"string\" ? `${provider}/${model}` : model);\n if (span.type === \"tool\") toolCalls += 1;\n if (typeof attributes.retries === \"number\") retries += attributes.retries;\n if (typeof attributes[\"agent.cacheHits\"] === \"number\")\n cacheHits = (cacheHits ?? 0) + attributes[\"agent.cacheHits\"];\n if (typeof attributes[\"agent.truncatedTrips\"] === \"number\")\n truncatedTrips += attributes[\"agent.truncatedTrips\"];\n if (typeof attributes[\"agent.providerCompactions\"] === \"number\")\n providerCompactions += attributes[\"agent.providerCompactions\"];\n if (Array.isArray(attributes[\"agent.compactions\"])) {\n const records: unknown[] = attributes[\"agent.compactions\"];\n for (const record of records) {\n if (typeof record !== \"object\" || record === null || !(\"type\" in record)) continue;\n if (record.type === \"applied\") compactions += 1;\n if (record.type === \"skipped\") skippedCompactions += 1;\n }\n }\n incomplete ||=\n span.status === \"incomplete\" ||\n span.error?.type === \"AgentIncompleteError\" ||\n span.error?.type === \"AGENT_INCOMPLETE\";\n span.children.forEach(visit);\n };\n visit(trace.root);\n return {\n traceId: trace.traceId,\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n name: trace.root.name,\n status: trace.root.status,\n startedAt: trace.startedAt,\n duration: trace.duration,\n usage: trace.usage,\n cost,\n models: [...models],\n toolCalls,\n retries,\n cacheHits,\n incomplete,\n truncatedTrips,\n compactions,\n skippedCompactions,\n providerCompactions,\n };\n}\n\n/** Content-free snapshot; never retain prompts, completions or tool arguments/results. */\nfunction snapshotSpan(span: TraceSpan): TraceSpan {\n return {\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n traceId: span.traceId,\n sessionId: span.sessionId,\n name: span.name,\n version: span.version,\n type: span.type,\n status: span.status,\n startedAt: span.startedAt,\n endedAt: span.endedAt,\n duration: span.duration,\n usage: structuredClone(span.usage),\n error: span.error ? { type: span.error.type, message: span.error.message } : undefined,\n attributes: toSafeValue(span.attributes) as Record<string, unknown> | undefined,\n children: span.children.map(snapshotSpan),\n };\n}\n\ntype PanopticModule = typeof import(\"@warlock.js/ai-panoptic\");\ntype AiCoreModule = { isObserveAll?: () => boolean; getObservers?: () => readonly unknown[] };\n\n/**\n * Loads Panoptic (required) and `@warlock.js/ai` (for the observation check)\n * lazily, or says why not. Shared by the development source and the AI\n * reports wiring, so both answer the same unavailable reasons.\n */\nexport async function loadAiPackages(\n deps: AiSourceDeps = {},\n): Promise<\n | { panoptic: PanopticModule; observationOff: () => boolean }\n | { unavailable: DevtoolsAiUnavailable }\n> {\n const aiPackage: string = \"@warlock.js/ai\"; // not a dependency of devtools: never resolved at build time\n const load =\n deps.load ??\n ((name: string) =>\n name === \"@warlock.js/ai-panoptic\" ? import(\"@warlock.js/ai-panoptic\") : import(aiPackage));\n const version =\n deps.version ?? ((name: string) => installedVersion(name, process.cwd(), import.meta.resolve));\n let panoptic: PanopticModule;\n try {\n panoptic = (await load(\"@warlock.js/ai-panoptic\")) as PanopticModule;\n if (typeof panoptic.subscribeTraces !== \"function\")\n throw new Error(\"Trace subscription unavailable\");\n } catch (error) {\n const aiVersion = version(\"@warlock.js/ai\");\n const panopticVersion = version(\"@warlock.js/ai-panoptic\");\n if (aiVersion === null) return { unavailable: describeAiUnavailable(\"ai-missing\") };\n if (panopticVersion === null) return { unavailable: describeAiUnavailable(\"panoptic-missing\") };\n const text = redactPaths(\n (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0] ?? \"\",\n ).slice(0, 300);\n return {\n unavailable: describeAiUnavailable(\n \"panoptic-failed\",\n `${text} (@warlock.js/ai ${aiVersion}, @warlock.js/ai-panoptic ${panopticVersion})`,\n ),\n };\n }\n\n let core: AiCoreModule | undefined;\n try {\n core = (await load(\"@warlock.js/ai\")) as AiCoreModule;\n } catch {\n core = undefined;\n }\n const observationOff = (): boolean =>\n typeof core?.isObserveAll === \"function\" &&\n typeof core.getObservers === \"function\" &&\n !core.isObserveAll() &&\n core.getObservers().length === 0;\n\n return { panoptic, observationOff };\n}\n\n/**\n * Optional, lazy integration. Retains only traces collected after devtools boots,\n * using Panoptic's bounded query store; existing exporter/cache stores stay independent.\n */\nexport async function attachAiSource(\n capacity: number,\n deps: AiSourceDeps = {},\n): Promise<DevtoolsAiSource> {\n const loaded = await loadAiPackages(deps);\n if (\"unavailable\" in loaded) return { ...loaded.unavailable, dispose() {} };\n const { panoptic, observationOff } = loaded;\n\n const { currentRequestId } = await import(\"../current-request-id\");\n const store = panoptic.createInMemoryTraceStore({ capacity });\n const listeners = new Set<(event: DevtoolsAiEvent) => void>();\n const detach = panoptic.subscribeTraces((trace) => {\n // Read ALS before any asynchronous exporter work, including for runs that\n // finish after the HTTP response. Never use sessionId as a request id.\n const requestId = currentRequestId() ?? trace.requestId;\n store.add({\n ...trace,\n requestId,\n usage: structuredClone(trace.usage),\n root: snapshotSpan(trace.root),\n });\n for (const listener of listeners) {\n try {\n listener({ traceId: trace.traceId, requestId });\n } catch {\n /* isolate clients */\n }\n }\n });\n\n return {\n available: true,\n observationOff,\n totalCost: (usage) => panoptic.totalCostUsd(usage),\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 store,\n summarize: (trace) => summarizeAiTrace(trace, panoptic.totalCostUsd(trace.usage)),\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n detach();\n listeners.clear();\n store.clear();\n },\n };\n}\n","import {\n DEVTOOLS_AI_ERROR_CATEGORIES,\n type DevtoolsAiErrorCategory,\n} from \"../../production/contracts\";\nimport type { DevtoolsAiErrorCounts } from \"../types\";\n\n/** Labels the Errors page shows, by category. */\nexport const DEVTOOLS_AI_ERROR_LABELS: Readonly<Record<DevtoolsAiErrorCategory, string>> = {\n \"rate-limit\": \"Rate limit\",\n timeout: \"Timeout\",\n refusal: \"Refusal\",\n provider: \"Provider error\",\n budget: \"Budget\",\n tool: \"Tool failed\",\n schema: \"Invalid output\",\n incomplete: \"Incomplete\",\n other: \"Other\",\n};\n\n/** Error counts with every category at 0. */\nexport function emptyErrorCounts(): DevtoolsAiErrorCounts {\n const counts = {} as DevtoolsAiErrorCounts;\n\n for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) counts[category] = 0;\n\n return counts;\n}\n\nconst CODE_CATEGORIES: Readonly<Record<string, DevtoolsAiErrorCategory>> = {\n PROVIDER_RATE_LIMIT: \"rate-limit\",\n PROVIDER_QUOTA_EXCEEDED: \"rate-limit\",\n PROVIDER_OVERLOADED: \"rate-limit\",\n PROVIDER_TIMEOUT: \"timeout\",\n CONTENT_FILTER: \"refusal\",\n GUARDRAIL_VIOLATION: \"refusal\",\n PROVIDER_ERROR: \"provider\",\n PROVIDER_INVALID_REQUEST: \"provider\",\n PROVIDER_AUTH: \"provider\",\n CONTEXT_LENGTH_EXCEEDED: \"provider\",\n PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH: \"provider\",\n BUDGET_EXCEEDED: \"budget\",\n TOOL_EXEC_FAILED: \"tool\",\n SCHEMA_VALIDATION_FAILED: \"schema\",\n AGENT_INCOMPLETE: \"incomplete\",\n AGENT_MAX_TRIPS: \"incomplete\",\n AgentIncompleteError: \"incomplete\",\n};\n\n/**\n * The category of a failed or stopped agent span, from its status and error\n * type (an `AIErrorCode` such as `PROVIDER_RATE_LIMIT`, or an error name):\n *\n * - `rate-limit`: PROVIDER_RATE_LIMIT, PROVIDER_QUOTA_EXCEEDED, PROVIDER_OVERLOADED\n * - `timeout`: PROVIDER_TIMEOUT, or a name/type containing \"Timeout\"\n * - `refusal`: CONTENT_FILTER, GUARDRAIL_VIOLATION\n * - `provider`: PROVIDER_ERROR, PROVIDER_INVALID_REQUEST, PROVIDER_AUTH,\n * CONTEXT_LENGTH_EXCEEDED, PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH\n * - `budget`: BUDGET_EXCEEDED\n * - `tool`: TOOL_EXEC_FAILED\n * - `schema`: SCHEMA_VALIDATION_FAILED\n * - `incomplete`: status `incomplete` or `max-iterations`, AGENT_INCOMPLETE,\n * AGENT_MAX_TRIPS, AgentIncompleteError\n * - `other`: anything else\n */\nexport function classifyAiError(\n status: string,\n errorType: string | undefined,\n): DevtoolsAiErrorCategory {\n if (status === \"incomplete\" || status === \"max-iterations\") return \"incomplete\";\n\n if (!errorType) return \"other\";\n\n const known = CODE_CATEGORIES[errorType];\n\n if (known) return known;\n\n return /timeout/i.test(errorType) ? \"timeout\" : \"other\";\n}\n","import { DEVTOOLS_AI_LATENCY_BUCKETS_MS } from \"../../production/contracts\";\n\n/**\n * Latency histograms over `DEVTOOLS_AI_LATENCY_BUCKETS_MS`, stored as plain\n * count arrays in the rollups (one more count than bounds).\n */\n\nconst BUCKETS = DEVTOOLS_AI_LATENCY_BUCKETS_MS;\n\n/** `DEVTOOLS_AI_LATENCY_BUCKETS_MS.length + 1` zeros. */\nexport function emptyAiLatency(): number[] {\n return new Array<number>(BUCKETS.length + 1).fill(0);\n}\n\n/** The bucket index of a duration; a negative or non-finite value counts as 0. */\nexport function aiLatencyBucket(durationMs: number): number {\n if (!Number.isFinite(durationMs) || durationMs < 0) return 0;\n\n const index = BUCKETS.findIndex((bound) => durationMs <= bound);\n\n return index === -1 ? BUCKETS.length : index;\n}\n\n/** Adds `source` into `target` in place (same length). */\nexport function addAiLatency(target: number[], source: readonly number[]): void {\n for (let index = 0; index < target.length; index++) {\n target[index] = (target[index] ?? 0) + (source[index] ?? 0);\n }\n}\n\n/**\n * The `q` quantile (0–1): the upper bound of the bucket that holds it, or the\n * last bound for the overflow bucket. `null` for an empty histogram.\n */\nexport function aiLatencyQuantile(counts: readonly number[], q: number): number | null {\n let total = 0;\n\n for (const count of counts) total += count;\n\n if (total <= 0) return null;\n\n const target = Math.max(1, Math.ceil(Math.min(1, Math.max(0, q)) * total));\n let seen = 0;\n\n for (let index = 0; index < counts.length; index++) {\n seen += counts[index] ?? 0;\n\n if (seen >= target) return BUCKETS[Math.min(index, BUCKETS.length - 1)] ?? null;\n }\n\n return BUCKETS[BUCKETS.length - 1] ?? null;\n}\n","import { createHash } from \"node:crypto\";\nimport type { Trace } from \"@warlock.js/ai-panoptic\";\nimport type { DevtoolsAiRollupDelta, DevtoolsAiTotalCost } from \"../types\";\nimport { classifyAiError, emptyErrorCounts } from \"./categories\";\nimport { addAiLatency, aiLatencyBucket, emptyAiLatency } from \"./histogram\";\n\ntype Span = Trace[\"root\"];\ntype RollupKey = { hour: number; agent: string; model: string; provider: string };\n\nconst HOUR_MS = 3_600_000;\nconst UNKNOWN = \"(unknown)\";\nconst MODEL_SPAN_TYPES: ReadonlySet<string> = new Set([\n \"agent\",\n \"image\",\n \"speech\",\n \"transcription\",\n]);\n\n/** Token counts with `input` normalised to the whole prompt. */\ntype Tokens = {\n input: number;\n output: number;\n cached: number;\n cacheWrite: number;\n reasoning: number;\n};\n\nfunction count(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction normalise(usage: Span[\"usage\"] | undefined): Tokens {\n const cached = count(usage?.cachedTokens);\n const cacheWrite = count(usage?.cacheWriteTokens);\n const input = count(usage?.input);\n\n return {\n input: usage?.inputIncludesCache === false ? input + cached + cacheWrite : input,\n output: count(usage?.output),\n cached,\n cacheWrite,\n reasoning: count(usage?.reasoningTokens),\n };\n}\n\nfunction subtract(own: Tokens, other: Tokens): void {\n own.input = Math.max(0, own.input - other.input);\n own.output = Math.max(0, own.output - other.output);\n own.cached = Math.max(0, own.cached - other.cached);\n own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);\n own.reasoning = Math.max(0, own.reasoning - other.reasoning);\n}\n\n/** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */\nexport function isAiModelSpan(span: Span): boolean {\n return (\n typeof span.attributes?.[\"agent.model.name\"] === \"string\" || MODEL_SPAN_TYPES.has(span.type)\n );\n}\n\n/** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */\nfunction nearestModelSpans(span: Span): Span[] {\n const found: Span[] = [];\n\n for (const child of span.children ?? []) {\n if (isAiModelSpan(child)) found.push(child);\n else found.push(...nearestModelSpans(child));\n }\n\n return found;\n}\n\nfunction cut(value: unknown, max: number): string {\n if (typeof value !== \"string\" || value === \"\") return UNKNOWN;\n\n return value.length > max ? value.slice(0, max) : value;\n}\n\nfunction spanCost(span: Span, totalCost: DevtoolsAiTotalCost): number {\n return count(totalCost(span.usage));\n}\n\n/** Whether a span's usage carries pricing at all (a free model is priced at 0; no pricing is `undefined`). */\nfunction hasPricing(span: Span, totalCost: DevtoolsAiTotalCost): boolean {\n return typeof totalCost(span.usage) === \"number\";\n}\n\nfunction buildDelta(\n key: RollupKey,\n status: string,\n errorType: string | undefined,\n tokens: Tokens,\n cost: number,\n /** The own usage is priced even when `cost` is 0 (a model priced as free). */\n pricedAtZero = false,\n): DevtoolsAiRollupDelta {\n const delta = emptyRollupDelta(key);\n\n delta.runs = 1;\n delta.inputTokens = tokens.input;\n delta.outputTokens = tokens.output;\n delta.cachedTokens = tokens.cached;\n delta.cacheWriteTokens = tokens.cacheWrite;\n delta.reasoningTokens = tokens.reasoning;\n\n if (status === \"completed\") delta.completed = 1;\n else if (status === \"failed\") delta.failed = 1;\n else if (status === \"incomplete\" || status === \"max-iterations\") delta.incomplete = 1;\n else if (status === \"cancelled\") delta.cancelled = 1;\n\n if (status === \"failed\" || status === \"incomplete\" || status === \"max-iterations\") {\n delta.errors[classifyAiError(status, errorType)] = 1;\n }\n\n if (cost > 0 || (pricedAtZero && tokens.input + tokens.output > 0)) {\n delta.costUsd = cost;\n delta.pricedRuns = 1;\n } else if (tokens.input + tokens.output > 0) {\n delta.unpricedRuns = 1;\n delta.unpricedTokens = tokens.input + tokens.output;\n }\n\n return delta;\n}\n\n/**\n * Turns one finished Panoptic trace into rollup deltas, one per\n * model-bearing span (a span with an `agent.model.name` attribute, or of type\n * `agent`, `image`, `speech` or `transcription`), keyed by the hour of the\n * span's `endedAt`.\n *\n * Each span counts its OWN usage and cost: its rolled-up `usage` minus the\n * usage of its nearest model-bearing descendants (an agent used as a tool is\n * counted once, as itself). Root usage left after subtracting every\n * model-bearing span (a custom flow with no agent span) becomes one more delta\n * for the root name with model `(unknown)`, counted as one run.\n *\n * Per span: status maps to completed / failed / incomplete (`incomplete`,\n * `max-iterations`) / cancelled; failed and incomplete runs add one error to\n * `classifyAiError(status, error.type)`; tokens are normalised so `input`\n * includes cache reads and writes; `costUsd` is `totalCost` of the own usage\n * when it is above 0 (or the span's model is priced as free), otherwise a run\n * with tokens counts in `unpricedRuns` and `unpricedTokens`; `agent.fallbackTrips > 0` adds a fallback run;\n * `agent.refusals > 0` or a CONTENT_FILTER error adds a refusal; the span's\n * `duration` goes into the latency histogram.\n *\n * Pure: no clock, no I/O. Names are cut to 200 (provider 100) characters.\n */\nexport function traceToRollupDeltas(\n trace: Trace,\n totalCost: DevtoolsAiTotalCost,\n): DevtoolsAiRollupDelta[] {\n const root = trace.root;\n\n if (!root) return [];\n\n // A span without a readable end falls back to the root's end, then the trace's; no end at all skips the trace.\n const rootEnd = Date.parse(root.endedAt);\n const fallbackEnd = Number.isNaN(rootEnd) ? Date.parse(trace.endedAt) : rootEnd;\n\n if (Number.isNaN(fallbackEnd)) return [];\n\n const hourOf = (span: Span): number => {\n const ended = Date.parse(span.endedAt);\n const at = Number.isNaN(ended) ? fallbackEnd : ended;\n\n return Math.floor(at / HOUR_MS) * HOUR_MS;\n };\n\n const deltas: DevtoolsAiRollupDelta[] = [];\n const topLevel: Span[] = isAiModelSpan(root) ? [root] : nearestModelSpans(root);\n\n const visit = (span: Span): void => {\n const tokens = normalise(span.usage);\n let cost = spanCost(span, totalCost);\n const inner = nearestModelSpans(span);\n\n for (const child of inner) {\n subtract(tokens, normalise(child.usage));\n cost -= spanCost(child, totalCost);\n }\n\n cost = Math.max(0, cost);\n\n // Priced at zero only when the span's own pricing is known: none of the nested model spans carry a cost.\n const pricedAtZero =\n hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));\n\n const attributes = span.attributes ?? {};\n const key: RollupKey = { hour: hourOf(span), ...aiRollupNamesOf(span) };\n const delta = buildDelta(key, span.status, span.error?.type, tokens, cost, pricedAtZero);\n\n if (count(attributes[\"agent.fallbackTrips\"]) > 0) delta.fallbackRuns = 1;\n\n if (count(attributes[\"agent.refusals\"]) > 0 || span.error?.type === \"CONTENT_FILTER\") {\n delta.refusals = 1;\n }\n\n const duration = count(span.duration);\n\n const bucket = aiLatencyBucket(duration);\n\n delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;\n delta.latencyCount = 1;\n delta.latencySumMs = Math.max(0, duration);\n\n deltas.push(delta);\n\n for (const child of inner) visit(child);\n };\n\n // Only the real model-bearing roots start the walk; `visit` handles nesting.\n for (const span of topLevel) visit(span);\n\n const leftover = normalise(root.usage);\n let leftoverCost = spanCost(root, totalCost);\n\n for (const span of topLevel) {\n subtract(leftover, normalise(span.usage));\n leftoverCost -= spanCost(span, totalCost);\n }\n\n if (leftover.input + leftover.output > 0) {\n deltas.push(\n buildDelta(\n { hour: hourOf(root), agent: cut(root.name, 200), model: UNKNOWN, provider: UNKNOWN },\n root.status,\n root.error?.type,\n leftover,\n Math.max(0, leftoverCost),\n ),\n );\n }\n\n return deltas;\n}\n\n/** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */\nexport function aiRollupNamesOf(span: Span): { agent: string; model: string; provider: string } {\n return {\n agent: cut(span.name, 200),\n model: cut(span.attributes?.[\"agent.model.name\"], 200),\n provider: cut(span.attributes?.[\"agent.model.provider\"], 100),\n };\n}\n\n/** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */\nexport function rollupId(key: RollupKey): string {\n return createHash(\"sha256\")\n .update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`)\n .digest(\"hex\")\n .slice(0, 40);\n}\n\n/** A delta with every counter at zero for `key`. */\nexport function emptyRollupDelta(key: RollupKey): DevtoolsAiRollupDelta {\n return {\n hour: key.hour,\n agent: key.agent,\n model: key.model,\n provider: key.provider,\n runs: 0,\n completed: 0,\n failed: 0,\n incomplete: 0,\n cancelled: 0,\n inputTokens: 0,\n outputTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n reasoningTokens: 0,\n costUsd: 0,\n pricedRuns: 0,\n unpricedRuns: 0,\n unpricedTokens: 0,\n fallbackRuns: 0,\n refusals: 0,\n errors: emptyErrorCounts(),\n latency: emptyAiLatency(),\n latencyCount: 0,\n latencySumMs: 0,\n };\n}\n\nconst NUMERIC_COUNTERS = [\n \"runs\",\n \"completed\",\n \"failed\",\n \"incomplete\",\n \"cancelled\",\n \"inputTokens\",\n \"outputTokens\",\n \"cachedTokens\",\n \"cacheWriteTokens\",\n \"reasoningTokens\",\n \"costUsd\",\n \"pricedRuns\",\n \"unpricedRuns\",\n \"unpricedTokens\",\n \"fallbackRuns\",\n \"refusals\",\n \"latencyCount\",\n \"latencySumMs\",\n] as const;\n\n/** Adds the counters of `source` into `target` in place (keys must match). */\nexport function addRollupCounters(\n target: DevtoolsAiRollupDelta,\n source: DevtoolsAiRollupDelta,\n): void {\n for (const field of NUMERIC_COUNTERS) target[field] += source[field];\n\n for (const category of Object.keys(target.errors) as (keyof typeof target.errors)[]) {\n target.errors[category] += source.errors[category] ?? 0;\n }\n\n addAiLatency(target.latency, source.latency);\n}\n"],"mappings":";;;;;;;;;;;AAoDA,MAAa,gCAAmD;CAC9D;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAQ;CAAO;AAAM,CAAC;;;;;AAMhF,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,WAAW;AACjB,MAAM,aAAa;AACnB,MAAM,0BAAU,IAAI,IAAyB;CAAC;CAAO;CAAQ;CAAO;CAAS;AAAQ,CAAC;;AAGtF,MAAM,gBAAwC;CAC5C,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,UAAU;AACZ;;AAGA,SAAgB,iBAAiB,MAAsB;CACrD,OAAO,cAAcA,kBAAK,QAAQ,IAAI,CAAC,CAAC,YAAY,MAAM;AAC5D;;AAGA,SAAS,WAAW,OAAoC;CACtD,IAAI,iBAAiB,KAAK,OAAO,MAAM,aAAa,cAAUC,wBAAc,KAAK,IAAI;CACrF,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO;CACtD,IAAI,MAAM,WAAW,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,OAAO,MAAM,GAC9C,OAAO,OAAO,aAAa,OAAO,OAAO,aAAa;CAGxD,aAAa,OAAO,SAAS,OAAO,OAAO;AAC7C"}
@@ -1,11 +1,11 @@
1
- const require_app_versions = require("./app-versions-DfpPZOI2.cjs");
1
+ const require_errors = require("./errors-DNQ-g49I.cjs");
2
2
  let node_crypto = require("node:crypto");
3
3
 
4
4
  //#region ../../packages/devtools/src/production/stats/histogram.ts
5
5
  /** An empty histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */
6
6
  function createHistogram() {
7
7
  return {
8
- counts: new Array(require_app_versions.DEVTOOLS_LATENCY_BUCKETS_MS.length + 1).fill(0),
8
+ counts: new Array(require_errors.DEVTOOLS_LATENCY_BUCKETS_MS.length + 1).fill(0),
9
9
  count: 0,
10
10
  sumMs: 0,
11
11
  maxMs: 0
@@ -13,8 +13,8 @@ function createHistogram() {
13
13
  }
14
14
  /** The bucket index a duration falls in. */
15
15
  function bucketIndex(durationMs) {
16
- for (let index = 0; index < require_app_versions.DEVTOOLS_LATENCY_BUCKETS_MS.length; index++) if (durationMs <= require_app_versions.DEVTOOLS_LATENCY_BUCKETS_MS[index]) return index;
17
- return require_app_versions.DEVTOOLS_LATENCY_BUCKETS_MS.length;
16
+ for (let index = 0; index < require_errors.DEVTOOLS_LATENCY_BUCKETS_MS.length; index++) if (durationMs <= require_errors.DEVTOOLS_LATENCY_BUCKETS_MS[index]) return index;
17
+ return require_errors.DEVTOOLS_LATENCY_BUCKETS_MS.length;
18
18
  }
19
19
  /** Adds one duration to `histogram` in place. A negative or non-finite value counts as 0. */
20
20
  function recordDuration(histogram, durationMs) {
@@ -47,7 +47,7 @@ function histogramQuantile(histogram, q) {
47
47
  for (let index = 0; index < histogram.counts.length; index++) {
48
48
  seen += histogram.counts[index] ?? 0;
49
49
  if (seen >= rank) {
50
- const bound = require_app_versions.DEVTOOLS_LATENCY_BUCKETS_MS[index];
50
+ const bound = require_errors.DEVTOOLS_LATENCY_BUCKETS_MS[index];
51
51
  return bound === void 0 ? histogram.maxMs : Math.min(bound, histogram.maxMs);
52
52
  }
53
53
  }
@@ -99,4 +99,4 @@ Object.defineProperty(exports, "shortId", {
99
99
  return shortId;
100
100
  }
101
101
  });
102
- //# sourceMappingURL=histogram-DTOGnNBW.cjs.map
102
+ //# sourceMappingURL=histogram-CkoVizdf.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"histogram-DTOGnNBW.cjs","names":["DEVTOOLS_LATENCY_BUCKETS_MS","createHash"],"sources":["../../../../../../../packages/devtools/src/production/stats/histogram.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { DEVTOOLS_LATENCY_BUCKETS_MS, type DevtoolsHistogram } from \"../contracts\";\n\n/** An empty histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport function createHistogram(): DevtoolsHistogram {\n return {\n counts: new Array<number>(DEVTOOLS_LATENCY_BUCKETS_MS.length + 1).fill(0),\n count: 0,\n sumMs: 0,\n maxMs: 0,\n };\n}\n\n/** The bucket index a duration falls in. */\nexport function bucketIndex(durationMs: number): number {\n for (let index = 0; index < DEVTOOLS_LATENCY_BUCKETS_MS.length; index++) {\n if (durationMs <= (DEVTOOLS_LATENCY_BUCKETS_MS[index] as number)) return index;\n }\n\n return DEVTOOLS_LATENCY_BUCKETS_MS.length;\n}\n\n/** Adds one duration to `histogram` in place. A negative or non-finite value counts as 0. */\nexport function recordDuration(histogram: DevtoolsHistogram, durationMs: number): void {\n const value = Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;\n const index = bucketIndex(value);\n\n histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;\n histogram.count += 1;\n histogram.sumMs += value;\n\n if (value > histogram.maxMs) histogram.maxMs = value;\n}\n\n/** The sum of several histograms (exact: they share the bucket bounds). */\nexport function mergeHistograms(histograms: readonly DevtoolsHistogram[]): DevtoolsHistogram {\n const merged = createHistogram();\n\n for (const histogram of histograms) {\n for (let index = 0; index < merged.counts.length; index++) {\n merged.counts[index] = (merged.counts[index] ?? 0) + (histogram.counts[index] ?? 0);\n }\n\n merged.count += histogram.count;\n merged.sumMs += histogram.sumMs;\n\n if (histogram.maxMs > merged.maxMs) merged.maxMs = histogram.maxMs;\n }\n\n return merged;\n}\n\n/**\n * The `q` quantile (0–1) of a histogram: the upper bound of the bucket that\n * holds it, capped at the largest value seen. 0 for an empty histogram.\n */\nexport function histogramQuantile(histogram: DevtoolsHistogram, q: number): number {\n if (histogram.count === 0) return 0;\n\n const rank = Math.max(1, Math.ceil(Math.min(Math.max(q, 0), 1) * histogram.count));\n let seen = 0;\n\n for (let index = 0; index < histogram.counts.length; index++) {\n seen += histogram.counts[index] ?? 0;\n\n if (seen >= rank) {\n const bound = DEVTOOLS_LATENCY_BUCKETS_MS[index];\n\n return bound === undefined ? histogram.maxMs : Math.min(bound, histogram.maxMs);\n }\n }\n\n return histogram.maxMs;\n}\n\n/** The mean duration, 0 for an empty histogram. */\nexport function histogramMean(histogram: DevtoolsHistogram): number {\n return histogram.count === 0 ? 0 : histogram.sumMs / histogram.count;\n}\n\n/** The first 16 hex characters of SHA-256: the id of a query shape or an error fingerprint. */\nexport function shortId(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 16);\n}\n"],"mappings":";;;;;AAIA,SAAgB,kBAAqC;CACnD,OAAO;EACL,QAAQ,IAAI,MAAcA,iDAA4B,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;EACxE,OAAO;EACP,OAAO;EACP,OAAO;CACT;AACF;;AAGA,SAAgB,YAAY,YAA4B;CACtD,KAAK,IAAI,QAAQ,GAAG,QAAQA,iDAA4B,QAAQ,SAC9D,IAAI,cAAeA,iDAA4B,QAAmB,OAAO;CAG3E,OAAOA,iDAA4B;AACrC;;AAGA,SAAgB,eAAe,WAA8B,YAA0B;CACrF,MAAM,QAAQ,OAAO,SAAS,UAAU,KAAK,aAAa,IAAI,aAAa;CAC3E,MAAM,QAAQ,YAAY,KAAK;CAE/B,UAAU,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UCKETS_MS","createHash"],"sources":["../../../../../../../packages/devtools/src/production/stats/histogram.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { DEVTOOLS_LATENCY_BUCKETS_MS, type DevtoolsHistogram } from \"../contracts\";\n\n/** An empty histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport function createHistogram(): DevtoolsHistogram {\n return {\n counts: new Array<number>(DEVTOOLS_LATENCY_BUCKETS_MS.length + 1).fill(0),\n count: 0,\n sumMs: 0,\n maxMs: 0,\n };\n}\n\n/** The bucket index a duration falls in. */\nexport function bucketIndex(durationMs: number): number {\n for (let index = 0; index < DEVTOOLS_LATENCY_BUCKETS_MS.length; index++) {\n if (durationMs <= (DEVTOOLS_LATENCY_BUCKETS_MS[index] as number)) return index;\n }\n\n return DEVTOOLS_LATENCY_BUCKETS_MS.length;\n}\n\n/** Adds one duration to `histogram` in place. A negative or non-finite value counts as 0. */\nexport function recordDuration(histogram: DevtoolsHistogram, durationMs: number): void {\n const value = Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;\n const index = bucketIndex(value);\n\n histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;\n histogram.count += 1;\n histogram.sumMs += value;\n\n if (value > histogram.maxMs) histogram.maxMs = value;\n}\n\n/** The sum of several histograms (exact: they share the bucket bounds). */\nexport function mergeHistograms(histograms: readonly DevtoolsHistogram[]): DevtoolsHistogram {\n const merged = createHistogram();\n\n for (const histogram of histograms) {\n for (let index = 0; index < merged.counts.length; index++) {\n merged.counts[index] = (merged.counts[index] ?? 0) + (histogram.counts[index] ?? 0);\n }\n\n merged.count += histogram.count;\n merged.sumMs += histogram.sumMs;\n\n if (histogram.maxMs > merged.maxMs) merged.maxMs = histogram.maxMs;\n }\n\n return merged;\n}\n\n/**\n * The `q` quantile (0–1) of a histogram: the upper bound of the bucket that\n * holds it, capped at the largest value seen. 0 for an empty histogram.\n */\nexport function histogramQuantile(histogram: DevtoolsHistogram, q: number): number {\n if (histogram.count === 0) return 0;\n\n const rank = Math.max(1, Math.ceil(Math.min(Math.max(q, 0), 1) * histogram.count));\n let seen = 0;\n\n for (let index = 0; index < histogram.counts.length; index++) {\n seen += histogram.counts[index] ?? 0;\n\n if (seen >= rank) {\n const bound = DEVTOOLS_LATENCY_BUCKETS_MS[index];\n\n return bound === undefined ? histogram.maxMs : Math.min(bound, histogram.maxMs);\n }\n }\n\n return histogram.maxMs;\n}\n\n/** The mean duration, 0 for an empty histogram. */\nexport function histogramMean(histogram: DevtoolsHistogram): number {\n return histogram.count === 0 ? 0 : histogram.sumMs / histogram.count;\n}\n\n/** The first 16 hex characters of SHA-256: the id of a query shape or an error fingerprint. */\nexport function shortId(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 16);\n}\n"],"mappings":";;;;;AAIA,SAAgB,kBAAqC;CACnD,OAAO;EACL,QAAQ,IAAI,MAAcA,2CAA4B,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;EACxE,OAAO;EACP,OAAO;EACP,OAAO;CACT;AACF;;AAGA,SAAgB,YAAY,YAA4B;CACtD,KAAK,IAAI,QAAQ,GAAG,QAAQA,2CAA4B,QAAQ,SAC9D,IAAI,cAAeA,2CAA4B,QAAmB,OAAO;CAG3E,OAAOA,2CAA4B;AACrC;;AAGA,SAAgB,eAAe,WAA8B,YAA0B;CACrF,MAAM,QAAQ,OAAO,SAAS,UAAU,KAAK,aAAa,IAAI,aAAa;CAC3E,MAAM,QAAQ,YAAY,KAAK;CAE/B,UAAU,OAAO,UAAU,UAAU,OAAO,UAAU,KAAK;CAC3D,UAAU,SAAS;CACnB,UAAU,SAAS;CAEnB,IAAI,QAAQ,UAAU,OAAO,UAAU,QAAQ;AACjD;;AAGA,SAAgB,gBAAgB,YAA6D;CAC3F,MAAM,SAAS,gBAAgB;CAE/B,KAAK,MAAM,aAAa,YAAY;EAClC,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,OAAO,QAAQ,SAChD,OAAO,OAAO,UAAU,OAAO,OAAO,UAAU,MAAM,UAAU,OAAO,UAAU;EAGnF,OAAO,SAAS,UAAU;EAC1B,OAAO,SAAS,UAAU;EAE1B,IAAI,UAAU,QAAQ,OAAO,OAAO,OAAO,QAAQ,UAAU;CAC/D;CAEA,OAAO;AACT;;;;;AAMA,SAAgB,kBAAkB,WAA8B,GAAmB;CACjF,IAAI,UAAU,UAAU,GAAG,OAAO;CAElC,MAAM,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,UAAU,KAAK,CAAC;CACjF,IAAI,OAAO;CAEX,KAAK,IAAI,QAAQ,GAAG,QAAQ,UAAU,OAAO,QAAQ,SAAS;EAC5D,QAAQ,UAAU,OAAO,UAAU;EAEnC,IAAI,QAAQ,MAAM;GAChB,MAAM,QAAQA,2CAA4B;GAE1C,OAAO,UAAU,SAAY,UAAU,QAAQ,KAAK,IAAI,OAAO,UAAU,KAAK;EAChF;CACF;CAEA,OAAO,UAAU;AACnB;;AAGA,SAAgB,cAAc,WAAsC;CAClE,OAAO,UAAU,UAAU,IAAI,IAAI,UAAU,QAAQ,UAAU;AACjE;;AAGA,SAAgB,QAAQ,OAAuB;CAC7C,WAAOC,wBAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;AACrE"}
@@ -1,9 +1,8 @@
1
- const require_app_versions = require("./app-versions-DfpPZOI2.cjs");
2
- const require_panels = require("./panels-D1ITm-jc.cjs");
3
- const require_errors = require("./errors-BadbSDX8.cjs");
1
+ const require_errors = require("./errors-DNQ-g49I.cjs");
2
+ const require_extract = require("./extract-8kaX_cUV.cjs");
4
3
  const require_ip = require("./ip-DbNhPOzi.cjs");
5
4
  const require_helpers = require("./helpers-BcMBFy9v.cjs");
6
- const require_stream_route = require("./stream-route-BqyAlfxQ.cjs");
5
+ const require_stream_route = require("./stream-route-DFHuIWgg.cjs");
7
6
  let node_crypto = require("node:crypto");
8
7
  let node_net = require("node:net");
9
8
 
@@ -96,6 +95,12 @@ function productionRouteAccess(panelIds, options = {}) {
96
95
  rule("GET", "/api/ai/agent-runs", VIEWER),
97
96
  rule("GET", "/api/ai/agent-runs/:id", VIEWER),
98
97
  rule("GET", "/api/ai/runs/:id", VIEWER),
98
+ rule("GET", "/api/ai/runs", VIEWER),
99
+ rule("GET", "/api/ai/reports", VIEWER),
100
+ rule("GET", "/api/ai/models", VIEWER),
101
+ rule("GET", "/api/ai/errors", VIEWER),
102
+ rule("GET", "/api/ai/evaluate", VIEWER),
103
+ rule("POST", "/api/ai/evaluate", ADMIN),
99
104
  rule("GET", "/api/openapi.json", VIEWER),
100
105
  rule("GET", "/api/postman.json", VIEWER),
101
106
  rule("GET", "/docs", VIEWER),
@@ -768,7 +773,7 @@ function createDevtoolsShare(deps) {
768
773
  const state = await store.state.read();
769
774
  const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);
770
775
  const count = await store.audit.count({
771
- types: require_app_versions.DEVTOOLS_FAILURE_AUDIT_TYPES,
776
+ types: require_errors.DEVTOOLS_FAILURE_AUDIT_TYPES,
772
777
  since,
773
778
  ip
774
779
  });
@@ -918,7 +923,7 @@ function createDevtoolsShare(deps) {
918
923
  const name = request.params.name;
919
924
  const file = panel.share?.assets.includes(name) === true && Object.hasOwn(panel.assets, name) ? panel.assets[name] : void 0;
920
925
  if (file === void 0) return notFound(request, reply);
921
- require_stream_route.sendFile(reply, file, require_panels.panelContentType(name));
926
+ require_stream_route.sendFile(reply, file, require_extract.panelContentType(name));
922
927
  return reply;
923
928
  });
924
929
  server.get("/api/share/files/*", async (request, reply) => {
@@ -1030,11 +1035,22 @@ const TAB_OF_ROUTE = [
1030
1035
  ["/api/requests", "requests"],
1031
1036
  ["/api/mails", "mail"],
1032
1037
  ["/api/ai/agent-runs", "agents"],
1038
+ ["/api/ai/reports", "ai-reports"],
1039
+ ["/api/ai/models", "ai-models"],
1040
+ ["/api/ai/errors", "ai-errors"],
1041
+ ["/api/ai/evaluate", "ai-evaluate"],
1033
1042
  ["/api/ai", "ai"],
1034
1043
  ["/api/openapi.json", "api"],
1035
1044
  ["/api/postman.json", "api"],
1036
1045
  ["/docs", "api"]
1037
1046
  ];
1047
+ /** The tabs the AI report routes serve; the routes register when any of them is on. */
1048
+ const AI_REPORT_TABS = [
1049
+ "ai-reports",
1050
+ "ai-models",
1051
+ "ai-errors",
1052
+ "ai-evaluate"
1053
+ ];
1038
1054
  function tabOf(pattern) {
1039
1055
  return TAB_OF_ROUTE.find(([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`))?.[1];
1040
1056
  }
@@ -1280,7 +1296,7 @@ function mountProductionDevtools(server, deps) {
1280
1296
  });
1281
1297
  require_stream_route.registerUiAssets(instance, { notFound });
1282
1298
  registerAuthRoutes(instance, deps);
1283
- instance.get("/api/panels", async () => require_panels.listPanelInfos(deps.panels, deps.builtInPanels));
1299
+ instance.get("/api/panels", async () => require_extract.listPanelInfos(deps.panels, deps.builtInPanels));
1284
1300
  require_stream_route.registerRequestsRoutes(instance, routes);
1285
1301
  require_stream_route.registerRouteRoutes(instance, routes);
1286
1302
  require_stream_route.registerInsightsRoutes(instance, routes);
@@ -1290,6 +1306,7 @@ function mountProductionDevtools(server, deps) {
1290
1306
  share?.register(instance, notFound);
1291
1307
  if (enabledTabs.has("mail")) require_stream_route.registerMailRoutes(instance, routes);
1292
1308
  if (enabledTabs.has("ai") || enabledTabs.has("agents")) require_stream_route.registerAiRoutes(instance, routes);
1309
+ if (AI_REPORT_TABS.some((tab) => enabledTabs.has(tab))) require_stream_route.registerAiReportRoutes(instance, routes);
1293
1310
  if (enabledTabs.has("api")) require_stream_route.registerOpenApiRoutes(instance, routes);
1294
1311
  require_stream_route.registerStreamRoute(instance, routes);
1295
1312
  }, { prefix });
@@ -1356,4 +1373,4 @@ exports.mountProductionDevtools = mountProductionDevtools;
1356
1373
  exports.productionRouteAccess = productionRouteAccess;
1357
1374
  exports.resolveClient = resolveClient;
1358
1375
  exports.sessionCookie = sessionCookie;
1359
- //# sourceMappingURL=http-Biauhqi0.cjs.map
1376
+ //# sourceMappingURL=http-DCVCf44M.cjs.map