@warlock.js/devtools 5.61.0 → 5.63.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 (46) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/cjs/{extract-8kaX_cUV.cjs → ai-source-CeHZDYG1.cjs} +449 -408
  3. package/cjs/ai-source-CeHZDYG1.cjs.map +1 -0
  4. package/cjs/{attach-D5aMqUnA.cjs → attach-D9gWc6lU.cjs} +19 -19
  5. package/cjs/attach-D9gWc6lU.cjs.map +1 -0
  6. package/cjs/{boot-D0nF-7w3.cjs → boot-Guumt-du.cjs} +10 -8
  7. package/cjs/boot-Guumt-du.cjs.map +1 -0
  8. package/cjs/{http-1nnpAoI7.cjs → http-CPbhLN61.cjs} +5 -5
  9. package/cjs/{http-1nnpAoI7.cjs.map → http-CPbhLN61.cjs.map} +1 -1
  10. package/cjs/index.cjs +1 -1
  11. package/cjs/{process-panel-D3D9Y_dc.cjs → process-panel-Dev6eg_f.cjs} +2 -2
  12. package/cjs/{process-panel-D3D9Y_dc.cjs.map → process-panel-Dev6eg_f.cjs.map} +1 -1
  13. package/cjs/{runs-DECWPGnq.cjs → runs-DXTf_o5P.cjs} +10 -11
  14. package/cjs/runs-DXTf_o5P.cjs.map +1 -0
  15. package/cjs/{server-DLT3uPef.cjs → server-Dc0YdP6Y.cjs} +6 -6
  16. package/cjs/{server-DLT3uPef.cjs.map → server-Dc0YdP6Y.cjs.map} +1 -1
  17. package/cjs/{src-BZiSv8A1.cjs → src-Ca1gNdZj.cjs} +15 -15
  18. package/cjs/{src-BZiSv8A1.cjs.map → src-Ca1gNdZj.cjs.map} +1 -1
  19. package/cjs/{stream-route-B6WAjbPG.cjs → stream-route-qEHoPVth.cjs} +21 -15
  20. package/cjs/stream-route-qEHoPVth.cjs.map +1 -0
  21. package/esm/ai/reports/runs.mjs +5 -6
  22. package/esm/ai/reports/runs.mjs.map +1 -1
  23. package/esm/ai/rollup/extract.mjs +21 -4
  24. package/esm/ai/rollup/extract.mjs.map +1 -1
  25. package/esm/panels.mjs +14 -1
  26. package/esm/panels.mjs.map +1 -1
  27. package/esm/production/boot.mjs +4 -2
  28. package/esm/production/boot.mjs.map +1 -1
  29. package/esm/production/options.d.mts +5 -0
  30. package/esm/production/options.d.mts.map +1 -1
  31. package/esm/production/options.mjs.map +1 -1
  32. package/esm/server/ai-routes.mjs +11 -5
  33. package/esm/server/ai-routes.mjs.map +1 -1
  34. package/esm/sources/ai-source.d.mts.map +1 -1
  35. package/esm/sources/ai-source.mjs +3 -3
  36. package/esm/sources/ai-source.mjs.map +1 -1
  37. package/esm/types.d.mts +5 -2
  38. package/esm/types.d.mts.map +1 -1
  39. package/llms-full.txt +5 -2
  40. package/package.json +8 -8
  41. package/skills/SKILL.md +5 -2
  42. package/cjs/attach-D5aMqUnA.cjs.map +0 -1
  43. package/cjs/boot-D0nF-7w3.cjs.map +0 -1
  44. package/cjs/extract-8kaX_cUV.cjs.map +0 -1
  45. package/cjs/runs-DECWPGnq.cjs.map +0 -1
  46. package/cjs/stream-route-B6WAjbPG.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-source-CeHZDYG1.cjs","names":["path","fileURLToPath","existsSync","statSync","pathToFileURL","readFileSync","createRequire","DEVTOOLS_BUILT_IN_PANELS","DEVTOOLS_AI_ERROR_CATEGORIES","DEVTOOLS_AI_LATENCY_BUCKETS_MS","createHash","installedVersion"],"sources":["../../../../../../../packages/devtools/src/panels.ts","../../../../../../../packages/devtools/src/ai/rollup/categories.ts","../../../../../../../packages/devtools/src/ai/rollup/histogram.ts","../../../../../../../packages/devtools/src/ai/rollup/extract.ts","../../../../../../../packages/devtools/src/safe-value.ts","../../../../../../../packages/devtools/src/sources/ai-source.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/** The tabs that read per-process run details; production keeps hourly totals instead. */\nexport const DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS: readonly string[] = [\"ai\", \"agents\"];\n\n/**\n * Drops the Runs (`ai`) and Agents (`agents`) tabs from a production tab list.\n * `ignored` lists the ones the project asked for (`production.panels[id] === true`),\n * so boot can warn once.\n */\nexport function withoutDevelopmentAiTabs(\n builtIn: readonly string[],\n overrides: Readonly<Record<string, boolean>> = {},\n): { builtIn: string[]; ignored: string[] } {\n return {\n builtIn: builtIn.filter((tab) => !DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.includes(tab)),\n ignored: DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.filter((tab) => overrides[tab] === true),\n };\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","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/**\n * The model a span reports: `agent.model.*` first, then `<span type>.model.*`\n * (image, speech and transcription spans).\n */\nexport function spanModelOf(span: Span): { name?: string; provider?: string } {\n const attributes = span.attributes;\n const pick = (key: string): string | undefined => {\n for (const prefix of [\"agent\", span.type]) {\n const value = attributes?.[`${prefix}.${key}`];\n\n if (typeof value === \"string\" && value !== \"\") return value;\n }\n\n return undefined;\n };\n\n return { name: pick(\"model.name\"), provider: pick(\"model.provider\") };\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 spanModelOf(span).name !== undefined || MODEL_SPAN_TYPES.has(span.type);\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(spanModelOf(span).name, 200),\n provider: cut(spanModelOf(span).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","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 { spanModelOf } from \"../ai/rollup/extract\";\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 { name: model, provider } = spanModelOf(span);\n if (model !== undefined) models.add(provider !== undefined ? `${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"],"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,OAAO,GAAG,WAAOA,wBAAc,KAAK;CAEzD,OAAOD,kBAAK,WAAW,KAAK,IAAI,QAAQ;AAC1C;AAEA,SAAS,OAAO,MAAuB;CACrC,WAAOE,oBAAW,IAAI,SAAKC,kBAAS,IAAI,CAAC,CAAC,OAAO;AACnD;;;;;;AAOA,SAAgB,mBACd,OACA,OACsB;CACtB,MAAM,QAAS,SAAS,CAAC;CACzB,MAAM,KAAK,MAA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Y,UAAU,SAAS,aAAa,KAAK;EACjD,SAAS;GACP,cAAc,SAAS;GACvB,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,aAAa,SAAS;GACtB,YAAY,SAAS;GACrB,gBAAgB,SAAS;EAC3B;EACA;EACA,YAAY,UAAU,iBAAiB,OAAO,SAAS,aAAa,MAAM,KAAK,CAAC;EAChF,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,OAAO;GACP,UAAU,MAAM;GAChB,MAAM,MAAM;EACd;CACF;AACF"}
@@ -1,6 +1,6 @@
1
1
  const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
2
2
  const require_errors = require("./errors-DNQ-g49I.cjs");
3
- const require_extract = require("./extract-8kaX_cUV.cjs");
3
+ const require_ai_source = require("./ai-source-CeHZDYG1.cjs");
4
4
  const require_ip = require("./ip-DbNhPOzi.cjs");
5
5
  let node_path = require("node:path");
6
6
  node_path = require_app_versions.__toESM(node_path, 1);
@@ -265,7 +265,7 @@ function totalsOf(rows) {
265
265
  fallbackRuns: 0,
266
266
  refusals: 0
267
267
  };
268
- const histogram = require_extract.emptyAiLatency();
268
+ const histogram = require_ai_source.emptyAiLatency();
269
269
  let latencyCount = 0;
270
270
  let latencySumMs = 0;
271
271
  for (const row of rows) {
@@ -285,14 +285,14 @@ function totalsOf(rows) {
285
285
  totals.cost.unpricedTokens += row.unpricedTokens;
286
286
  totals.fallbackRuns += row.fallbackRuns;
287
287
  totals.refusals += row.refusals;
288
- require_extract.addAiLatency(histogram, row.latency);
288
+ require_ai_source.addAiLatency(histogram, row.latency);
289
289
  latencyCount += row.latencyCount;
290
290
  latencySumMs += row.latencySumMs;
291
291
  }
292
292
  totals.errorRate = totals.runs > 0 ? (totals.failed + totals.incomplete) / totals.runs : 0;
293
293
  totals.latency = {
294
- p50Ms: require_extract.aiLatencyQuantile(histogram, .5),
295
- p95Ms: require_extract.aiLatencyQuantile(histogram, .95),
294
+ p50Ms: require_ai_source.aiLatencyQuantile(histogram, .5),
295
+ p95Ms: require_ai_source.aiLatencyQuantile(histogram, .95),
296
296
  meanMs: latencyCount > 0 ? latencySumMs / latencyCount : null
297
297
  };
298
298
  return totals;
@@ -430,7 +430,7 @@ function errorSeries(rows, range) {
430
430
  if (value > 0) entries.push({
431
431
  bucket,
432
432
  key: category,
433
- label: require_extract.DEVTOOLS_AI_ERROR_LABELS[category],
433
+ label: require_ai_source.DEVTOOLS_AI_ERROR_LABELS[category],
434
434
  value
435
435
  });
436
436
  }
@@ -522,7 +522,7 @@ function errorGroups(rows, previousRows) {
522
522
  const total = counted.reduce((sum, item) => sum + item.count, 0);
523
523
  return counted.filter((item) => item.count > 0).sort((a, b) => b.count - a.count).map(({ category, count }) => ({
524
524
  category,
525
- label: require_extract.DEVTOOLS_AI_ERROR_LABELS[category],
525
+ label: require_ai_source.DEVTOOLS_AI_ERROR_LABELS[category],
526
526
  count,
527
527
  share: total > 0 ? count / total : 0,
528
528
  previousCount: countErrors(previousRows, category),
@@ -840,7 +840,7 @@ function deltaToIncrements(delta) {
840
840
  /** A record from a row; numbers a driver returns as strings are converted. */
841
841
  function rowToRecord(row) {
842
842
  const record = {
843
- ...require_extract.emptyRollupDelta({
843
+ ...require_ai_source.emptyRollupDelta({
844
844
  hour: number(row.hour),
845
845
  agent: String(row.agent ?? ""),
846
846
  model: String(row.model ?? ""),
@@ -920,7 +920,7 @@ async function createCascadeAiRollupStore(options = {}) {
920
920
  }
921
921
  };
922
922
  if (Object.keys(increments).length > 0) operations.$inc = increments;
923
- await Rollups.atomic({ id: require_extract.rollupId(delta) }, operations, {
923
+ await Rollups.atomic({ id: require_ai_source.rollupId(delta) }, operations, {
924
924
  upsert: true,
925
925
  trustedFilter: true
926
926
  });
@@ -958,10 +958,10 @@ function matchesAiRollupFilter(record, filter) {
958
958
  }
959
959
  /** Adds a delta into `rows` (creating the record when missing); shared by the memory and file stores. */
960
960
  function applyAiRollupDelta(rows, delta, at) {
961
- const id = require_extract.rollupId(delta);
961
+ const id = require_ai_source.rollupId(delta);
962
962
  const existing = rows.get(id);
963
963
  if (existing) {
964
- require_extract.addRollupCounters(existing, delta);
964
+ require_ai_source.addRollupCounters(existing, delta);
965
965
  existing.updatedAt = at;
966
966
  return;
967
967
  }
@@ -1148,7 +1148,7 @@ function startAiRollupWriter(input) {
1148
1148
  };
1149
1149
  /** Adds a delta, folding a new key into agent `(other)` once `maxKeys` is reached. */
1150
1150
  const add = (delta) => {
1151
- let id = require_extract.rollupId(delta);
1151
+ let id = require_ai_source.rollupId(delta);
1152
1152
  let target = pending.get(id);
1153
1153
  let source = delta;
1154
1154
  if (!target && pending.size >= maxKeys) {
@@ -1156,10 +1156,10 @@ function startAiRollupWriter(input) {
1156
1156
  ...structuredClone(delta),
1157
1157
  agent: "(other)"
1158
1158
  };
1159
- id = require_extract.rollupId(source);
1159
+ id = require_ai_source.rollupId(source);
1160
1160
  target = pending.get(id);
1161
1161
  }
1162
- if (target) require_extract.addRollupCounters(target, source);
1162
+ if (target) require_ai_source.addRollupCounters(target, source);
1163
1163
  else pending.set(id, structuredClone(source));
1164
1164
  };
1165
1165
  const writeNow = async () => {
@@ -1196,7 +1196,7 @@ function startAiRollupWriter(input) {
1196
1196
  return {
1197
1197
  record(trace) {
1198
1198
  try {
1199
- for (const delta of require_extract.traceToRollupDeltas(trace, totalCost)) add(delta);
1199
+ for (const delta of require_ai_source.traceToRollupDeltas(trace, totalCost)) add(delta);
1200
1200
  } catch {}
1201
1201
  },
1202
1202
  pending() {
@@ -1229,8 +1229,8 @@ function startAiRollupWriter(input) {
1229
1229
  * when they do not load. Shared by the development and production wiring.
1230
1230
  */
1231
1231
  async function loadAiFeed(deps) {
1232
- const loaded = await require_extract.loadAiPackages(deps);
1233
- if ("unavailable" in loaded) return { unavailable: require_extract.toAiUnavailableView(loaded.unavailable) };
1232
+ const loaded = await require_ai_source.loadAiPackages(deps);
1233
+ if ("unavailable" in loaded) return { unavailable: require_ai_source.toAiUnavailableView(loaded.unavailable) };
1234
1234
  const { panoptic, observationOff } = loaded;
1235
1235
  return {
1236
1236
  feed: {
@@ -1260,7 +1260,7 @@ const TABLE_MISSING_WARNING = "AI reports are off: the devtools_ai_rollups table
1260
1260
  async function attachAiReports(input) {
1261
1261
  const { feed, options, warn } = input;
1262
1262
  const off = (reason) => ({
1263
- ...require_extract.toAiUnavailableView(require_extract.describeAiUnavailable(reason)),
1263
+ ...require_ai_source.toAiUnavailableView(require_ai_source.describeAiUnavailable(reason)),
1264
1264
  async dispose() {}
1265
1265
  });
1266
1266
  if (!options.reports) return off("reports-off");
@@ -1339,4 +1339,4 @@ Object.defineProperty(exports, "resolveProductionOptions", {
1339
1339
  return resolveProductionOptions;
1340
1340
  }
1341
1341
  });
1342
- //# sourceMappingURL=attach-D5aMqUnA.cjs.map
1342
+ //# sourceMappingURL=attach-D9gWc6lU.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach-D9gWc6lU.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 /**\n * Turn a dashboard tab on or off by id. `ai` (Runs) and `agents` are development\n * tabs: they are ignored in production, with one warning at boot. Production\n * shows AI totals in the Reports, Models and Errors tabs.\n */\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,gCAAgC;;;;;;AAO7C,SAAgB,yBACd,SACA,MAC2B;CAC3B,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,gBAAgB,SAAS,iBAAiB,2BAA2B;CAC3E,MAAM,kBAAkB,SAAS;CAEjC,IAAI,OAAO,YAAY,WACrB,MAAM,IAAI,MAAM,u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