@warlock.js/devtools 5.60.0 → 5.62.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 (83) hide show
  1. package/CHANGELOG.md +20 -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-Dg5YZGGR.cjs → boot-Guumt-du.cjs} +13 -10
  7. package/cjs/boot-Guumt-du.cjs.map +1 -0
  8. package/cjs/{capture-CBgONYhk.cjs → capture-D2k0GnBN.cjs} +21 -420
  9. package/cjs/capture-D2k0GnBN.cjs.map +1 -0
  10. package/cjs/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
  11. package/cjs/collector-BfC4v87v.cjs.map +1 -0
  12. package/cjs/errors-DNQ-g49I.cjs.map +1 -1
  13. package/cjs/{http-DCVCf44M.cjs → http-CPbhLN61.cjs} +13 -7
  14. package/cjs/http-CPbhLN61.cjs.map +1 -0
  15. package/cjs/index.cjs +1 -1
  16. package/cjs/{insights-CFof59kF.cjs → insights-COA3u37q.cjs} +53 -21
  17. package/cjs/insights-COA3u37q.cjs.map +1 -0
  18. package/cjs/{process-panel-D3D9Y_dc.cjs → process-panel-Dev6eg_f.cjs} +2 -2
  19. package/cjs/{process-panel-D3D9Y_dc.cjs.map → process-panel-Dev6eg_f.cjs.map} +1 -1
  20. package/cjs/query-shape-DShKQa0x.cjs +45 -0
  21. package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
  22. package/cjs/redact-DQ28mDzr.cjs +533 -0
  23. package/cjs/redact-DQ28mDzr.cjs.map +1 -0
  24. package/cjs/{runs-DECWPGnq.cjs → runs-DXTf_o5P.cjs} +10 -11
  25. package/cjs/runs-DXTf_o5P.cjs.map +1 -0
  26. package/cjs/{server-CC5DpObz.cjs → server-Dc0YdP6Y.cjs} +6 -6
  27. package/cjs/{server-CC5DpObz.cjs.map → server-Dc0YdP6Y.cjs.map} +1 -1
  28. package/cjs/{src-VyOjEEAo.cjs → src-Ca1gNdZj.cjs} +21 -18
  29. package/cjs/src-Ca1gNdZj.cjs.map +1 -0
  30. package/cjs/{stream-route-DFHuIWgg.cjs → stream-route-qEHoPVth.cjs} +25 -22
  31. package/cjs/stream-route-qEHoPVth.cjs.map +1 -0
  32. package/esm/ai/reports/runs.mjs +5 -6
  33. package/esm/ai/reports/runs.mjs.map +1 -1
  34. package/esm/ai/rollup/extract.mjs +21 -4
  35. package/esm/ai/rollup/extract.mjs.map +1 -1
  36. package/esm/devtools-connector.d.mts.map +1 -1
  37. package/esm/devtools-connector.mjs +4 -1
  38. package/esm/devtools-connector.mjs.map +1 -1
  39. package/esm/index.d.mts +2 -2
  40. package/esm/panels.mjs +14 -1
  41. package/esm/panels.mjs.map +1 -1
  42. package/esm/production/boot.mjs +5 -2
  43. package/esm/production/boot.mjs.map +1 -1
  44. package/esm/production/contracts.d.mts +17 -4
  45. package/esm/production/contracts.d.mts.map +1 -1
  46. package/esm/production/contracts.mjs.map +1 -1
  47. package/esm/production/http/mount.mjs +8 -2
  48. package/esm/production/http/mount.mjs.map +1 -1
  49. package/esm/production/http/share.mjs.map +1 -1
  50. package/esm/production/index.d.mts +2 -2
  51. package/esm/production/insights/jobs.mjs +45 -11
  52. package/esm/production/insights/jobs.mjs.map +1 -1
  53. package/esm/production/options.d.mts +5 -0
  54. package/esm/production/options.d.mts.map +1 -1
  55. package/esm/production/options.mjs.map +1 -1
  56. package/esm/server/ai-routes.mjs +11 -5
  57. package/esm/server/ai-routes.mjs.map +1 -1
  58. package/esm/server/panel-routes.mjs.map +1 -1
  59. package/esm/server/ui-assets.mjs +4 -7
  60. package/esm/server/ui-assets.mjs.map +1 -1
  61. package/esm/sources/ai-source.d.mts.map +1 -1
  62. package/esm/sources/ai-source.mjs +3 -3
  63. package/esm/sources/ai-source.mjs.map +1 -1
  64. package/esm/types.d.mts +7 -4
  65. package/esm/types.d.mts.map +1 -1
  66. package/llms-full.txt +27 -24
  67. package/package.json +8 -8
  68. package/skills/SKILL.md +27 -24
  69. package/ui/dashboard/assets/app.css +1 -1
  70. package/ui/dashboard/assets/app.js +2 -2
  71. package/ui/dashboard/build-info.json +7 -7
  72. package/cjs/attach-D5aMqUnA.cjs.map +0 -1
  73. package/cjs/boot-Dg5YZGGR.cjs.map +0 -1
  74. package/cjs/capture-CBgONYhk.cjs.map +0 -1
  75. package/cjs/collector-CJbQbzzK.cjs.map +0 -1
  76. package/cjs/extract-8kaX_cUV.cjs.map +0 -1
  77. package/cjs/histogram-CkoVizdf.cjs +0 -102
  78. package/cjs/histogram-CkoVizdf.cjs.map +0 -1
  79. package/cjs/http-DCVCf44M.cjs.map +0 -1
  80. package/cjs/insights-CFof59kF.cjs.map +0 -1
  81. package/cjs/runs-DECWPGnq.cjs.map +0 -1
  82. package/cjs/src-VyOjEEAo.cjs.map +0 -1
  83. package/cjs/stream-route-DFHuIWgg.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"extract-8kaX_cUV.cjs","names":["path","fileURLToPath","existsSync","statSync","pathToFileURL","readFileSync","createRequire","DEVTOOLS_BUILT_IN_PANELS","installedVersion","DEVTOOLS_AI_ERROR_CATEGORIES","DEVTOOLS_AI_LATENCY_BUCKETS_MS","createHash"],"sources":["../../../../../../../packages/devtools/src/panels.ts","../../../../../../../packages/devtools/src/safe-value.ts","../../../../../../../packages/devtools/src/sources/ai-source.ts","../../../../../../../packages/devtools/src/ai/rollup/categories.ts","../../../../../../../packages/devtools/src/ai/rollup/histogram.ts","../../../../../../../packages/devtools/src/ai/rollup/extract.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { DEVTOOLS_BUILT_IN_PANELS } from \"./production/contracts\";\nimport type { DevtoolsMode, DevtoolsPanelInfo } from \"./production/contracts\";\nimport type {\n DevtoolsPanel,\n DevtoolsPanelEntry,\n DevtoolsPanelErrorSummary,\n DevtoolsPanelExport,\n DevtoolsPanelMethod,\n DevtoolsPanelRoute,\n} from \"./types\";\n\n/**\n * A validated panel: file paths are absolute strings and every list is\n * present, so the server never re-checks them per request.\n */\nexport type MountedDevtoolsPanel = {\n id: string;\n title: string;\n view: string;\n routes: readonly (DevtoolsPanelRoute & { method: DevtoolsPanelMethod })[];\n assets: Readonly<Record<string, string>>;\n /** The folder of images the panel serves; `null` when it declared none. */\n files: MountedPanelFiles | null;\n /** What a read-only share link of the panel opens; `null` when the panel cannot be shared. */\n share: MountedPanelShare | null;\n /** Whether the panel declared itself safe for the production monitor. */\n production: boolean;\n};\n\n/** A panel's folder of images, validated: an absolute directory and lower-case extensions. */\nexport type MountedPanelFiles = {\n dir: string;\n extensions: readonly string[];\n};\n\n/** A panel's shared view, validated. */\nexport type MountedPanelShare = {\n /** Absolute path of the shared view module. */\n view: string;\n /** Paths of the GET routes the shared page may call. */\n routes: readonly string[];\n /** Served names from `assets` the shared page may load. */\n assets: readonly string[];\n /** Whether the shared page may load images from `files`. */\n files: boolean;\n};\n\n/** The extensions a panel serves from `files` when it lists none. */\nexport const DEFAULT_PANEL_FILE_EXTENSIONS: readonly string[] = [\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".webp\",\n \".gif\",\n];\n\n/** Extensions a panel may never serve from `files`: a browser runs or renders them as a page. */\nconst BLOCKED_FILE_EXTENSIONS = new Set([\".svg\", \".html\", \".htm\", \".js\", \".mjs\"]);\n\n/**\n * Ids the dashboard already uses for its own tabs, API segments and URLs. A\n * panel's routes live under `<path>/api/<id>`, so these would collide.\n */\nconst RESERVED_PANEL_IDS = new Set([\n \"account\",\n \"admin\",\n \"agents\",\n \"ai\",\n \"api\",\n \"assets\",\n \"auth\",\n \"background\",\n \"docs\",\n \"errors\",\n \"health\",\n \"instances\",\n \"jobs\",\n \"logs\",\n \"mail\",\n \"mails\",\n \"panels\",\n \"queries\",\n \"requests\",\n \"resources\",\n \"routes\",\n \"share\",\n \"stream\",\n]);\n\nconst PANEL_ID = /^[a-z][a-z0-9-]*$/;\nconst ASSET_NAME = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;\nconst METHODS = new Set<DevtoolsPanelMethod>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/** Content types for the files a panel may serve; anything else is sent as bytes. */\nconst CONTENT_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".gif\": \"image/gif\",\n \".woff2\": \"font/woff2\",\n};\n\n/** The content type a panel file is served with, from its served name. */\nexport function panelContentType(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** An absolute file path from a path or `file:` URL, or `undefined` for anything else. */\nfunction toFilePath(value: unknown): string | undefined {\n if (value instanceof URL) return value.protocol === \"file:\" ? fileURLToPath(value) : undefined;\n if (typeof value !== \"string\" || value === \"\") return undefined;\n if (value.startsWith(\"file:\")) return fileURLToPath(value);\n\n return path.isAbsolute(value) ? value : undefined;\n}\n\nfunction isFile(file: string): boolean {\n return existsSync(file) && statSync(file).isFile();\n}\n\n/**\n * Validates `value` as a panel and returns it ready to mount. Throws an\n * error that names the panel and what to change; `taken` maps the ids\n * already registered to their titles and receives this panel's id.\n */\nexport function checkDevtoolsPanel(\n value: unknown,\n taken: Map<string, string>,\n): MountedDevtoolsPanel {\n const panel = (value ?? {}) as Partial<DevtoolsPanel>;\n const id = panel.id;\n\n if (typeof id !== \"string\" || !PANEL_ID.test(id)) {\n throw new Error(\n `A devtools panel needs an \"id\" of lower-case letters, digits and dashes that starts with a letter; got ${JSON.stringify(id)}.`,\n );\n }\n\n if (RESERVED_PANEL_IDS.has(id)) {\n throw new Error(\n `Devtools panel id \"${id}\" is used by the dashboard itself; give the panel another id.`,\n );\n }\n\n const existing = taken.get(id);\n\n if (existing !== undefined) {\n throw new Error(\n `Devtools panel id \"${id}\" is already registered by the \"${existing}\" panel; each panel needs its own id.`,\n );\n }\n\n if (typeof panel.title !== \"string\" || panel.title.trim() === \"\") {\n throw new Error(`Devtools panel \"${id}\" needs a \"title\" for its tab.`);\n }\n\n const view = toFilePath(panel.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs a \"view\": an absolute path or file: URL of its browser module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n // Two routes on one method and path would make the server refuse to start.\n const seen = new Set<string>();\n const routes = (panel.routes ?? []).map((route) => {\n const method = route.method ?? \"GET\";\n\n if (!METHODS.has(method)) {\n throw new Error(\n `Devtools panel \"${id}\" has a route with method \"${String(method)}\"; use GET, POST, PUT, PATCH or DELETE.`,\n );\n }\n\n if (typeof route.path !== \"string\" || (route.path !== \"\" && !route.path.startsWith(\"/\"))) {\n throw new Error(\n `Devtools panel \"${id}\" has a route path ${JSON.stringify(route.path)}; use \"\" or a path starting with \"/\".`,\n );\n }\n\n if (typeof route.handler !== \"function\") {\n throw new Error(`Devtools panel \"${id}\" route ${method} \"${route.path}\" has no handler.`);\n }\n\n if (seen.has(`${method} ${route.path}`)) {\n throw new Error(\n `Devtools panel \"${id}\" lists route ${method} \"${route.path}\" twice; keep one.`,\n );\n }\n\n seen.add(`${method} ${route.path}`);\n\n return { ...route, method };\n });\n\n const assets: Record<string, string> = {};\n\n for (const [name, source] of Object.entries(panel.assets ?? {})) {\n if (!ASSET_NAME.test(name) || name === \"view.js\") {\n throw new Error(\n `Devtools panel \"${id}\" has an asset named ${JSON.stringify(name)}; use a plain file name other than \"view.js\".`,\n );\n }\n\n const file = toFilePath(source);\n\n if (file === undefined || !isFile(file)) {\n throw new Error(\n `The asset \"${name}\" of devtools panel \"${id}\" was not found at ${String(source)}; give an absolute path or file: URL.`,\n );\n }\n\n assets[name] = file;\n }\n\n const files = checkPanelFiles(id, panel.files);\n const share = checkPanelShare(id, panel.share, routes, assets, files !== null);\n\n taken.set(id, panel.title);\n\n return {\n id,\n title: panel.title,\n view,\n routes,\n assets,\n files,\n share,\n production: panel.production === true,\n };\n}\n\nconst FILE_EXTENSION = /^\\.[a-z0-9]{1,16}$/;\n\n/** Validates `files`; `null` when the panel declares none. */\nfunction checkPanelFiles(\n id: string,\n value: DevtoolsPanel[\"files\"] | null,\n): MountedPanelFiles | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has files that is not an object; use { dir: \"/absolute/folder\" }.`,\n );\n }\n\n const dir = toFilePath(value.dir);\n\n if (dir === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs files.dir to be an absolute path or a file: URL; got ${String(value.dir)}.`,\n );\n }\n\n const given = value.extensions;\n\n if (given !== undefined && (!Array.isArray(given) || given.length === 0)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions that is not a list; use [\".png\", \".jpg\"] or leave it out.`,\n );\n }\n\n for (const extension of given ?? []) {\n if (typeof extension !== \"string\" || !FILE_EXTENSION.test(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions entry ${JSON.stringify(extension)}; use lower-case extensions that start with a dot, such as \".png\".`,\n );\n }\n\n if (BLOCKED_FILE_EXTENSIONS.has(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" lists files.extensions entry \"${extension}\", which can run as a page or script in the browser; remove it (images such as .png, .jpg, .webp and .gif are fine).`,\n );\n }\n }\n\n return { dir, extensions: [...(given ?? DEFAULT_PANEL_FILE_EXTENSIONS)] };\n}\n\n/** Validates `share` against the panel's own routes, assets and files. */\nfunction checkPanelShare(\n id: string,\n value: DevtoolsPanel[\"share\"] | null,\n routes: readonly { method: DevtoolsPanelMethod; path: string }[],\n assets: Readonly<Record<string, string>>,\n hasFiles: boolean,\n): MountedPanelShare | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has share that is not an object; use { view, routes }.`,\n );\n }\n\n const view = toFilePath(value.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.view: an absolute path or file: URL of the shared view module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The share.view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n if (!Array.isArray(value.routes)) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.routes: a list of the paths of its GET routes the shared page may call.`,\n );\n }\n\n const getPaths = routes.filter((route) => route.method === \"GET\").map((route) => route.path);\n\n for (const route of value.routes) {\n if (typeof route !== \"string\" || !getPaths.includes(route)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.routes entry ${JSON.stringify(route)}, which is not the path of one of its GET routes${getPaths.length > 0 ? `; use one of ${getPaths.map((path) => JSON.stringify(path)).join(\", \")}` : \" (the panel has no GET routes)\"}.`,\n );\n }\n }\n\n for (const name of value.assets ?? []) {\n if (typeof name !== \"string\" || !Object.hasOwn(assets, name)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.assets entry ${JSON.stringify(name)}, which is not a name in its assets; use one of ${Object.keys(assets).join(\", \") || \"(the panel has no assets)\"}.`,\n );\n }\n }\n\n const files = value.files === true;\n\n if (value.files !== undefined && typeof value.files !== \"boolean\") {\n throw new Error(`Devtools panel \"${id}\" needs share.files to be true or false.`);\n }\n\n if (files && !hasFiles) {\n throw new Error(\n `Devtools panel \"${id}\" sets share.files, but the panel has no files folder; add files: { dir } or remove share.files.`,\n );\n }\n\n return { view, routes: [...value.routes], assets: [...(value.assets ?? [])], files };\n}\n\n/** Validates a list of panels; the first invalid or duplicate one throws. */\nexport function checkDevtoolsPanels(panels: readonly unknown[]): MountedDevtoolsPanel[] {\n const taken = new Map<string, string>();\n\n return panels.map((panel) => checkDevtoolsPanel(panel, taken));\n}\n\n/** Hooks `loadDevtoolsPanels` uses; replaced in specs. */\nexport type LoadDevtoolsPanelsOptions = {\n /** The app's root directory: bare specifiers resolve from here, `./` paths are relative to it. */\n root: string;\n /** Receives one line per entry that could not be loaded or was rejected. */\n warn: (message: string) => void;\n /** Ids already taken (the built-in panels), mapped to their titles. */\n taken?: ReadonlyMap<string, string>;\n /** Imports a module URL or specifier; defaults to a dynamic `import()`. */\n importModule?: (specifier: string) => Promise<unknown>;\n /** Where the dashboard runs; panel factories receive it as `context.mode`. @default \"development\" */\n mode?: DevtoolsMode;\n /** The captured error groups of the last hour; panel factories receive it as `context.errors`. */\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\n/** What is wrong with a `[specifier, options]` entry, or `undefined` when it is valid. */\nfunction tupleProblem(entry: readonly unknown[]): string | undefined {\n if (entry.length !== 2) {\n return `it has ${entry.length} item(s); use exactly [specifier, options]`;\n }\n\n if (typeof entry[0] !== \"string\" || entry[0] === \"\") {\n return `its first item is ${JSON.stringify(entry[0])}; use the module specifier as a string`;\n }\n\n if (!isPlainObject(entry[1])) {\n return `its second item is not a plain object; pass the options as { name: value }`;\n }\n\n return undefined;\n}\n\n/** The URL or specifier to import for a `panels` entry. */\nfunction resolvePanelSpecifier(entry: string, root: string): string {\n if (entry.startsWith(\"./\") || entry.startsWith(\"../\") || path.isAbsolute(entry)) {\n return pathToFileURL(path.resolve(root, entry)).href;\n }\n\n return resolveFromNodeModules(entry, root) ?? resolveWithRequire(entry, root) ?? entry;\n}\n\n/** Picks the file an `exports` target names: `import`, then `default`, then `node`. */\nfunction exportTarget(target: unknown): string | undefined {\n if (typeof target === \"string\") return target;\n\n if (Array.isArray(target)) {\n for (const item of target) {\n const found = exportTarget(item);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n }\n\n if (target !== null && typeof target === \"object\") {\n const conditions = target as Record<string, unknown>;\n\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const found = exportTarget(conditions[condition]);\n\n if (found !== undefined) return found;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a package specifier by looking it up in the `node_modules` folders\n * above the app root and reading its `exports` map. `createRequire().resolve`\n * cannot do this for a package that only has an `import` condition.\n */\nfunction resolveFromNodeModules(entry: string, root: string): string | undefined {\n const parts = entry.split(\"/\");\n const nameLength = entry.startsWith(\"@\") ? 2 : 1;\n const name = parts.slice(0, nameLength).join(\"/\");\n const subpath = parts.length > nameLength ? `./${parts.slice(nameLength).join(\"/\")}` : \".\";\n\n if (!name) return undefined;\n\n let directory = path.resolve(root);\n\n for (;;) {\n const packageDirectory = path.join(directory, \"node_modules\", name);\n const manifestFile = path.join(packageDirectory, \"package.json\");\n\n if (existsSync(manifestFile)) {\n try {\n const manifest = JSON.parse(readFileSync(manifestFile, \"utf8\")) as {\n exports?: unknown;\n main?: string;\n };\n const exported = manifest.exports;\n const map =\n exported !== null && typeof exported === \"object\" && !Array.isArray(exported)\n ? (exported as Record<string, unknown>)\n : undefined;\n const hasSubpaths =\n map !== undefined && Object.keys(map).some((key) => key.startsWith(\".\"));\n const target =\n exported === undefined\n ? subpath === \".\"\n ? (manifest.main ?? \"index.js\")\n : subpath\n : hasSubpaths\n ? exportTarget(map?.[subpath])\n : subpath === \".\"\n ? exportTarget(exported)\n : undefined;\n\n if (target === undefined) return undefined;\n\n const file = path.resolve(packageDirectory, target);\n\n return isFile(file) ? pathToFileURL(file).href : undefined;\n } catch {\n return undefined;\n }\n }\n\n const parent = path.dirname(directory);\n\n if (parent === directory) return undefined;\n\n directory = parent;\n }\n}\n\n/** The `require` resolution, for packages the `node_modules` lookup does not understand. */\nfunction resolveWithRequire(entry: string, root: string): string | undefined {\n try {\n return pathToFileURL(createRequire(path.join(root, \"package.json\")).resolve(entry)).href;\n } catch {\n return undefined;\n }\n}\n\n/** The panels a module's default export describes. */\nasync function panelsOf(\n exported: DevtoolsPanelExport,\n root: string,\n mode: DevtoolsMode,\n panelOptions: Readonly<Record<string, unknown>> = {},\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>,\n): Promise<readonly unknown[]> {\n const value =\n typeof exported === \"function\"\n ? await exported({ ...panelOptions, root, mode, ...(errors ? { errors } : {}) })\n : exported;\n\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Loads the devtools `panels` option: imports each module entry, reads its\n * default export, and validates every panel. An entry that fails to load and\n * a panel that is invalid or reuses an id are reported through `warn` and\n * skipped, so one broken panel never stops the dashboard.\n */\nexport async function loadDevtoolsPanels(\n entries: readonly DevtoolsPanelEntry[],\n options: LoadDevtoolsPanelsOptions,\n): Promise<MountedDevtoolsPanel[]> {\n // `src/config/devtools.ts` is a plain object with no types: a single string would be read letter by letter.\n if (!Array.isArray(entries as unknown)) {\n options.warn(\n `The devtools \"panels\" option must be a list, such as panels: [\"@warlock.js/grimoire/devtools\"]; got ${JSON.stringify(entries)}. No panel was added.`,\n );\n\n return [];\n }\n\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const mode = options.mode ?? \"development\";\n const taken = new Map<string, string>(options.taken ?? []);\n const panels: MountedDevtoolsPanel[] = [];\n\n for (const entry of entries) {\n let candidates: readonly unknown[];\n\n try {\n if (Array.isArray(entry as unknown)) {\n const problem = tupleProblem(entry as readonly unknown[]);\n\n if (problem !== undefined) {\n options.warn(\n `Devtools panels entry ${JSON.stringify(entry)} is invalid: ${problem}. Example: [\"@warlock.js/grimoire/devtools\", { ttlMs: 60000 }]. The entry was not added.`,\n );\n continue;\n }\n }\n\n if (typeof entry === \"string\" || Array.isArray(entry as unknown)) {\n const [specifier, panelOptions] =\n typeof entry === \"string\"\n ? [entry, undefined]\n : (entry as readonly [string, Record<string, unknown>]);\n const module = (await importModule(resolvePanelSpecifier(specifier, options.root))) as {\n default?: DevtoolsPanelExport;\n };\n\n if (module.default === undefined) {\n throw new Error(\"the module has no default export\");\n }\n\n candidates = await panelsOf(\n module.default,\n options.root,\n mode,\n panelOptions,\n options.errors,\n );\n } else {\n candidates = [entry];\n }\n } catch (error) {\n options.warn(\n `Devtools panel module \"${String(Array.isArray(entry as unknown) ? (entry as readonly unknown[])[0] : entry)}\" could not be loaded: ${describe(error)}. Check that it is installed and listed correctly in the devtools \"panels\" option.`,\n );\n continue;\n }\n\n for (const candidate of candidates) {\n try {\n panels.push(checkDevtoolsPanel(candidate, taken));\n } catch (error) {\n options.warn(`${describe(error)} The panel was not added.`);\n }\n }\n }\n\n return panels;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** What `productionPanels` decides. */\nexport type DevtoolsProductionPanels = {\n /** Built-in tab ids shown, in display order. */\n builtIn: string[];\n /** Package panels shown. */\n panels: MountedDevtoolsPanel[];\n};\n\n/**\n * Which tabs the production monitor shows. A built-in tab follows\n * `DEVTOOLS_BUILT_IN_PANELS` unless `overrides[id]` says otherwise. A package\n * panel (the Processes panel included) shows when it declares\n * `production: true` or `overrides[id]` is `true`; `overrides[id]: false` turns\n * any tab off.\n */\nexport function productionPanels(\n packagePanels: readonly MountedDevtoolsPanel[],\n overrides: Readonly<Record<string, boolean>> = {},\n): DevtoolsProductionPanels {\n const builtIn = DEVTOOLS_BUILT_IN_PANELS.filter((tab) => overrides[tab.id] ?? tab.production).map(\n (tab) => tab.id,\n );\n const panels = packagePanels.filter((panel) => overrides[panel.id] ?? panel.production);\n\n return { builtIn, panels };\n}\n\n/**\n * The tab list `GET api/panels` answers with: the built-in tabs in\n * `builtIn` (default: every one), in display order, then the package panels\n * in registration order.\n */\nexport function listPanelInfos(\n panels: readonly (Pick<MountedDevtoolsPanel, \"id\" | \"title\"> &\n Partial<Pick<MountedDevtoolsPanel, \"share\">>)[],\n builtIn?: readonly string[],\n): DevtoolsPanelInfo[] {\n const tabs: DevtoolsPanelInfo[] = DEVTOOLS_BUILT_IN_PANELS.filter(\n (tab) => builtIn === undefined || builtIn.includes(tab.id),\n ).map((tab) => ({\n id: tab.id,\n title: tab.title,\n type: \"built-in\" as const,\n shareable: false,\n }));\n\n for (const panel of panels) {\n tabs.push({\n id: panel.id,\n title: panel.title,\n type: \"package\" as const,\n shareable: panel.share !== undefined && panel.share !== null,\n });\n }\n\n return tabs;\n}\n","const MAX_DEPTH = 6;\n\n/**\n * A JSON-safe snapshot of a value devtools keeps for later display.\n *\n * Log contexts and phase attributes are app data: they can hold live objects\n * (a request, its socket) whose graphs are circular and which must not be kept\n * alive by the collector anyway. Plain objects and arrays are copied; anything\n * with a `toJSON()` is serialized through it; other class instances collapse\n * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to\n * `[Object]` / `[Array]`.\n */\nexport function toSafeValue(value: unknown): unknown {\n return snapshot(value, 0, new WeakSet());\n}\n\nfunction snapshot(value: unknown, depth: number, seen: WeakSet<object>): unknown {\n if (value === null || value === undefined) return value;\n\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"symbol\":\n return value.toString();\n case \"function\":\n return undefined;\n }\n\n const object = value as object;\n\n if (seen.has(object)) return \"[Circular]\";\n if (value instanceof Date)\n return Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n if (value instanceof Error) return { name: value.name, message: value.message };\n\n if (depth >= MAX_DEPTH) return Array.isArray(value) ? \"[Array]\" : \"[Object]\";\n\n seen.add(object);\n\n try {\n if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));\n\n const prototype = Object.getPrototypeOf(object);\n\n if (prototype !== Object.prototype && prototype !== null) {\n const toJSON = (object as { toJSON?: unknown }).toJSON;\n\n if (typeof toJSON === \"function\") {\n try {\n return snapshot(toJSON.call(object), depth + 1, seen);\n } catch {\n return `[${constructorName(object)}]`;\n }\n }\n\n return `[${constructorName(object)}]`;\n }\n\n const copy: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(object)) {\n const safe = snapshot(entry, depth + 1, seen);\n if (safe !== undefined) copy[key] = safe;\n }\n\n return copy;\n } finally {\n seen.delete(object);\n }\n}\n\nfunction constructorName(object: object): string {\n return (object as { constructor?: { name?: string } }).constructor?.name || \"Object\";\n}\n","import type { Trace, TraceSpan, TraceStoreContract } from \"@warlock.js/ai-panoptic\";\nimport { installedVersion } from \"../app-versions\";\nimport type { DevtoolsAiRunHelpers } from \"../ai/reports/runs\";\nimport type { DevtoolsAiTotalCost } from \"../ai/types\";\nimport type { DevtoolsAiUnavailableView } from \"../production/contracts\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsDisposer } from \"../types\";\n\nexport type DevtoolsAiUnavailableReason =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** Why the AI tab is empty, as sent to the dashboard: a title, one line and an optional command. */\nexport type DevtoolsAiUnavailable = {\n available: false;\n reason: DevtoolsAiUnavailableReason;\n title: string;\n message: string;\n command?: string;\n detail?: string;\n};\n\n/** Replaces absolute file paths in an error line with their package-relative part, or `<path>`. */\nexport function redactPaths(text: string): string {\n return text.replace(/(?:file:\\/\\/)?(?:[A-Za-z]:)?[\\\\/][^\\s'\"`()]*/g, (match) => {\n const normalized = match.replace(/^file:\\/\\//, \"\").replaceAll(\"\\\\\", \"/\");\n const index = normalized.lastIndexOf(\"node_modules/\");\n\n return index === -1 ? \"<path>\" : normalized.slice(index + \"node_modules/\".length);\n });\n}\n\nconst OBSERVATION_COMMAND = \"ai.config({ panoptic: { observeAll: true } })\";\n\n/** The answer for each reason; `detail` carries the load error and versions for `panoptic-failed`. */\nexport function describeAiUnavailable(\n reason: DevtoolsAiUnavailableReason,\n detail?: string,\n): DevtoolsAiUnavailable {\n switch (reason) {\n case \"ai-missing\":\n return {\n available: false,\n reason,\n title: \"AI isn't installed\",\n message: \"Add @warlock.js/ai to see AI runs here.\",\n command: \"warlock add ai\",\n };\n case \"panoptic-missing\":\n return {\n available: false,\n reason,\n title: \"Panoptic isn't installed\",\n message: \"Your app uses @warlock.js/ai. Add Panoptic to see its runs.\",\n command: \"warlock add ai-panoptic\",\n };\n case \"panoptic-failed\":\n return {\n available: false,\n reason,\n title: \"Panoptic could not be loaded\",\n message:\n \"Panoptic is installed but failed to load. Check that both packages share a version.\",\n detail,\n };\n case \"not-collected\":\n return {\n available: false,\n reason,\n title: \"AI runs are not collected here\",\n message:\n \"Production keeps hourly AI totals, not run details. Open Reports, Models or Errors here, or the Runs tab in development (warlock dev).\",\n };\n case \"table-missing\":\n return {\n available: false,\n reason,\n title: \"AI reports need their table\",\n message: \"Run the devtools migrations to create devtools_ai_rollups, then restart the app.\",\n command: \"warlock migrate\",\n };\n case \"reports-off\":\n return {\n available: false,\n reason,\n title: \"AI reports are off\",\n message:\n \"Set devtools.ai.reports to true in src/config/devtools.ts to keep hourly AI totals.\",\n };\n case \"observation-off\":\n return {\n available: false,\n reason,\n title: \"AI observation is off\",\n message: \"Turn it on in src/config/ai.ts, then restart warlock dev.\",\n command: OBSERVATION_COMMAND,\n };\n }\n}\n\n/** The unavailable answer as the AI routes send it: `command` and `detail` are `null` when absent. */\nexport function toAiUnavailableView(unavailable: DevtoolsAiUnavailable): DevtoolsAiUnavailableView {\n return {\n available: false,\n reason: unavailable.reason,\n title: unavailable.title,\n message: unavailable.message,\n command: unavailable.command ?? null,\n detail: unavailable.detail ?? null,\n };\n}\n\n/** Test seam: how packages are loaded and their versions read. */\nexport type AiSourceDeps = {\n load?: (name: string) => Promise<unknown>;\n version?: (name: string) => string | null;\n};\n\nexport type DevtoolsAiEvent = { traceId: string; requestId?: string };\n\n/** Only the connector's development branch constructs this source. */\nexport type DevtoolsAiSource =\n | (DevtoolsAiUnavailable & { dispose: DevtoolsDisposer })\n | {\n available: true;\n /** True when `@warlock.js/ai` has no `observeAll` and no registered observer (read per request). */\n observationOff?: () => boolean;\n /** Totals a trace's priced usage (Panoptic's `totalCostUsd`). */\n totalCost: DevtoolsAiTotalCost;\n /** Panoptic's trace filter, grouping and percentile helpers for the Runs list. */\n helpers: DevtoolsAiRunHelpers;\n store: TraceStoreContract;\n summarize: (trace: Trace) => DevtoolsAiRun;\n subscribe: (listener: (event: DevtoolsAiEvent) => void) => DevtoolsDisposer;\n dispose: DevtoolsDisposer;\n };\n\nexport type DevtoolsAiRun = {\n traceId: string;\n requestId?: string;\n sessionId?: string;\n name: string;\n status: TraceSpan[\"status\"];\n startedAt: string;\n duration: number;\n usage: Trace[\"usage\"];\n cost?: number;\n models: string[];\n toolCalls: number;\n retries: number;\n cacheHits?: number;\n incomplete: boolean;\n truncatedTrips: number;\n compactions: number;\n skippedCompactions: number;\n providerCompactions: number;\n};\n\n/** Summaries use root usage once: nested spans already roll up into it. */\nexport function summarizeAiTrace(trace: Trace, cost?: number): DevtoolsAiRun {\n const models = new Set<string>();\n let toolCalls = 0;\n let retries = 0;\n let cacheHits: number | undefined;\n let incomplete = false;\n let truncatedTrips = 0;\n let compactions = 0;\n let skippedCompactions = 0;\n let providerCompactions = 0;\n const visit = (span: TraceSpan): void => {\n const attributes = span.attributes ?? {};\n const model = attributes[\"agent.model.name\"];\n const provider = attributes[\"agent.model.provider\"];\n if (typeof model === \"string\")\n models.add(typeof provider === \"string\" ? `${provider}/${model}` : model);\n if (span.type === \"tool\") toolCalls += 1;\n if (typeof attributes.retries === \"number\") retries += attributes.retries;\n if (typeof attributes[\"agent.cacheHits\"] === \"number\")\n cacheHits = (cacheHits ?? 0) + attributes[\"agent.cacheHits\"];\n if (typeof attributes[\"agent.truncatedTrips\"] === \"number\")\n truncatedTrips += attributes[\"agent.truncatedTrips\"];\n if (typeof attributes[\"agent.providerCompactions\"] === \"number\")\n providerCompactions += attributes[\"agent.providerCompactions\"];\n if (Array.isArray(attributes[\"agent.compactions\"])) {\n const records: unknown[] = attributes[\"agent.compactions\"];\n for (const record of records) {\n if (typeof record !== \"object\" || record === null || !(\"type\" in record)) continue;\n if (record.type === \"applied\") compactions += 1;\n if (record.type === \"skipped\") skippedCompactions += 1;\n }\n }\n incomplete ||=\n span.status === \"incomplete\" ||\n span.error?.type === \"AgentIncompleteError\" ||\n span.error?.type === \"AGENT_INCOMPLETE\";\n span.children.forEach(visit);\n };\n visit(trace.root);\n return {\n traceId: trace.traceId,\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n name: trace.root.name,\n status: trace.root.status,\n startedAt: trace.startedAt,\n duration: trace.duration,\n usage: trace.usage,\n cost,\n models: [...models],\n toolCalls,\n retries,\n cacheHits,\n incomplete,\n truncatedTrips,\n compactions,\n skippedCompactions,\n providerCompactions,\n };\n}\n\n/** Content-free snapshot; never retain prompts, completions or tool arguments/results. */\nfunction snapshotSpan(span: TraceSpan): TraceSpan {\n return {\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n traceId: span.traceId,\n sessionId: span.sessionId,\n name: span.name,\n version: span.version,\n type: span.type,\n status: span.status,\n startedAt: span.startedAt,\n endedAt: span.endedAt,\n duration: span.duration,\n usage: structuredClone(span.usage),\n error: span.error ? { type: span.error.type, message: span.error.message } : undefined,\n attributes: toSafeValue(span.attributes) as Record<string, unknown> | undefined,\n children: span.children.map(snapshotSpan),\n };\n}\n\ntype PanopticModule = typeof import(\"@warlock.js/ai-panoptic\");\ntype AiCoreModule = { isObserveAll?: () => boolean; getObservers?: () => readonly unknown[] };\n\n/**\n * Loads Panoptic (required) and `@warlock.js/ai` (for the observation check)\n * lazily, or says why not. Shared by the development source and the AI\n * reports wiring, so both answer the same unavailable reasons.\n */\nexport async function loadAiPackages(\n deps: AiSourceDeps = {},\n): Promise<\n | { panoptic: PanopticModule; observationOff: () => boolean }\n | { unavailable: DevtoolsAiUnavailable }\n> {\n const aiPackage: string = \"@warlock.js/ai\"; // not a dependency of devtools: never resolved at build time\n const load =\n deps.load ??\n ((name: string) =>\n name === \"@warlock.js/ai-panoptic\" ? import(\"@warlock.js/ai-panoptic\") : import(aiPackage));\n const version =\n deps.version ?? ((name: string) => installedVersion(name, process.cwd(), import.meta.resolve));\n let panoptic: PanopticModule;\n try {\n panoptic = (await load(\"@warlock.js/ai-panoptic\")) as PanopticModule;\n if (typeof panoptic.subscribeTraces !== \"function\")\n throw new Error(\"Trace subscription unavailable\");\n } catch (error) {\n const aiVersion = version(\"@warlock.js/ai\");\n const panopticVersion = version(\"@warlock.js/ai-panoptic\");\n if (aiVersion === null) return { unavailable: describeAiUnavailable(\"ai-missing\") };\n if (panopticVersion === null) return { unavailable: describeAiUnavailable(\"panoptic-missing\") };\n const text = redactPaths(\n (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0] ?? \"\",\n ).slice(0, 300);\n return {\n unavailable: describeAiUnavailable(\n \"panoptic-failed\",\n `${text} (@warlock.js/ai ${aiVersion}, @warlock.js/ai-panoptic ${panopticVersion})`,\n ),\n };\n }\n\n let core: AiCoreModule | undefined;\n try {\n core = (await load(\"@warlock.js/ai\")) as AiCoreModule;\n } catch {\n core = undefined;\n }\n const observationOff = (): boolean =>\n typeof core?.isObserveAll === \"function\" &&\n typeof core.getObservers === \"function\" &&\n !core.isObserveAll() &&\n core.getObservers().length === 0;\n\n return { panoptic, observationOff };\n}\n\n/**\n * Optional, lazy integration. Retains only traces collected after devtools boots,\n * using Panoptic's bounded query store; existing exporter/cache stores stay independent.\n */\nexport async function attachAiSource(\n capacity: number,\n deps: AiSourceDeps = {},\n): Promise<DevtoolsAiSource> {\n const loaded = await loadAiPackages(deps);\n if (\"unavailable\" in loaded) return { ...loaded.unavailable, dispose() {} };\n const { panoptic, observationOff } = loaded;\n\n const { currentRequestId } = await import(\"../current-request-id\");\n const store = panoptic.createInMemoryTraceStore({ capacity });\n const listeners = new Set<(event: DevtoolsAiEvent) => void>();\n const detach = panoptic.subscribeTraces((trace) => {\n // Read ALS before any asynchronous exporter work, including for runs that\n // finish after the HTTP response. Never use sessionId as a request id.\n const requestId = currentRequestId() ?? trace.requestId;\n store.add({\n ...trace,\n requestId,\n usage: structuredClone(trace.usage),\n root: snapshotSpan(trace.root),\n });\n for (const listener of listeners) {\n try {\n listener({ traceId: trace.traceId, requestId });\n } catch {\n /* isolate clients */\n }\n }\n });\n\n return {\n available: true,\n observationOff,\n totalCost: (usage) => panoptic.totalCostUsd(usage),\n helpers: {\n filterTraces: panoptic.filterTraces,\n groupBySession: panoptic.groupBySession,\n groupByPrompt: panoptic.groupByPrompt,\n groupByType: panoptic.groupByType,\n percentile: panoptic.percentile,\n tracePromptKey: panoptic.tracePromptKey,\n },\n store,\n summarize: (trace) => summarizeAiTrace(trace, panoptic.totalCostUsd(trace.usage)),\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n detach();\n listeners.clear();\n store.clear();\n },\n };\n}\n","import {\n DEVTOOLS_AI_ERROR_CATEGORIES,\n type DevtoolsAiErrorCategory,\n} from \"../../production/contracts\";\nimport type { DevtoolsAiErrorCounts } from \"../types\";\n\n/** Labels the Errors page shows, by category. */\nexport const DEVTOOLS_AI_ERROR_LABELS: Readonly<Record<DevtoolsAiErrorCategory, string>> = {\n \"rate-limit\": \"Rate limit\",\n timeout: \"Timeout\",\n refusal: \"Refusal\",\n provider: \"Provider error\",\n budget: \"Budget\",\n tool: \"Tool failed\",\n schema: \"Invalid output\",\n incomplete: \"Incomplete\",\n other: \"Other\",\n};\n\n/** Error counts with every category at 0. */\nexport function emptyErrorCounts(): DevtoolsAiErrorCounts {\n const counts = {} as DevtoolsAiErrorCounts;\n\n for (const category of DEVTOOLS_AI_ERROR_CATEGORIES) counts[category] = 0;\n\n return counts;\n}\n\nconst CODE_CATEGORIES: Readonly<Record<string, DevtoolsAiErrorCategory>> = {\n PROVIDER_RATE_LIMIT: \"rate-limit\",\n PROVIDER_QUOTA_EXCEEDED: \"rate-limit\",\n PROVIDER_OVERLOADED: \"rate-limit\",\n PROVIDER_TIMEOUT: \"timeout\",\n CONTENT_FILTER: \"refusal\",\n GUARDRAIL_VIOLATION: \"refusal\",\n PROVIDER_ERROR: \"provider\",\n PROVIDER_INVALID_REQUEST: \"provider\",\n PROVIDER_AUTH: \"provider\",\n CONTEXT_LENGTH_EXCEEDED: \"provider\",\n PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH: \"provider\",\n BUDGET_EXCEEDED: \"budget\",\n TOOL_EXEC_FAILED: \"tool\",\n SCHEMA_VALIDATION_FAILED: \"schema\",\n AGENT_INCOMPLETE: \"incomplete\",\n AGENT_MAX_TRIPS: \"incomplete\",\n AgentIncompleteError: \"incomplete\",\n};\n\n/**\n * The category of a failed or stopped agent span, from its status and error\n * type (an `AIErrorCode` such as `PROVIDER_RATE_LIMIT`, or an error name):\n *\n * - `rate-limit`: PROVIDER_RATE_LIMIT, PROVIDER_QUOTA_EXCEEDED, PROVIDER_OVERLOADED\n * - `timeout`: PROVIDER_TIMEOUT, or a name/type containing \"Timeout\"\n * - `refusal`: CONTENT_FILTER, GUARDRAIL_VIOLATION\n * - `provider`: PROVIDER_ERROR, PROVIDER_INVALID_REQUEST, PROVIDER_AUTH,\n * CONTEXT_LENGTH_EXCEEDED, PROVIDER_EMBEDDING_VECTOR_COUNT_MISMATCH\n * - `budget`: BUDGET_EXCEEDED\n * - `tool`: TOOL_EXEC_FAILED\n * - `schema`: SCHEMA_VALIDATION_FAILED\n * - `incomplete`: status `incomplete` or `max-iterations`, AGENT_INCOMPLETE,\n * AGENT_MAX_TRIPS, AgentIncompleteError\n * - `other`: anything else\n */\nexport function classifyAiError(\n status: string,\n errorType: string | undefined,\n): DevtoolsAiErrorCategory {\n if (status === \"incomplete\" || status === \"max-iterations\") return \"incomplete\";\n\n if (!errorType) return \"other\";\n\n const known = CODE_CATEGORIES[errorType];\n\n if (known) return known;\n\n return /timeout/i.test(errorType) ? \"timeout\" : \"other\";\n}\n","import { DEVTOOLS_AI_LATENCY_BUCKETS_MS } from \"../../production/contracts\";\n\n/**\n * Latency histograms over `DEVTOOLS_AI_LATENCY_BUCKETS_MS`, stored as plain\n * count arrays in the rollups (one more count than bounds).\n */\n\nconst BUCKETS = DEVTOOLS_AI_LATENCY_BUCKETS_MS;\n\n/** `DEVTOOLS_AI_LATENCY_BUCKETS_MS.length + 1` zeros. */\nexport function emptyAiLatency(): number[] {\n return new Array<number>(BUCKETS.length + 1).fill(0);\n}\n\n/** The bucket index of a duration; a negative or non-finite value counts as 0. */\nexport function aiLatencyBucket(durationMs: number): number {\n if (!Number.isFinite(durationMs) || durationMs < 0) return 0;\n\n const index = BUCKETS.findIndex((bound) => durationMs <= bound);\n\n return index === -1 ? BUCKETS.length : index;\n}\n\n/** Adds `source` into `target` in place (same length). */\nexport function addAiLatency(target: number[], source: readonly number[]): void {\n for (let index = 0; index < target.length; index++) {\n target[index] = (target[index] ?? 0) + (source[index] ?? 0);\n }\n}\n\n/**\n * The `q` quantile (0–1): the upper bound of the bucket that holds it, or the\n * last bound for the overflow bucket. `null` for an empty histogram.\n */\nexport function aiLatencyQuantile(counts: readonly number[], q: number): number | null {\n let total = 0;\n\n for (const count of counts) total += count;\n\n if (total <= 0) return null;\n\n const target = Math.max(1, Math.ceil(Math.min(1, Math.max(0, q)) * total));\n let seen = 0;\n\n for (let index = 0; index < counts.length; index++) {\n seen += counts[index] ?? 0;\n\n if (seen >= target) return BUCKETS[Math.min(index, BUCKETS.length - 1)] ?? null;\n }\n\n return BUCKETS[BUCKETS.length - 1] ?? null;\n}\n","import { createHash } from \"node:crypto\";\nimport type { Trace } from \"@warlock.js/ai-panoptic\";\nimport type { DevtoolsAiRollupDelta, DevtoolsAiTotalCost } from \"../types\";\nimport { classifyAiError, emptyErrorCounts } from \"./categories\";\nimport { addAiLatency, aiLatencyBucket, emptyAiLatency } from \"./histogram\";\n\ntype Span = Trace[\"root\"];\ntype RollupKey = { hour: number; agent: string; model: string; provider: string };\n\nconst HOUR_MS = 3_600_000;\nconst UNKNOWN = \"(unknown)\";\nconst MODEL_SPAN_TYPES: ReadonlySet<string> = new Set([\n \"agent\",\n \"image\",\n \"speech\",\n \"transcription\",\n]);\n\n/** Token counts with `input` normalised to the whole prompt. */\ntype Tokens = {\n input: number;\n output: number;\n cached: number;\n cacheWrite: number;\n reasoning: number;\n};\n\nfunction count(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction normalise(usage: Span[\"usage\"] | undefined): Tokens {\n const cached = count(usage?.cachedTokens);\n const cacheWrite = count(usage?.cacheWriteTokens);\n const input = count(usage?.input);\n\n return {\n input: usage?.inputIncludesCache === false ? input + cached + cacheWrite : input,\n output: count(usage?.output),\n cached,\n cacheWrite,\n reasoning: count(usage?.reasoningTokens),\n };\n}\n\nfunction subtract(own: Tokens, other: Tokens): void {\n own.input = Math.max(0, own.input - other.input);\n own.output = Math.max(0, own.output - other.output);\n own.cached = Math.max(0, own.cached - other.cached);\n own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);\n own.reasoning = Math.max(0, own.reasoning - other.reasoning);\n}\n\n/** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */\nexport function isAiModelSpan(span: Span): boolean {\n return (\n typeof span.attributes?.[\"agent.model.name\"] === \"string\" || MODEL_SPAN_TYPES.has(span.type)\n );\n}\n\n/** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */\nfunction nearestModelSpans(span: Span): Span[] {\n const found: Span[] = [];\n\n for (const child of span.children ?? []) {\n if (isAiModelSpan(child)) found.push(child);\n else found.push(...nearestModelSpans(child));\n }\n\n return found;\n}\n\nfunction cut(value: unknown, max: number): string {\n if (typeof value !== \"string\" || value === \"\") return UNKNOWN;\n\n return value.length > max ? value.slice(0, max) : value;\n}\n\nfunction spanCost(span: Span, totalCost: DevtoolsAiTotalCost): number {\n return count(totalCost(span.usage));\n}\n\n/** Whether a span's usage carries pricing at all (a free model is priced at 0; no pricing is `undefined`). */\nfunction hasPricing(span: Span, totalCost: DevtoolsAiTotalCost): boolean {\n return typeof totalCost(span.usage) === \"number\";\n}\n\nfunction buildDelta(\n key: RollupKey,\n status: string,\n errorType: string | undefined,\n tokens: Tokens,\n cost: number,\n /** The own usage is priced even when `cost` is 0 (a model priced as free). */\n pricedAtZero = false,\n): DevtoolsAiRollupDelta {\n const delta = emptyRollupDelta(key);\n\n delta.runs = 1;\n delta.inputTokens = tokens.input;\n delta.outputTokens = tokens.output;\n delta.cachedTokens = tokens.cached;\n delta.cacheWriteTokens = tokens.cacheWrite;\n delta.reasoningTokens = tokens.reasoning;\n\n if (status === \"completed\") delta.completed = 1;\n else if (status === \"failed\") delta.failed = 1;\n else if (status === \"incomplete\" || status === \"max-iterations\") delta.incomplete = 1;\n else if (status === \"cancelled\") delta.cancelled = 1;\n\n if (status === \"failed\" || status === \"incomplete\" || status === \"max-iterations\") {\n delta.errors[classifyAiError(status, errorType)] = 1;\n }\n\n if (cost > 0 || (pricedAtZero && tokens.input + tokens.output > 0)) {\n delta.costUsd = cost;\n delta.pricedRuns = 1;\n } else if (tokens.input + tokens.output > 0) {\n delta.unpricedRuns = 1;\n delta.unpricedTokens = tokens.input + tokens.output;\n }\n\n return delta;\n}\n\n/**\n * Turns one finished Panoptic trace into rollup deltas, one per\n * model-bearing span (a span with an `agent.model.name` attribute, or of type\n * `agent`, `image`, `speech` or `transcription`), keyed by the hour of the\n * span's `endedAt`.\n *\n * Each span counts its OWN usage and cost: its rolled-up `usage` minus the\n * usage of its nearest model-bearing descendants (an agent used as a tool is\n * counted once, as itself). Root usage left after subtracting every\n * model-bearing span (a custom flow with no agent span) becomes one more delta\n * for the root name with model `(unknown)`, counted as one run.\n *\n * Per span: status maps to completed / failed / incomplete (`incomplete`,\n * `max-iterations`) / cancelled; failed and incomplete runs add one error to\n * `classifyAiError(status, error.type)`; tokens are normalised so `input`\n * includes cache reads and writes; `costUsd` is `totalCost` of the own usage\n * when it is above 0 (or the span's model is priced as free), otherwise a run\n * with tokens counts in `unpricedRuns` and `unpricedTokens`; `agent.fallbackTrips > 0` adds a fallback run;\n * `agent.refusals > 0` or a CONTENT_FILTER error adds a refusal; the span's\n * `duration` goes into the latency histogram.\n *\n * Pure: no clock, no I/O. Names are cut to 200 (provider 100) characters.\n */\nexport function traceToRollupDeltas(\n trace: Trace,\n totalCost: DevtoolsAiTotalCost,\n): DevtoolsAiRollupDelta[] {\n const root = trace.root;\n\n if (!root) return [];\n\n // A span without a readable end falls back to the root's end, then the trace's; no end at all skips the trace.\n const rootEnd = Date.parse(root.endedAt);\n const fallbackEnd = Number.isNaN(rootEnd) ? Date.parse(trace.endedAt) : rootEnd;\n\n if (Number.isNaN(fallbackEnd)) return [];\n\n const hourOf = (span: Span): number => {\n const ended = Date.parse(span.endedAt);\n const at = Number.isNaN(ended) ? fallbackEnd : ended;\n\n return Math.floor(at / HOUR_MS) * HOUR_MS;\n };\n\n const deltas: DevtoolsAiRollupDelta[] = [];\n const topLevel: Span[] = isAiModelSpan(root) ? [root] : nearestModelSpans(root);\n\n const visit = (span: Span): void => {\n const tokens = normalise(span.usage);\n let cost = spanCost(span, totalCost);\n const inner = nearestModelSpans(span);\n\n for (const child of inner) {\n subtract(tokens, normalise(child.usage));\n cost -= spanCost(child, totalCost);\n }\n\n cost = Math.max(0, cost);\n\n // Priced at zero only when the span's own pricing is known: none of the nested model spans carry a cost.\n const pricedAtZero =\n hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));\n\n const attributes = span.attributes ?? {};\n const key: RollupKey = { hour: hourOf(span), ...aiRollupNamesOf(span) };\n const delta = buildDelta(key, span.status, span.error?.type, tokens, cost, pricedAtZero);\n\n if (count(attributes[\"agent.fallbackTrips\"]) > 0) delta.fallbackRuns = 1;\n\n if (count(attributes[\"agent.refusals\"]) > 0 || span.error?.type === \"CONTENT_FILTER\") {\n delta.refusals = 1;\n }\n\n const duration = count(span.duration);\n\n const bucket = aiLatencyBucket(duration);\n\n delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;\n delta.latencyCount = 1;\n delta.latencySumMs = Math.max(0, duration);\n\n deltas.push(delta);\n\n for (const child of inner) visit(child);\n };\n\n // Only the real model-bearing roots start the walk; `visit` handles nesting.\n for (const span of topLevel) visit(span);\n\n const leftover = normalise(root.usage);\n let leftoverCost = spanCost(root, totalCost);\n\n for (const span of topLevel) {\n subtract(leftover, normalise(span.usage));\n leftoverCost -= spanCost(span, totalCost);\n }\n\n if (leftover.input + leftover.output > 0) {\n deltas.push(\n buildDelta(\n { hour: hourOf(root), agent: cut(root.name, 200), model: UNKNOWN, provider: UNKNOWN },\n root.status,\n root.error?.type,\n leftover,\n Math.max(0, leftoverCost),\n ),\n );\n }\n\n return deltas;\n}\n\n/** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */\nexport function aiRollupNamesOf(span: Span): { agent: string; model: string; provider: string } {\n return {\n agent: cut(span.name, 200),\n model: cut(span.attributes?.[\"agent.model.name\"], 200),\n provider: cut(span.attributes?.[\"agent.model.provider\"], 100),\n };\n}\n\n/** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */\nexport function rollupId(key: RollupKey): string {\n return createHash(\"sha256\")\n .update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`)\n .digest(\"hex\")\n .slice(0, 40);\n}\n\n/** A delta with every counter at zero for `key`. */\nexport function emptyRollupDelta(key: RollupKey): DevtoolsAiRollupDelta {\n return {\n hour: key.hour,\n agent: key.agent,\n model: key.model,\n provider: key.provider,\n runs: 0,\n completed: 0,\n failed: 0,\n incomplete: 0,\n cancelled: 0,\n inputTokens: 0,\n outputTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n reasoningTokens: 0,\n costUsd: 0,\n pricedRuns: 0,\n unpricedRuns: 0,\n unpricedTokens: 0,\n fallbackRuns: 0,\n refusals: 0,\n errors: emptyErrorCounts(),\n latency: emptyAiLatency(),\n latencyCount: 0,\n latencySumMs: 0,\n };\n}\n\nconst NUMERIC_COUNTERS = [\n \"runs\",\n \"completed\",\n \"failed\",\n \"incomplete\",\n \"cancelled\",\n \"inputTokens\",\n \"outputTokens\",\n \"cachedTokens\",\n \"cacheWriteTokens\",\n \"reasoningTokens\",\n \"costUsd\",\n \"pricedRuns\",\n \"unpricedRuns\",\n \"unpricedTokens\",\n \"fallbackRuns\",\n \"refusals\",\n \"latencyCount\",\n \"latencySumMs\",\n] as const;\n\n/** Adds the counters of `source` into `target` in place (keys must match). */\nexport function addRollupCounters(\n target: DevtoolsAiRollupDelta,\n source: DevtoolsAiRollupDelta,\n): void {\n for (const field of NUMERIC_COUNTERS) target[field] += source[field];\n\n for (const category of Object.keys(target.errors) as (keyof typeof target.errors)[]) {\n target.errors[category] += source.errors[category] ?? 0;\n }\n\n addAiLatency(target.latency, source.latency);\n}\n"],"mappings":";;;;;;;;;;;AAoDA,MAAa,gCAAmD;CAC9D;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAQ;CAAO;AAAM,CAAC;;;;;AAMhF,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,WAAW;AACjB,MAAM,aAAa;AACnB,MAAM,0BAAU,IAAI,IAAyB;CAAC;CAAO;CAAQ;CAAO;CAAS;AAAQ,CAAC;;AAGtF,MAAM,gBAAwC;CAC5C,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;C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AAiB;EACzB,SAAS,eAAe;EACxB,cAAc;EACd,cAAc;CAChB;AACF;AAEA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,kBACd,QACA,QACM;CACN,KAAK,MAAM,SAAS,kBAAkB,OAAO,UAAU,OAAO;CAE9D,KAAK,MAAM,YAAY,OAAO,KAAK,OAAO,MAAM,GAC9C,OAAO,OAAO,aAAa,OAAO,OAAO,aAAa;CAGxD,aAAa,OAAO,SAAS,OAAO,OAAO;AAC7C"}
@@ -1,102 +0,0 @@
1
- const require_errors = require("./errors-DNQ-g49I.cjs");
2
- let node_crypto = require("node:crypto");
3
-
4
- //#region ../../packages/devtools/src/production/stats/histogram.ts
5
- /** An empty histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */
6
- function createHistogram() {
7
- return {
8
- counts: new Array(require_errors.DEVTOOLS_LATENCY_BUCKETS_MS.length + 1).fill(0),
9
- count: 0,
10
- sumMs: 0,
11
- maxMs: 0
12
- };
13
- }
14
- /** The bucket index a duration falls in. */
15
- function bucketIndex(durationMs) {
16
- for (let index = 0; index < require_errors.DEVTOOLS_LATENCY_BUCKETS_MS.length; index++) if (durationMs <= require_errors.DEVTOOLS_LATENCY_BUCKETS_MS[index]) return index;
17
- return require_errors.DEVTOOLS_LATENCY_BUCKETS_MS.length;
18
- }
19
- /** Adds one duration to `histogram` in place. A negative or non-finite value counts as 0. */
20
- function recordDuration(histogram, durationMs) {
21
- const value = Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;
22
- const index = bucketIndex(value);
23
- histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;
24
- histogram.count += 1;
25
- histogram.sumMs += value;
26
- if (value > histogram.maxMs) histogram.maxMs = value;
27
- }
28
- /** The sum of several histograms (exact: they share the bucket bounds). */
29
- function mergeHistograms(histograms) {
30
- const merged = createHistogram();
31
- for (const histogram of histograms) {
32
- for (let index = 0; index < merged.counts.length; index++) merged.counts[index] = (merged.counts[index] ?? 0) + (histogram.counts[index] ?? 0);
33
- merged.count += histogram.count;
34
- merged.sumMs += histogram.sumMs;
35
- if (histogram.maxMs > merged.maxMs) merged.maxMs = histogram.maxMs;
36
- }
37
- return merged;
38
- }
39
- /**
40
- * The `q` quantile (0–1) of a histogram: the upper bound of the bucket that
41
- * holds it, capped at the largest value seen. 0 for an empty histogram.
42
- */
43
- function histogramQuantile(histogram, q) {
44
- if (histogram.count === 0) return 0;
45
- const rank = Math.max(1, Math.ceil(Math.min(Math.max(q, 0), 1) * histogram.count));
46
- let seen = 0;
47
- for (let index = 0; index < histogram.counts.length; index++) {
48
- seen += histogram.counts[index] ?? 0;
49
- if (seen >= rank) {
50
- const bound = require_errors.DEVTOOLS_LATENCY_BUCKETS_MS[index];
51
- return bound === void 0 ? histogram.maxMs : Math.min(bound, histogram.maxMs);
52
- }
53
- }
54
- return histogram.maxMs;
55
- }
56
- /** The mean duration, 0 for an empty histogram. */
57
- function histogramMean(histogram) {
58
- return histogram.count === 0 ? 0 : histogram.sumMs / histogram.count;
59
- }
60
- /** The first 16 hex characters of SHA-256: the id of a query shape or an error fingerprint. */
61
- function shortId(value) {
62
- return (0, node_crypto.createHash)("sha256").update(value).digest("hex").slice(0, 16);
63
- }
64
-
65
- //#endregion
66
- Object.defineProperty(exports, "createHistogram", {
67
- enumerable: true,
68
- get: function () {
69
- return createHistogram;
70
- }
71
- });
72
- Object.defineProperty(exports, "histogramMean", {
73
- enumerable: true,
74
- get: function () {
75
- return histogramMean;
76
- }
77
- });
78
- Object.defineProperty(exports, "histogramQuantile", {
79
- enumerable: true,
80
- get: function () {
81
- return histogramQuantile;
82
- }
83
- });
84
- Object.defineProperty(exports, "mergeHistograms", {
85
- enumerable: true,
86
- get: function () {
87
- return mergeHistograms;
88
- }
89
- });
90
- Object.defineProperty(exports, "recordDuration", {
91
- enumerable: true,
92
- get: function () {
93
- return recordDuration;
94
- }
95
- });
96
- Object.defineProperty(exports, "shortId", {
97
- enumerable: true,
98
- get: function () {
99
- return shortId;
100
- }
101
- });
102
- //# sourceMappingURL=histogram-CkoVizdf.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"histogram-CkoVizdf.cjs","names":["DEVTOOLS_LATENCY_BUCKETS_MS","createHash"],"sources":["../../../../../../../packages/devtools/src/production/stats/histogram.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { DEVTOOLS_LATENCY_BUCKETS_MS, type DevtoolsHistogram } from \"../contracts\";\n\n/** An empty histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport function createHistogram(): DevtoolsHistogram {\n return {\n counts: new Array<number>(DEVTOOLS_LATENCY_BUCKETS_MS.length + 1).fill(0),\n count: 0,\n sumMs: 0,\n maxMs: 0,\n };\n}\n\n/** The bucket index a duration falls in. */\nexport function bucketIndex(durationMs: number): number {\n for (let index = 0; index < DEVTOOLS_LATENCY_BUCKETS_MS.length; index++) {\n if (durationMs <= (DEVTOOLS_LATENCY_BUCKETS_MS[index] as number)) return index;\n }\n\n return DEVTOOLS_LATENCY_BUCKETS_MS.length;\n}\n\n/** Adds one duration to `histogram` in place. A negative or non-finite value counts as 0. */\nexport function recordDuration(histogram: DevtoolsHistogram, durationMs: number): void {\n const value = Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;\n const index = bucketIndex(value);\n\n histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;\n histogram.count += 1;\n histogram.sumMs += value;\n\n if (value > histogram.maxMs) histogram.maxMs = value;\n}\n\n/** The sum of several histograms (exact: they share the bucket bounds). */\nexport function mergeHistograms(histograms: readonly DevtoolsHistogram[]): DevtoolsHistogram {\n const merged = createHistogram();\n\n for (const histogram of histograms) {\n for (let index = 0; index < merged.counts.length; index++) {\n merged.counts[index] = (merged.counts[index] ?? 0) + (histogram.counts[index] ?? 0);\n }\n\n merged.count += histogram.count;\n merged.sumMs += histogram.sumMs;\n\n if (histogram.maxMs > merged.maxMs) merged.maxMs = histogram.maxMs;\n }\n\n return merged;\n}\n\n/**\n * The `q` quantile (0–1) of a histogram: the upper bound of the bucket that\n * holds it, capped at the largest value seen. 0 for an empty histogram.\n */\nexport function histogramQuantile(histogram: DevtoolsHistogram, q: number): number {\n if (histogram.count === 0) return 0;\n\n const rank = Math.max(1, Math.ceil(Math.min(Math.max(q, 0), 1) * histogram.count));\n let seen = 0;\n\n for (let index = 0; index < histogram.counts.length; index++) {\n seen += histogram.counts[index] ?? 0;\n\n if (seen >= rank) {\n const bound = DEVTOOLS_LATENCY_BUCKETS_MS[index];\n\n return bound === undefined ? histogram.maxMs : Math.min(bound, histogram.maxMs);\n }\n }\n\n return histogram.maxMs;\n}\n\n/** The mean duration, 0 for an empty histogram. */\nexport function histogramMean(histogram: DevtoolsHistogram): number {\n return histogram.count === 0 ? 0 : histogram.sumMs / histogram.count;\n}\n\n/** The first 16 hex characters of SHA-256: the id of a query shape or an error fingerprint. */\nexport function shortId(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 16);\n}\n"],"mappings":";;;;;AAIA,SAAgB,kBAAqC;CACnD,OAAO;EACL,QAAQ,IAAI,MAAcA,2CAA4B,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;EACxE,OAAO;EACP,OAAO;EACP,OAAO;CACT;AACF;;AAGA,SAAgB,YAAY,YAA4B;CACtD,KAAK,IAAI,QAAQ,GAAG,QAAQA,2CAA4B,QAAQ,SAC9D,IAAI,cAAeA,2CAA4B,QAAmB,OAAO;CAG3E,OAAOA,2CAA4B;AACrC;;AAGA,SAAgB,eAAe,WAA8B,YAA0B;CACrF,MAAM,QAAQ,OAAO,SAAS,UAAU,KAAK,aAAa,IAAI,aAAa;CAC3E,MAAM,QAAQ,YAAY,KAAK;CAE/B,UAAU,OAAO,UAAU,UAAU,OAAO,UAAU,KAAK;CAC3D,UAAU,SAAS;CACnB,UAAU,SAAS;CAEnB,IAAI,QAAQ,UAA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T_TYPES","generateToken","hashToken","panelContentType","sendPanelFile","createHash","DevtoolsApiError","ipMatches","createErrorRef","DEVTOOLS_ERROR_MESSAGES","listPanelInfos","createHash"],"sources":["../../../../../../../packages/devtools/src/production/http/access.ts","../../../../../../../packages/devtools/src/production/http/client.ts","../../../../../../../packages/devtools/src/production/http/constants.ts","../../../../../../../packages/devtools/src/production/http/context.ts","../../../../../../../packages/devtools/src/production/http/cookie.ts","../../../../../../../packages/devtools/src/production/http/auth-routes.ts","../../../../../../../packages/devtools/src/production/http/headers.ts","../../../../../../../packages/devtools/src/production/http/share-session.ts","../../../../../../../packages/devtools/src/production/http/share.ts","../../../../../../../packages/devtools/src/production/http/mount.ts","../../../../../../../packages/devtools/src/production/http/state.ts"],"sourcesContent":["import type { DevtoolsRouteAccess, DevtoolsRouteAccessRule } from \"./types\";\n\ntype Method = DevtoolsRouteAccessRule[\"method\"];\n\nconst PUBLIC: DevtoolsRouteAccess = { type: \"public\" };\nconst VIEWER: DevtoolsRouteAccess = { type: \"viewer\" };\nconst ADMIN: DevtoolsRouteAccess = { type: \"admin\" };\nconst SHARE: DevtoolsRouteAccess = { type: \"share\" };\n\nconst pending = (...stages: Extract<DevtoolsRouteAccess, { type: \"pending\" }>[\"stages\"]) =>\n ({ type: \"pending\", stages }) satisfies DevtoolsRouteAccess;\n\nconst ALL_STEPS = [\"password-change\", \"mfa-enrol\", \"mfa-verify\"] as const;\n\n/**\n * The access table: every production route, its method and who may call it.\n * A route with no entry is `admin` (fail closed). A package panel `<id>`\n * gets `GET /api/<id>` and `GET /api/<id>/*` for viewers and every other\n * method there for admins, audited as `panel.action`; a url ending in `/*`\n * matches every pattern below it. The share routes exist only when\n * `options.share` is `true` (`production.share.enabled`).\n */\nexport function productionRouteAccess(\n panelIds: readonly string[],\n options: { share?: boolean } = {},\n): DevtoolsRouteAccessRule[] {\n const rule = (\n method: Method,\n url: string,\n access: DevtoolsRouteAccess,\n audit?: DevtoolsRouteAccessRule[\"audit\"],\n ): DevtoolsRouteAccessRule => ({ method, url, access, ...(audit ? { audit } : {}) });\n\n const rules: DevtoolsRouteAccessRule[] = [\n // The shell and its sign-in steps.\n rule(\"GET\", \"/\", PUBLIC),\n rule(\"GET\", \"/assets/:name\", PUBLIC),\n rule(\"GET\", \"/api/auth/session\", PUBLIC),\n rule(\"POST\", \"/api/auth/login\", PUBLIC),\n rule(\"POST\", \"/api/auth/setup\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/inspect\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/accept\", PUBLIC),\n rule(\"POST\", \"/api/auth/password\", pending(\"password-change\")),\n rule(\"POST\", \"/api/auth/totp/start\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/totp/confirm\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/passkey/options\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/passkey/verify\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/mfa\", pending(\"mfa-verify\")),\n rule(\"POST\", \"/api/auth/logout\", pending(...ALL_STEPS)),\n\n // The signed-in account.\n rule(\"GET\", \"/api/panels\", VIEWER),\n rule(\"GET\", \"/api/account\", VIEWER),\n rule(\"GET\", \"/api/account/sessions\", VIEWER),\n rule(\"DELETE\", \"/api/account/sessions/:id\", VIEWER),\n rule(\"POST\", \"/api/account/password\", VIEWER),\n rule(\"POST\", \"/api/account/totp/start\", VIEWER),\n rule(\"POST\", \"/api/account/totp/confirm\", VIEWER),\n rule(\"DELETE\", \"/api/account/totp\", VIEWER),\n rule(\"POST\", \"/api/account/recovery-codes\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/options\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/verify\", VIEWER),\n rule(\"DELETE\", \"/api/account/passkeys/:id\", VIEWER),\n\n // Administration.\n rule(\"GET\", \"/api/admin/users\", ADMIN),\n rule(\"POST\", \"/api/admin/invites\", ADMIN),\n rule(\"DELETE\", \"/api/admin/invites/:id\", ADMIN),\n rule(\"PATCH\", \"/api/admin/users/:id\", ADMIN),\n rule(\"DELETE\", \"/api/admin/users/:id\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/reset-mfa\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/sign-out\", ADMIN),\n rule(\"GET\", \"/api/admin/audit\", ADMIN),\n rule(\"POST\", \"/api/admin/disable\", ADMIN),\n\n // Data.\n rule(\"GET\", \"/api/stream\", VIEWER),\n rule(\"GET\", \"/api/instances\", VIEWER),\n rule(\"GET\", \"/api/resources\", VIEWER),\n rule(\"GET\", \"/api/queries/stats\", VIEWER),\n rule(\"GET\", \"/api/routes/stats\", VIEWER),\n rule(\"GET\", \"/api/health\", VIEWER),\n rule(\"GET\", \"/api/errors\", VIEWER),\n rule(\"GET\", \"/api/jobs\", VIEWER),\n rule(\"GET\", \"/api/logs\", VIEWER),\n rule(\"GET\", \"/api/requests\", VIEWER),\n rule(\"GET\", \"/api/requests/:id\", VIEWER),\n rule(\"GET\", \"/api/requests/:id/curl\", VIEWER),\n rule(\"DELETE\", \"/api/requests\", ADMIN, \"requests.cleared\"),\n rule(\"POST\", \"/api/queries/:shapeId/explain\", ADMIN, \"explain.run\"),\n rule(\"GET\", \"/api/routes\", VIEWER),\n rule(\"GET\", \"/panels/:id/:name\", VIEWER),\n rule(\"GET\", \"/panels/:id/files/*\", VIEWER),\n\n // Tabs that are off unless the project turns them on.\n rule(\"GET\", \"/api/mails\", VIEWER),\n rule(\"GET\", \"/api/mails/:id\", VIEWER),\n rule(\"GET\", \"/api/mails/:id/html\", VIEWER),\n rule(\"GET\", \"/api/ai\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs/:id\", VIEWER),\n rule(\"GET\", \"/api/ai/runs/:id\", VIEWER),\n rule(\"GET\", \"/api/ai/runs\", VIEWER),\n rule(\"GET\", \"/api/ai/reports\", VIEWER),\n rule(\"GET\", \"/api/ai/models\", VIEWER),\n rule(\"GET\", \"/api/ai/errors\", VIEWER),\n rule(\"GET\", \"/api/ai/evaluate\", VIEWER),\n rule(\"POST\", \"/api/ai/evaluate\", ADMIN),\n rule(\"GET\", \"/api/openapi.json\", VIEWER),\n rule(\"GET\", \"/api/postman.json\", VIEWER),\n rule(\"GET\", \"/docs\", VIEWER),\n rule(\"GET\", \"/docs/swagger\", VIEWER),\n ];\n\n if (options.share === true) {\n rules.push(\n // The grant exchange: public, answered only for a valid token.\n rule(\"POST\", \"/api/share/open\", PUBLIC),\n // What a share grant may reach.\n rule(\"GET\", \"/api/share/info\", SHARE),\n rule(\"GET\", \"/api/share/view.js\", SHARE),\n rule(\"GET\", \"/api/share/assets/:name\", SHARE),\n rule(\"GET\", \"/api/share/files/*\", SHARE),\n rule(\"GET\", \"/api/share/panel\", SHARE),\n rule(\"GET\", \"/api/share/panel/*\", SHARE),\n // Managing the links.\n rule(\"GET\", \"/api/admin/shares\", ADMIN),\n rule(\"POST\", \"/api/admin/shares\", ADMIN),\n rule(\"DELETE\", \"/api/admin/shares/:id\", ADMIN),\n rule(\"POST\", \"/api/admin/shares/revoke-all\", ADMIN),\n );\n }\n\n for (const id of panelIds) {\n rules.push(rule(\"GET\", `/api/${id}`, VIEWER), rule(\"GET\", `/api/${id}/*`, VIEWER));\n\n for (const method of [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const) {\n rules.push(\n rule(method, `/api/${id}`, ADMIN, \"panel.action\"),\n rule(method, `/api/${id}/*`, ADMIN, \"panel.action\"),\n );\n }\n }\n\n return rules;\n}\n\n/** Looks routes up by method and URL pattern: exact first, then the longest `/*` prefix. */\nexport function createAccessLookup(\n rules: readonly DevtoolsRouteAccessRule[],\n): (method: string, pattern: string) => DevtoolsRouteAccessRule | undefined {\n const exact = new Map<string, DevtoolsRouteAccessRule>();\n const wildcards: { method: Method; prefix: string; rule: DevtoolsRouteAccessRule }[] = [];\n\n for (const rule of rules) {\n if (rule.url.endsWith(\"/*\")) {\n wildcards.push({ method: rule.method, prefix: rule.url.slice(0, -1), rule });\n } else {\n exact.set(`${rule.method} ${rule.url}`, rule);\n }\n }\n\n wildcards.sort((a, b) => b.prefix.length - a.prefix.length);\n\n return (method, pattern) => {\n // A HEAD request is answered by the GET route.\n const verb = method === \"HEAD\" ? \"GET\" : method;\n const found = exact.get(`${verb} ${pattern}`);\n\n if (found) return found;\n\n return wildcards.find((item) => item.method === verb && pattern.startsWith(item.prefix))?.rule;\n };\n}\n","import { isIP } from \"node:net\";\nimport type { DevtoolsClientInfo, DevtoolsProxyRequest } from \"./types\";\nimport { ipMatches, normalizeIp } from \"./ip\";\n\n/** The first value of a header that may repeat or hold a comma list. */\nfunction firstValue(value: string | string[] | undefined): string | undefined {\n const text = Array.isArray(value) ? value[0] : value;\n const first = text?.split(\",\")[0]?.trim();\n\n return first === undefined || first === \"\" ? undefined : first;\n}\n\n/** The host name of a `Host` value: no port, lower case, brackets of an IPv6 literal kept. */\nfunction hostnameOf(host: string): string {\n const value = host.trim().toLowerCase();\n\n if (value.startsWith(\"[\")) {\n const end = value.indexOf(\"]\");\n\n return end === -1 ? value : value.slice(0, end + 1);\n }\n\n const colon = value.indexOf(\":\");\n\n return colon === -1 ? value : value.slice(0, colon);\n}\n\n/** The client address out of an `X-Forwarded-For` value, walking right to left past trusted hops. */\nfunction forwardedClient(\n header: string | string[] | undefined,\n trusted: readonly string[],\n): string | undefined {\n const text = Array.isArray(header) ? header.join(\",\") : header;\n const hops = (text ?? \"\")\n .split(\",\")\n .map((hop) => normalizeIp(hop.trim().replace(/^\\[|\\]$/g, \"\")))\n .filter((hop) => isIP(hop) !== 0);\n\n for (let index = hops.length - 1; index >= 0; index -= 1) {\n const hop = hops[index];\n\n if (hop !== undefined && !ipMatches(hop, trusted)) return hop;\n }\n\n // Every hop is a trusted proxy: the leftmost is the origin of the chain.\n return hops[0];\n}\n\n/**\n * The client IP, protocol and host. Forwarding headers are read only when the\n * socket peer is a trusted proxy; `X-Forwarded-For` is walked right to left,\n * skipping trusted addresses, and the first untrusted one is the client.\n */\nexport function resolveClient(\n request: DevtoolsProxyRequest,\n trustedProxies: readonly string[],\n): DevtoolsClientInfo {\n const peer = normalizeIp(request.socket.remoteAddress ?? \"\");\n const headers = request.headers;\n let ip = peer;\n let proto = request.socket.encrypted === true ? \"https\" : \"http\";\n let host = firstValue(headers.host) ?? \"\";\n\n if (peer !== \"\" && ipMatches(peer, trustedProxies)) {\n ip = forwardedClient(headers[\"x-forwarded-for\"], trustedProxies) ?? peer;\n\n const forwardedProto = firstValue(headers[\"x-forwarded-proto\"])?.toLowerCase();\n\n if (forwardedProto === \"http\" || forwardedProto === \"https\") proto = forwardedProto;\n\n host = firstValue(headers[\"x-forwarded-host\"]) ?? host;\n }\n\n host = host.toLowerCase();\n\n return { ip, proto, hostname: hostnameOf(host), host };\n}\n","/** The header the dashboard sends the CSRF token in. */\nexport const DEVTOOLS_CSRF_HEADER = \"x-devtools-csrf\";\n\n/** The session cookie name over HTTPS (`__Secure-` makes browsers refuse it over plain HTTP). */\nexport const DEVTOOLS_SESSION_COOKIE = \"__Secure-warlock-devtools\";\n\n/** The session cookie name when `requireHttps` is off (local trials only). */\nexport const DEVTOOLS_SESSION_COOKIE_INSECURE = \"warlock-devtools\";\n\n/** The share cookie name over HTTPS. */\nexport const DEVTOOLS_SHARE_COOKIE = \"__Secure-warlock-devtools-share\";\n\n/** The share cookie name when `requireHttps` is off (local trials only). */\nexport const DEVTOOLS_SHARE_COOKIE_INSECURE = \"warlock-devtools-share\";\n\n/** The longest a share cookie lives, whatever the link's expiry: 12 hours. */\nexport const DEVTOOLS_SHARE_COOKIE_MAX_SECONDS = 12 * 3600;\n","import type { FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsShareGrant } from \"./share-session\";\nimport type { DevtoolsClientInfo, DevtoolsRouteAccessRule } from \"./types\";\n\n/** What the gate learned about a dashboard request, for the handlers that follow. */\nexport type DevtoolsRequestContext = {\n client: DevtoolsClientInfo;\n meta: DevtoolsRequestMeta;\n /** The access rule the route matched; `undefined` for a route with no entry (treated as admin). */\n rule: DevtoolsRouteAccessRule | undefined;\n /** The route pattern relative to the dashboard path (`/api/requests/:id`). */\n pattern: string;\n /** The session, for every route that is not public. */\n authenticated: DevtoolsAuthenticated | null;\n /** The share grant, for a request that passed the `share` access check. */\n share?: DevtoolsShareGrant | null;\n};\n\nconst contexts = new WeakMap<FastifyRequest, DevtoolsRequestContext>();\n\n/** Stores the context of `request` (the gate calls this). */\nexport function setDevtoolsRequestContext(\n request: FastifyRequest,\n context: DevtoolsRequestContext,\n): void {\n contexts.set(request, context);\n}\n\n/** The context the gate stored for `request`, or `undefined` outside the production dashboard. */\nexport function devtoolsRequestContext(\n request: FastifyRequest,\n): DevtoolsRequestContext | undefined {\n return contexts.get(request);\n}\n","import {\n DEVTOOLS_SESSION_COOKIE,\n DEVTOOLS_SESSION_COOKIE_INSECURE,\n DEVTOOLS_SHARE_COOKIE,\n DEVTOOLS_SHARE_COOKIE_INSECURE,\n} from \"./constants\";\n\n/** The cookie name for the HTTPS mode. */\nexport function sessionCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SESSION_COOKIE : DEVTOOLS_SESSION_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a session token (or a clearing cookie when `token`\n * is `null`). The cookie is a browser-session cookie scoped to the dashboard\n * path, `HttpOnly` and `SameSite=Strict`, with no `Domain`.\n */\nexport function sessionCookie(\n token: string | null,\n options: { path: string; secure: boolean },\n): string {\n const parts = [\n `${sessionCookieName(options.secure)}=${token ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (token === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n\n return parts.join(\"; \");\n}\n\n/** The value of cookie `name` in a `Cookie` header, or `undefined`. */\nexport function readCookie(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n\n for (const pair of header.split(\";\")) {\n const equals = pair.indexOf(\"=\");\n\n if (equals === -1) continue;\n\n if (pair.slice(0, equals).trim() === name) {\n const value = pair.slice(equals + 1).trim();\n\n return value === \"\" ? undefined : value;\n }\n }\n\n return undefined;\n}\n\n/** The share cookie name for the HTTPS mode. */\nexport function shareCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SHARE_COOKIE : DEVTOOLS_SHARE_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a share grant (or a clearing cookie when `value` is\n * `null`). Scoped to the dashboard path, `HttpOnly`, `SameSite=Strict`, no\n * `Domain`, and it ends after `maxAgeSeconds`.\n */\nexport function shareCookie(\n value: string | null,\n options: { path: string; secure: boolean; maxAgeSeconds?: number },\n): string {\n const parts = [\n `${shareCookieName(options.secure)}=${value ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (value === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n else parts.push(`Max-Age=${Math.max(1, Math.floor(options.maxAgeSeconds ?? 0))}`);\n\n return parts.join(\"; \");\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsAuthStep, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsRole } from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport { readCookie, sessionCookie, sessionCookieName } from \"./cookie\";\nimport { devtoolsRequestContext } from \"./context\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst MAX_TEXT = 1024;\nconst MAX_EMAIL = 320;\nconst MAX_CODE = 128;\nconst MAX_TOKEN = 512;\nconst ROLES: readonly DevtoolsRole[] = [\"admin\", \"viewer\"];\n\n/** A request body that is a plain JSON object, or `input.invalid`. */\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\n/** A non-empty string field no longer than `max`, or `input.invalid`. */\nfunction text(body: Record<string, unknown>, key: string, max = MAX_TEXT): string {\n const value = body[key];\n\n if (typeof value !== \"string\" || value === \"\" || value.length > max) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value;\n}\n\n/** An optional string field; `undefined` when absent, `input.invalid` when present but wrong. */\nfunction optionalText(\n body: Record<string, unknown>,\n key: string,\n max = MAX_TEXT,\n): string | undefined {\n return body[key] === undefined ? undefined : text(body, key, max);\n}\n\nfunction email(body: Record<string, unknown>): string {\n const value = text(body, \"email\", MAX_EMAIL).trim().toLowerCase();\n\n if (!/^[^\\s@]+@[^\\s@]+$/.test(value)) throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction role(body: Record<string, unknown>): DevtoolsRole {\n const value = body.role;\n\n if (typeof value !== \"string\" || !ROLES.includes(value as DevtoolsRole)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value as DevtoolsRole;\n}\n\nfunction purpose(body: Record<string, unknown>): \"register\" | \"login\" {\n const value = body.purpose;\n\n if (value !== \"register\" && value !== \"login\") throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction idParam(request: FastifyRequest): string {\n const { id } = (request.params ?? {}) as { id?: unknown };\n\n if (typeof id !== \"string\" || id === \"\" || id.length > MAX_CODE) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return id;\n}\n\n/** The `current` password of a request that may have no body (a DELETE). */\nfunction currentOf(request: FastifyRequest): string | undefined {\n return request.body === undefined || request.body === null\n ? undefined\n : optionalText(bodyOf(request), \"current\");\n}\n\n/** What the gate stored, for a route that is never reached without it. */\nfunction contextOf(request: FastifyRequest): {\n meta: DevtoolsRequestMeta;\n auth: DevtoolsAuthenticated;\n} {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { meta: context.meta, auth: context.authenticated };\n}\n\nfunction metaOf(request: FastifyRequest): DevtoolsRequestMeta {\n const context = devtoolsRequestContext(request);\n\n if (!context) throw new Error(\"A dashboard route ran without its request context.\");\n\n return context.meta;\n}\n\n/**\n * Registers the sign-in, account and admin routes. All decisions live in the\n * auth service; the handlers read the body, call it and answer. The gate\n * (`mountProductionDevtools`) has already checked the session, role, origin\n * and CSRF token by the time a handler runs.\n */\nexport function registerAuthRoutes(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { auth, store, state, production } = deps;\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n\n /** Sets the new session cookie when the step minted one; answers the step. */\n const answerStep = (\n reply: FastifyReply,\n step: DevtoolsAuthStep,\n recoveryCodes?: string[] | null,\n ): DevtoolsAuthStepResult & { recoveryCodes?: string[] } => {\n if (step.token !== null) reply.header(\"set-cookie\", sessionCookie(step.token, cookieOptions));\n\n return {\n stage: step.stage,\n csrf: step.csrf,\n ...(recoveryCodes ? { recoveryCodes } : {}),\n };\n };\n\n /** The stage and CSRF token of the session in force, for answers that do not change it. */\n const currentStep = (authenticated: DevtoolsAuthenticated): DevtoolsAuthStepResult => ({\n stage: authenticated.stage,\n csrf: auth.csrfToken(authenticated.session),\n });\n\n const clearCookie = (reply: FastifyReply): void => {\n reply.header(\"set-cookie\", sessionCookie(null, cookieOptions));\n };\n\n const requireAdmin = (authenticated: DevtoolsAuthenticated): void => {\n if (authenticated.account.role !== \"admin\" || authenticated.stage !== \"active\") {\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n };\n\n // ---- Public ------------------------------------------------------------\n\n server.get(\"/api/auth/session\", async (request, reply) => {\n const token = readCookie(request.headers.cookie, sessionCookieName(production.requireHttps));\n const authenticated = token === undefined ? null : await auth.authenticate(token);\n\n // A cookie that no longer matches a session is dead weight: clear it.\n if (token !== undefined && authenticated === null) clearCookie(reply);\n\n return auth.sessionView(authenticated);\n });\n\n server.post(\"/api/auth/login\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.login(\n { email: email(body), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/setup\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.setup(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/invite/inspect\", async (request) => {\n const body = bodyOf(request);\n\n return auth.inspectInvite(text(body, \"token\", MAX_TOKEN));\n });\n\n server.post(\"/api/auth/invite/accept\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.acceptInvite(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n // ---- Sign-in steps and the account (a session is required) --------------\n\n const changePassword = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const current = optionalText(body, \"current\");\n const step = await auth.changePassword(\n authenticated,\n { ...(current === undefined ? {} : { current }), password: text(body, \"password\") },\n meta,\n );\n\n return answerStep(reply, step);\n };\n\n const startTotp = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.startTotp(authenticated, meta);\n };\n\n const confirmTotp = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const result = await auth.confirmTotp(\n authenticated,\n text(body, \"code\", MAX_CODE),\n meta,\n optionalText(body, \"current\"),\n );\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n const passkeyOptions = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.passkeyOptions(authenticated, purpose(bodyOf(request)), meta);\n };\n\n const passkeyVerify = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n if (body.response === null || typeof body.response !== \"object\") {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const result = await auth.verifyPasskey(\n authenticated,\n purpose(body),\n body.response,\n meta,\n optionalText(body, \"current\"),\n );\n\n if (result.step === null) {\n return {\n ...currentStep(authenticated),\n ...(result.recoveryCodes ? { recoveryCodes: result.recoveryCodes } : {}),\n };\n }\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n server.post(\"/api/auth/password\", changePassword);\n server.post(\"/api/auth/totp/start\", startTotp);\n server.post(\"/api/auth/totp/confirm\", confirmTotp);\n server.post(\"/api/auth/passkey/options\", passkeyOptions);\n server.post(\"/api/auth/passkey/verify\", passkeyVerify);\n\n server.post(\"/api/auth/mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const code = optionalText(body, \"code\", MAX_CODE);\n const recoveryCode = optionalText(body, \"recoveryCode\", MAX_CODE);\n\n if ((code === undefined) === (recoveryCode === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const step = await auth.verifySecondFactor(\n authenticated,\n code === undefined ? { recoveryCode: recoveryCode as string } : { code },\n meta,\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/logout\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.logout(authenticated, meta);\n clearCookie(reply);\n\n return reply.code(204).send();\n });\n\n server.get(\"/api/account\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.accountView(authenticated.account);\n });\n\n server.get(\"/api/account/sessions\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listSessions(authenticated);\n });\n\n server.delete(\"/api/account/sessions/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeSession(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/password\", changePassword);\n server.post(\"/api/account/totp/start\", startTotp);\n server.post(\"/api/account/totp/confirm\", confirmTotp);\n\n server.delete(\"/api/account/totp\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeTotp(authenticated, meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/recovery-codes\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n // No code: a passkey step-up in this session stands in for it.\n const codes = await auth.regenerateRecoveryCodes(\n authenticated,\n optionalText(bodyOf(request), \"code\", MAX_CODE) ?? \"\",\n meta,\n );\n\n return { codes };\n });\n\n server.post(\"/api/account/passkey/options\", passkeyOptions);\n server.post(\"/api/account/passkey/verify\", passkeyVerify);\n\n server.delete(\"/api/account/passkeys/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removePasskey(authenticated, idParam(request), meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n // ---- Admin ---------------------------------------------------------------\n\n server.get(\"/api/admin/users\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listUsers(authenticated);\n });\n\n server.post(\"/api/admin/invites\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n return auth.createInvite(authenticated, { email: email(body), role: role(body) }, meta);\n });\n\n server.delete(\"/api/admin/invites/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeInvite(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.patch(\"/api/admin/users/:id\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.setRole(authenticated, idParam(request), role(bodyOf(request)), meta);\n });\n\n server.delete(\"/api/admin/users/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/reset-mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.resetSecondFactor(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/sign-out\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.signOutAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.get<{ Querystring: Record<string, string | undefined> }>(\n \"/api/admin/audit\",\n async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n requireAdmin(authenticated);\n\n const query = request.query;\n const types = query.type\n ?.split(\",\")\n .map((type) => type.trim())\n .filter((type) => type !== \"\");\n const before = query.before === undefined ? undefined : Number(query.before);\n const limit = query.limit === undefined ? 100 : Number(query.limit);\n\n if (\n (before !== undefined && !Number.isFinite(before)) ||\n !Number.isInteger(limit) ||\n limit < 1\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return store.audit.list({\n ...(types && types.length > 0 ? { types: types as DevtoolsAuditType[] } : {}),\n ...(query.account ? { accountId: query.account } : {}),\n ...(before === undefined ? {} : { before }),\n limit: Math.min(limit, 500),\n });\n },\n );\n\n server.post(\"/api/admin/disable\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n if (bodyOf(request).confirm !== \"disable\") throw new DevtoolsApiError(\"input.invalid\");\n\n await auth.disableDashboard(authenticated, meta);\n // This process closes at once; the others within the state cache time.\n state.invalidate();\n\n return reply.code(204).send();\n });\n}\n","/** Headers on every dashboard answer that is not the uniform 404. */\nexport const DASHBOARD_HEADERS: Readonly<Record<string, string>> = {\n \"Cache-Control\": \"no-store\",\n \"X-Robots-Tag\": \"noindex, nofollow, noarchive\",\n \"Referrer-Policy\": \"no-referrer\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"X-Frame-Options\": \"DENY\",\n \"Cross-Origin-Opener-Policy\": \"same-origin\",\n \"Cross-Origin-Resource-Policy\": \"same-origin\",\n \"Permissions-Policy\":\n \"camera=(), microphone=(), geolocation=(), publickey-credentials-get=(self), publickey-credentials-create=(self)\",\n};\n\n/** The policy of the dashboard's own HTML: scripts and styles from the bundle only. */\nexport const DASHBOARD_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n\n/**\n * The policy of the opt-in API documentation pages: scripts from the dashboard\n * only (Scalar and Swagger UI probe `Function` in a try/catch and work without\n * `'unsafe-eval'`), inline styles, and framing by the dashboard itself, whose\n * API tab shows them in a frame.\n */\nexport const DOCS_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n","import type { MountedDevtoolsPanel } from \"../../panels\";\nimport { safeEqual } from \"../auth/helpers\";\nimport type { DevtoolsShareRecord, DevtoolsStore } from \"../store/types\";\nimport { DEVTOOLS_SHARE_COOKIE_MAX_SECONDS } from \"./constants\";\n\n/** How long a read of a share record is reused. A revoke reaches every instance within this time. */\nexport const SHARE_CACHE_MS = 5000;\n\n/** Records kept in the cache of one process (oldest evicted). */\nconst SHARE_CACHE_SIZE = 500;\n\n/** A link's use is written at most this often per link and process. */\nconst TOUCH_INTERVAL_MS = 60_000;\n\n/** What a valid share cookie grants: the link and the panel it opens. */\nexport type DevtoolsShareGrant = {\n share: DevtoolsShareRecord;\n panel: MountedDevtoolsPanel;\n};\n\n/** Why a share cookie or token was refused (written to the audit log; never the value). */\nexport type DevtoolsShareRefusal = \"unknown\" | \"expired\" | \"revoked\" | \"panel\" | \"cookie\";\n\nexport type DevtoolsShareSessions = {\n /** The cookie value for `share`: `<id>.<exp>.<hmac>`, and its life in seconds. */\n issue(share: DevtoolsShareRecord): { value: string; maxAgeSeconds: number };\n /** The grant a `Cookie` value carries, or the reason it was refused. */\n verify(\n value: string | undefined,\n ): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** The record a token hash names, checked for life and panel; or the reason it is refused. */\n open(\n tokenHash: string,\n ): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** Counts one use of `share` (at most once a minute per link). */\n touch(shareId: string): void;\n /** Forgets cached records (after this process revoked or created a link). */\n invalidate(): void;\n};\n\n/**\n * The share grant: a cookie carrying `<shareId>.<exp>.<HMAC-SHA256(key,\n * \"share:<id>:<exp>\")>`. The signature proves this server issued it; the\n * link's record, read through a 5-second cache, proves it is still alive, so\n * a revoke takes effect everywhere within that time without a session table.\n */\nexport function createShareSessions(input: {\n store: DevtoolsStore;\n panels: readonly MountedDevtoolsPanel[];\n hmac: (value: string) => string;\n now?: () => number;\n warn?: (message: string) => void;\n}): DevtoolsShareSessions {\n const { store, hmac } = input;\n const now = input.now ?? (() => Date.now());\n const panels = new Map(\n input.panels.filter((panel) => panel.share !== null).map((panel) => [panel.id, panel]),\n );\n const cache = new Map<string, { record: DevtoolsShareRecord | null; at: number }>();\n const touched = new Map<string, number>();\n\n const sign = (id: string, exp: number): string => hmac(`share:${id}:${exp}`);\n\n async function record(id: string): Promise<DevtoolsShareRecord | null> {\n const cached = cache.get(id);\n\n if (cached && now() - cached.at < SHARE_CACHE_MS) return cached.record;\n\n const found = await store.shares.get(id);\n\n cache.delete(id);\n\n if (cache.size >= SHARE_CACHE_SIZE) {\n const oldest = cache.keys().next();\n\n if (!oldest.done) cache.delete(oldest.value);\n }\n\n cache.set(id, { record: found, at: now() });\n\n return found;\n }\n\n function grantFor(\n share: DevtoolsShareRecord,\n ): { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string } {\n if (share.revokedAt !== null) return { refused: \"revoked\", shareId: share.id };\n\n if (share.expiresAt <= now()) return { refused: \"expired\", shareId: share.id };\n\n const panel = panels.get(share.panel);\n\n return panel ? { grant: { share, panel } } : { refused: \"panel\", shareId: share.id };\n }\n\n return {\n issue(share) {\n const remaining = Math.floor((share.expiresAt - now()) / 1000);\n const maxAgeSeconds = Math.max(1, Math.min(remaining, DEVTOOLS_SHARE_COOKIE_MAX_SECONDS));\n const exp = now() + maxAgeSeconds * 1000;\n\n return { value: `${share.id}.${exp}.${sign(share.id, exp)}`, maxAgeSeconds };\n },\n\n async verify(value) {\n const parts = (value ?? \"\").split(\".\");\n const [id, expText, signature] = parts;\n\n if (parts.length !== 3 || !id || !expText || !signature || !/^\\d{1,16}$/.test(expText)) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const exp = Number(expText);\n\n if (!safeEqual(signature, sign(id, exp)) || exp <= now()) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const share = await record(id);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: id };\n },\n\n async open(tokenHash) {\n const share = await store.shares.findByTokenHash(tokenHash);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: null };\n },\n\n touch(shareId) {\n const at = now();\n const last = touched.get(shareId);\n\n if (last !== undefined && at - last < TOUCH_INTERVAL_MS) return;\n\n touched.delete(shareId);\n\n if (touched.size >= SHARE_CACHE_SIZE) {\n const oldest = touched.keys().next();\n\n if (!oldest.done) touched.delete(oldest.value);\n }\n\n touched.set(shareId, at);\n // A failed write is not worth failing the request for.\n void store.shares.touch(shareId, at).catch((error: unknown) => {\n input.warn?.(\n `devtools could not record a share link use: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n },\n\n invalidate() {\n cache.clear();\n },\n };\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { panelContentType, type MountedDevtoolsPanel } from \"../../panels\";\nimport { sendPanelFile } from \"../../server/panel-routes\";\nimport { sendFile } from \"../../server/ui-assets\";\nimport type { DevtoolsPanelRequest } from \"../../types\";\nimport { generateToken, hashToken } from \"../auth/helpers\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport {\n DEVTOOLS_FAILURE_AUDIT_TYPES,\n DEVTOOLS_SHARE_LABEL_MAX,\n type DevtoolsCreatedShare,\n type DevtoolsShareList,\n type DevtoolsShareOpenAnswer,\n type DevtoolsShareView,\n} from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport type { DevtoolsShareRecord } from \"../store/types\";\nimport { devtoolsRequestContext } from \"./context\";\nimport { readCookie, shareCookie, shareCookieName } from \"./cookie\";\nimport { rateLimitClient } from \"./ip\";\nimport { createShareSessions, type DevtoolsShareGrant } from \"./share-session\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst DAY_MS = 86_400_000;\nconst MAX_TOKEN = 512;\nconst MAX_PANEL_ID = 64;\n\n/** A failed token is not looked up again for this long once its client is over the limit. */\nconst BLOCK_CACHE_MS = 30_000;\nconst BLOCK_CACHE_SIZE = 1000;\n\n/** A cookie failure is audited at most this often per client (a revoked link in use must not flood the log). */\nconst COOKIE_AUDIT_INTERVAL_MS = 60_000;\n\ntype Notfound = (request: FastifyRequest, reply: FastifyReply) => FastifyReply;\n\n/** The path pattern `pattern` (`/flows/:feature`) matched against `path`, as its params; `null` for no match. */\nexport function matchSharePath(pattern: string, path: string): Record<string, string> | null {\n if (/[\\0\\\\]/.test(path)) return null;\n\n const wanted = pattern.split(\"/\");\n const given = path.split(\"/\");\n\n if (wanted.length !== given.length) return null;\n\n const params: Record<string, string> = {};\n\n for (const [index, part] of wanted.entries()) {\n const actual = given[index];\n\n if (actual === undefined) return null;\n\n if (part.startsWith(\":\")) {\n if (actual === \"\") return null;\n\n params[part.slice(1)] = actual;\n } else if (part !== actual) {\n return null;\n }\n }\n\n return params;\n}\n\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\nfunction viewOf(\n record: DevtoolsShareRecord,\n createdBy: string | null,\n at: number,\n): DevtoolsShareView {\n return {\n id: record.id,\n panel: record.panel,\n label: record.label,\n createdBy,\n createdAt: record.createdAt,\n expiresAt: record.expiresAt,\n revokedAt: record.revokedAt,\n lastUsedAt: record.lastUsedAt,\n uses: record.uses,\n status: record.revokedAt !== null ? \"revoked\" : record.expiresAt <= at ? \"expired\" : \"active\",\n };\n}\n\nfunction openAnswer(grant: DevtoolsShareGrant): DevtoolsShareOpenAnswer {\n const { panel, share } = grant;\n\n return {\n panel: panel.id,\n title: panel.title,\n label: share.label,\n expiresAt: share.expiresAt,\n assets: [...(panel.share?.assets ?? [])],\n files: panel.share?.files === true,\n };\n}\n\n/** What `mountProductionDevtools` gets back when sharing is on. */\nexport type DevtoolsShareMount = {\n /** The grant of a request's share cookie, or `null` (the gate then answers the uniform 404). */\n authorize(request: FastifyRequest, meta: DevtoolsRequestMeta): Promise<DevtoolsShareGrant | null>;\n /** Registers the share routes and the admin routes that manage links. */\n register(server: FastifyInstance, notFound: Notfound): void;\n};\n\n/**\n * Read-only share links of the production monitor. An admin creates a link\n * for a panel that declares `share`; the token is shown once and only its\n * SHA-256 is stored. Opening a link exchanges the token for a scoped cookie\n * (`__Secure-warlock-devtools-share`) that reaches only that panel's shared\n * view. Every refusal answers the dashboard's uniform 404, is audited as\n * `share.failed` (which counts toward the per-IP failure limit) and never\n * records the token.\n */\nexport function createDevtoolsShare(\n deps: MountProductionDevtoolsDeps & { now?: () => number },\n): DevtoolsShareMount {\n const { production, store, auth } = deps;\n const now = deps.now ?? (() => Date.now());\n\n if (typeof deps.hmac !== \"function\") {\n throw new Error(\"Share links need deps.hmac (HMAC-SHA256 keyed with encryption.key).\");\n }\n\n const sessions = createShareSessions({\n store,\n panels: deps.panels,\n hmac: deps.hmac,\n now,\n ...(deps.warn ? { warn: deps.warn } : {}),\n });\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n const cookieName = shareCookieName(production.requireHttps);\n const sharePanels = deps.panels.filter((panel) => panel.share !== null);\n const blocked = new Map<string, number>();\n const cookieAudited = new Map<string, number>();\n\n const limits = production.rateLimits;\n const windowMs = limits.windowMinutes * 60_000;\n\n async function overLimit(ip: string): Promise<boolean> {\n const client = rateLimitClient(ip);\n const at = now();\n const until = blocked.get(client);\n\n if (until !== undefined && at < until) return true;\n\n const state = await store.state.read();\n const since = Math.max(at - windowMs, state.failuresResetAt ?? 0);\n const count = await store.audit.count({ types: DEVTOOLS_FAILURE_AUDIT_TYPES, since, ip });\n\n blocked.delete(client);\n\n if (count < limits.ip) return false;\n\n if (blocked.size >= BLOCK_CACHE_SIZE) {\n const oldest = blocked.keys().next();\n\n if (!oldest.done) blocked.delete(oldest.value);\n }\n\n blocked.set(client, at + BLOCK_CACHE_MS);\n\n return true;\n }\n\n /** Writes one `share.failed` entry (never the token). Never throws. */\n async function failed(\n meta: DevtoolsRequestMeta,\n reason: string,\n shareId: string | null,\n ): Promise<void> {\n await auth.audit(\"share.failed\", { meta, detail: { reason, share: shareId } });\n }\n\n /** The cookie check for a share request. */\n async function authorize(\n request: FastifyRequest,\n meta: DevtoolsRequestMeta,\n ): Promise<DevtoolsShareGrant | null> {\n const value = readCookie(request.headers.cookie, cookieName);\n\n if (value === undefined) return null;\n\n let result;\n\n try {\n result = await sessions.verify(value);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return null;\n }\n\n if (\"grant\" in result) {\n sessions.touch(result.grant.share.id);\n\n return result.grant;\n }\n\n const client = rateLimitClient(meta.ip);\n const last = cookieAudited.get(client);\n\n if (last === undefined || now() - last >= COOKIE_AUDIT_INTERVAL_MS) {\n cookieAudited.delete(client);\n\n if (cookieAudited.size >= BLOCK_CACHE_SIZE) {\n const oldest = cookieAudited.keys().next();\n\n if (!oldest.done) cookieAudited.delete(oldest.value);\n }\n\n cookieAudited.set(client, now());\n\n try {\n if (!(await overLimit(meta.ip))) await failed(meta, result.refused, result.shareId);\n } catch {\n // The refusal stands even when the audit cannot be written.\n }\n }\n\n return null;\n }\n\n function grantOf(request: FastifyRequest): DevtoolsShareGrant {\n const grant = devtoolsRequestContext(request)?.share;\n\n if (!grant) throw new Error(\"A share route ran without its grant.\");\n\n return grant;\n }\n\n function createdByOf(\n accounts: readonly { id: string; email: string }[],\n id: string | null,\n ): string | null {\n return accounts.find((account) => account.id === id)?.email ?? null;\n }\n\n // ---- Admin ----------------------------------------------------------------\n\n async function list(): Promise<DevtoolsShareList> {\n const [records, accounts] = await Promise.all([store.shares.list(), store.accounts.list()]);\n const at = now();\n\n return {\n enabled: true,\n maxDays: production.share.maxDays,\n panels: sharePanels.map((panel) => ({ id: panel.id, title: panel.title })),\n shares: records.map((record) => viewOf(record, createdByOf(accounts, record.createdBy), at)),\n };\n }\n\n async function create(\n authenticated: DevtoolsAuthenticated,\n meta: DevtoolsRequestMeta,\n body: Record<string, unknown>,\n ): Promise<DevtoolsCreatedShare> {\n const panel = body.panel;\n const label = typeof body.label === \"string\" ? body.label.trim() : \"\";\n const days = body.days;\n\n if (\n typeof panel !== \"string\" ||\n panel.length > MAX_PANEL_ID ||\n !sharePanels.some((item) => item.id === panel) ||\n label === \"\" ||\n label.length > DEVTOOLS_SHARE_LABEL_MAX ||\n // eslint-disable-next-line no-control-regex\n /[\\u0000-\\u001f\\u007f]/.test(label) ||\n typeof days !== \"number\" ||\n !Number.isInteger(days) ||\n days < 1 ||\n days > production.share.maxDays\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const token = generateToken();\n const at = now();\n const record = await store.shares.create({\n tokenHash: hashToken(token),\n panel,\n label,\n createdBy: authenticated.account.id,\n createdAt: at,\n expiresAt: at + days * DAY_MS,\n });\n\n sessions.invalidate();\n await auth.audit(\"share.created\", {\n auth: authenticated,\n meta,\n detail: { share: record.id, panel, days },\n });\n\n return {\n share: viewOf(record, authenticated.account.email, at),\n // The token rides in the fragment: it never reaches an access log or a Referer header.\n url: `${meta.origin}${production.path}/#/share/${token}`,\n };\n }\n\n // ---- Registration -----------------------------------------------------------\n\n function register(server: FastifyInstance, notFound: Notfound): void {\n const requireAuth = (request: FastifyRequest) => {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { auth: context.authenticated, meta: context.meta };\n };\n\n // The grant exchange. Every failure answers the uniform 404.\n server.post(\"/api/share/open\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n\n if (!context) return notFound(request, reply);\n\n const { meta } = context;\n const token = (request.body as { token?: unknown } | null | undefined)?.token;\n\n if (typeof token !== \"string\" || token === \"\" || token.length > MAX_TOKEN) {\n return notFound(request, reply);\n }\n\n try {\n if (await overLimit(meta.ip)) return notFound(request, reply);\n\n const result = await sessions.open(hashToken(token));\n\n if (!(\"grant\" in result)) {\n await failed(meta, result.refused, result.shareId);\n\n return notFound(request, reply);\n }\n\n const { value, maxAgeSeconds } = sessions.issue(result.grant.share);\n\n sessions.touch(result.grant.share.id);\n reply.header(\"set-cookie\", shareCookie(value, { ...cookieOptions, maxAgeSeconds }));\n\n return openAnswer(result.grant);\n } catch (error) {\n deps.warn?.(\n `A devtools share link could not be opened: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n });\n\n server.get(\"/api/share/info\", async (request) => openAnswer(grantOf(request)));\n\n server.get(\"/api/share/view.js\", async (request, reply) => {\n const view = grantOf(request).panel.share?.view;\n\n if (view === undefined) return notFound(request, reply);\n\n sendFile(reply, view, \"text/javascript; charset=utf-8\");\n\n return reply;\n });\n\n server.get<{ Params: { name: string } }>(\"/api/share/assets/:name\", async (request, reply) => {\n const { panel } = grantOf(request);\n const name = request.params.name;\n const file =\n panel.share?.assets.includes(name) === true && Object.hasOwn(panel.assets, name)\n ? panel.assets[name]\n : undefined;\n\n if (file === undefined) return notFound(request, reply);\n\n sendFile(reply, file, panelContentType(name));\n\n return reply;\n });\n\n server.get<{ Params: { \"*\": string } }>(\"/api/share/files/*\", async (request, reply) => {\n const { panel } = grantOf(request);\n\n return sendPanelFile(\n { files: panel.share?.files === true ? panel.files : null },\n request.params[\"*\"],\n request,\n reply,\n notFound,\n );\n });\n\n const panelRoute = async (request: FastifyRequest, reply: FastifyReply) => {\n const { panel } = grantOf(request);\n const sub = (request.params as { \"*\"?: string })[\"*\"];\n const path = sub === undefined || sub === \"\" ? \"\" : `/${sub}`;\n let matched: {\n route: MountedDevtoolsPanel[\"routes\"][number];\n params: Record<string, string>;\n } | null = null;\n\n for (const pattern of panel.share?.routes ?? []) {\n const params = matchSharePath(pattern, path);\n const route = panel.routes.find(\n (candidate) => candidate.method === \"GET\" && candidate.path === pattern,\n );\n\n if (params !== null && route !== undefined) {\n matched = { route, params };\n break;\n }\n }\n\n if (matched === null) return notFound(request, reply);\n\n const input: DevtoolsPanelRequest = {\n params: matched.params,\n query: (request.query ?? {}) as Record<string, string | string[]>,\n body: undefined,\n shared: true,\n };\n const result = await matched.route.handler(input);\n\n reply.header(\"cache-control\", \"no-store\");\n\n if (result === undefined) return reply.code(204).send();\n\n return result;\n };\n\n server.get(\"/api/share/panel\", panelRoute);\n server.get(\"/api/share/panel/*\", panelRoute);\n\n server.get(\"/api/admin/shares\", async () => list());\n\n server.post(\"/api/admin/shares\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const created = await create(authenticated, meta, bodyOf(request));\n\n return reply.code(201).send(created);\n });\n\n server.delete<{ Params: { id: string } }>(\"/api/admin/shares/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const id = request.params.id;\n\n if (typeof id !== \"string\" || id === \"\" || id.length > 64) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const record = await store.shares.get(id);\n\n if (!record || !(await store.shares.revoke(id, now()))) {\n throw new DevtoolsApiError(\"share.not-found\");\n }\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { share: id, panel: record.panel },\n });\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/shares/revoke-all\", async (request) => {\n const { auth: authenticated, meta } = requireAuth(request);\n const revoked = await store.shares.revokeAll(now());\n\n sessions.invalidate();\n await auth.audit(\"share.revoked\", {\n auth: authenticated,\n meta,\n detail: { all: true, count: revoked },\n });\n\n return { revoked };\n });\n }\n\n return { authorize, register };\n}\n","import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\nimport { registerAiReportRoutes } from \"../../server/ai-report-routes\";\nimport { registerAiRoutes } from \"../../server/ai-routes\";\nimport { registerShapeExplainRoute } from \"../../server/explain-route\";\nimport { registerInsightsRoutes } from \"../../server/insights-routes\";\nimport { registerLogRoutes } from \"../../server/log-routes\";\nimport { registerMailRoutes } from \"../../server/mail-routes\";\nimport { registerOpenApiRoutes } from \"../../server/openapi-routes\";\nimport { registerPanelRoutes } from \"../../server/panel-routes\";\nimport { registerRequestsRoutes } from \"../../server/requests-routes\";\nimport { registerRouteRoutes } from \"../../server/route-routes\";\nimport { registerStreamRoute } from \"../../server/stream-route\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"../../server/types\";\nimport { registerUiAssets } from \"../../server/ui-assets\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport { DevtoolsApiError, createErrorRef, DEVTOOLS_ERROR_MESSAGES } from \"../errors\";\nimport { createAccessLookup, productionRouteAccess } from \"./access\";\nimport { registerAuthRoutes } from \"./auth-routes\";\nimport { resolveClient } from \"./client\";\nimport { setDevtoolsRequestContext, devtoolsRequestContext } from \"./context\";\nimport { readCookie, sessionCookieName } from \"./cookie\";\nimport { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from \"./headers\";\nimport { DEVTOOLS_CSRF_HEADER } from \"./constants\";\nimport { createDevtoolsShare } from \"./share\";\nimport { ipMatches } from \"./ip\";\nimport type { DevtoolsRouteAccess, MountProductionDevtoolsDeps } from \"./types\";\n\n/** Open live streams a session may hold, and an instance may serve. */\nconst MAX_STREAMS_PER_SESSION = 3;\nconst MAX_STREAMS_PER_INSTANCE = 50;\n\nconst MAX_USER_AGENT = 200;\n\n/** Methods that never change state. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */\nconst DOCS_PATTERNS = new Set([\"/docs\", \"/docs/swagger\"]);\n\n/** The grant exchange of a share link: every failure of it answers the uniform 404. */\nconst SHARE_OPEN_PATTERN = \"/api/share/open\";\n\n/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */\nconst MAIL_HTML_PATTERN = \"/api/mails/:id/html\";\n\n/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */\nconst TAB_OF_ROUTE: readonly (readonly [prefix: string, tab: string])[] = [\n [\"/api/resources\", \"resources\"],\n [\"/api/queries\", \"queries\"],\n [\"/api/routes/stats\", \"routes\"],\n [\"/api/routes\", \"routes\"],\n [\"/api/health\", \"health\"],\n [\"/api/errors\", \"errors\"],\n [\"/api/jobs\", \"jobs\"],\n [\"/api/logs\", \"logs\"],\n [\"/api/requests\", \"requests\"],\n [\"/api/mails\", \"mail\"],\n [\"/api/ai/agent-runs\", \"agents\"],\n [\"/api/ai/reports\", \"ai-reports\"],\n [\"/api/ai/models\", \"ai-models\"],\n [\"/api/ai/errors\", \"ai-errors\"],\n [\"/api/ai/evaluate\", \"ai-evaluate\"],\n [\"/api/ai\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\n\n/** The tabs the AI report routes serve; the routes register when any of them is on. */\nconst AI_REPORT_TABS = [\"ai-reports\", \"ai-models\", \"ai-errors\", \"ai-evaluate\"] as const;\n\nfunction tabOf(pattern: string): string | undefined {\n return TAB_OF_ROUTE.find(\n ([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`),\n )?.[1];\n}\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */\nconst uniformNotFound = new WeakSet<FastifyRequest>();\n\n/**\n * The origin the browser must send for an unsafe request: `production.origin`,\n * else the scheme and host the request was addressed to.\n */\nfunction originAllowed(request: FastifyRequest, expected: string): boolean {\n const origin = request.headers.origin;\n const site = request.headers[\"sec-fetch-site\"];\n\n if (site !== undefined && site !== \"same-origin\") return false;\n\n if (origin !== undefined) return origin.toLowerCase() === expected.toLowerCase();\n\n // No Origin header: a same-origin fetch from an older browser. Accept it only with the fetch metadata that proves it.\n return site === \"same-origin\";\n}\n\nfunction hasBody(request: FastifyRequest): boolean {\n const length = request.headers[\"content-length\"];\n\n return (\n (length !== undefined && length !== \"0\") || request.headers[\"transfer-encoding\"] !== undefined\n );\n}\n\nfunction isJson(request: FastifyRequest): boolean {\n return /^application\\/json\\s*(;|$)/i.test(request.headers[\"content-type\"] ?? \"\");\n}\n\nfunction sessionAccessOk(\n access: Exclude<DevtoolsRouteAccess, { type: \"public\" }>,\n stage: string,\n): boolean {\n if (stage === \"active\") return true;\n\n return access.type === \"pending\" && (access.stages as readonly string[]).includes(stage);\n}\n\n/**\n * Mounts the production monitor under `production.path` in one encapsulated\n * Fastify context: the gate (uniform 404, HTTPS, allowed IPs, open state),\n * session and role checks from the access table, CSRF and origin checks,\n * security headers and CORS stripping, the auth/account/admin routes, and\n * the shared data routes of the enabled tabs.\n */\nexport function mountProductionDevtools(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { production, auth, state, store } = deps;\n const prefix = production.path;\n const cookieName = sessionCookieName(production.requireHttps);\n const enabledTabs = new Set(deps.builtInPanels);\n const share = production.share.enabled ? createDevtoolsShare(deps) : null;\n const lookup = createAccessLookup(\n productionRouteAccess(\n deps.panels.map((panel) => panel.id),\n { share: share !== null },\n ),\n );\n const streamsPerSession = new Map<string, number>();\n let streamsInstance = 0;\n let lastWarningAt = 0;\n\n const warn = (message: string): void => {\n // At most one line a minute: a database outage must not flood the log.\n const now = Date.now();\n\n if (now - lastWarningAt < 60_000) return;\n\n lastWarningAt = now;\n deps.warn?.(message);\n };\n\n const notFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply => {\n uniformNotFound.add(request);\n\n // The app's own not-found handler answers, so the reply is the one any unknown URL gets.\n reply.callNotFound();\n\n // Returning the reply is what stops an async hook's lifecycle.\n return reply;\n };\n\n const streamSession = async (request: FastifyRequest): Promise<DevtoolsStreamSession> => {\n const authenticated = devtoolsRequestContext(request)?.authenticated;\n\n if (!authenticated) throw new Error(\"A dashboard stream was opened without a session.\");\n\n const sessionId = authenticated.session.id;\n const token = readCookie(request.headers.cookie, cookieName);\n const open = streamsPerSession.get(sessionId) ?? 0;\n\n if (open >= MAX_STREAMS_PER_SESSION || streamsInstance >= MAX_STREAMS_PER_INSTANCE) {\n throw new DevtoolsApiError(\"stream.too-many\");\n }\n\n streamsPerSession.set(sessionId, open + 1);\n streamsInstance += 1;\n\n let released = false;\n\n return {\n role: authenticated.account.role,\n logLevels: production.logLevels,\n headers: DASHBOARD_HEADERS,\n // Reads the session without touching `lastSeenAt`: a stream left open must not keep the session alive.\n async revalidate() {\n if (token === undefined || !(await state.isOpen())) return false;\n\n const session = await store.sessions.findByTokenHash(tokenHash(token));\n const now = Date.now();\n\n if (\n session === null ||\n session.stage !== \"active\" ||\n now >= session.expiresAt ||\n now - session.lastSeenAt >= production.session.idleMinutes * 60_000\n ) {\n return false;\n }\n\n return (await store.accounts.findById(session.accountId)) !== null;\n },\n release() {\n if (released) return;\n\n released = true;\n streamsInstance -= 1;\n\n const left = (streamsPerSession.get(sessionId) ?? 1) - 1;\n\n if (left <= 0) streamsPerSession.delete(sessionId);\n else streamsPerSession.set(sessionId, left);\n },\n };\n };\n\n // The route deps the shared route files read: the development deps, completed.\n const routes: MountDevtoolsRoutesDeps = {\n ...deps.routes,\n mode: \"production\",\n isDevelopment: () => false,\n instance: deps.instance,\n insights: deps.insights,\n collector: deps.routes.collector ?? deps.capture.collector,\n requests: deps.routes.requests ?? deps.capture.requests,\n explainShape: deps.routes.explainShape ?? ((shapeId) => deps.capture.explain(shapeId)),\n builtInPanels: deps.builtInPanels,\n streamSession,\n };\n\n server.register(\n async (instance) => {\n // ---- The gate -------------------------------------------------------\n instance.addHook(\"onRequest\", async (request, reply) => {\n let open: boolean;\n\n try {\n open = await state.isOpen();\n } catch (error) {\n // Fail closed: when the state cannot be read the dashboard does not answer.\n warn(\n `The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`,\n );\n open = false;\n }\n\n if (!open) return notFound(request, reply);\n\n const client = resolveClient(request, production.trustedProxies);\n\n if (production.requireHttps && client.proto !== \"https\") return notFound(request, reply);\n\n if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) {\n return notFound(request, reply);\n }\n\n const userAgent = request.headers[\"user-agent\"];\n const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;\n const meta: DevtoolsRequestMeta = {\n ip: client.ip,\n userAgent: typeof userAgent === \"string\" ? userAgent.slice(0, MAX_USER_AGENT) : null,\n origin: expectedOrigin,\n hostname: client.hostname,\n };\n\n const routeUrl = request.routeOptions.url ?? \"\";\n const relative = routeUrl.startsWith(prefix) ? routeUrl.slice(prefix.length) : routeUrl;\n // The shell is registered once for both `<path>` and `<path>/`.\n const pattern = relative === \"\" ? \"/\" : relative;\n const method = request.method;\n\n // The bare path (no trailing slash) redirects to the shell's address. The\n // address as sent: core's server drops a trailing slash before routing,\n // so the rewritten URL of `<path>/` is the bare path too.\n const sent = request.originalUrl ?? request.raw.url ?? \"\";\n\n if (sent.split(\"?\")[0] === prefix) {\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule: undefined,\n pattern,\n authenticated: null,\n });\n\n if (method !== \"GET\" && method !== \"HEAD\") return notFound(request, reply);\n\n const search = sent.includes(\"?\") ? `?${sent.split(\"?\").slice(1).join(\"?\")}` : \"\";\n\n return reply.redirect(`${prefix}/${search}`, 308);\n }\n\n const tab = tabOf(pattern);\n\n if (tab !== undefined && !enabledTabs.has(tab)) return notFound(request, reply);\n\n const rule = lookup(method, pattern);\n const access: DevtoolsRouteAccess = rule?.access ?? { type: \"admin\" };\n let authenticated: DevtoolsAuthenticated | null = null;\n\n // A share link has no account: its cookie grants one panel's shared view and nothing else.\n if (access.type === \"share\") {\n const grant = share ? await share.authorize(request, meta) : null;\n\n if (grant === null) return notFound(request, reply);\n\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule,\n pattern,\n authenticated: null,\n share: grant,\n });\n\n return;\n }\n\n if (access.type !== \"public\") {\n try {\n authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));\n } catch (error) {\n warn(\n `The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n\n if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) {\n return notFound(request, reply);\n }\n\n if (access.type === \"admin\" && authenticated.account.role !== \"admin\") {\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n }\n\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n\n if (SAFE_METHODS.has(method)) return;\n\n if (!originAllowed(request, expectedOrigin)) {\n if (authenticated === null) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n\n if (hasBody(request) && !isJson(request)) {\n if (pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (authenticated !== null) {\n const header = request.headers[DEVTOOLS_CSRF_HEADER];\n\n if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) {\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n }\n });\n\n // ---- Headers --------------------------------------------------------\n instance.addHook(\"onSend\", async (request, reply, payload) => {\n // The uniform 404 must look like any other 404 of the app.\n if (uniformNotFound.has(request)) return payload;\n\n for (const name of Object.keys(reply.getHeaders())) {\n if (name.startsWith(\"access-control-\")) reply.removeHeader(name);\n }\n\n reply.headers(DASHBOARD_HEADERS);\n\n const pattern = devtoolsRequestContext(request)?.pattern ?? \"\";\n\n // The mail preview is the one page the dashboard frames, from its own origin, and it sends its own policy.\n if (pattern === MAIL_HTML_PATTERN) {\n reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n return payload;\n }\n\n // The API docs pages are shown in a frame by the dashboard's API tab.\n if (DOCS_PATTERNS.has(pattern)) reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n // Always the dashboard's policy: the app's own (core's security headers set one on every response) is not\n // written for this page and must not replace it.\n if (String(reply.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n reply.header(\n \"Content-Security-Policy\",\n DOCS_PATTERNS.has(pattern) ? DOCS_CSP : DASHBOARD_CSP,\n );\n }\n\n return payload;\n });\n\n // ---- Audit ----------------------------------------------------------\n instance.addHook(\"onResponse\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n const type = context?.rule?.audit;\n\n if (!context || !type || reply.statusCode < 200 || reply.statusCode > 299) return;\n\n const params = (request.params ?? {}) as Record<string, string | undefined>;\n const detail: Record<string, string | number | boolean | null> =\n type === \"explain.run\"\n ? { shapeId: params.shapeId ?? null }\n : type === \"panel.action\"\n ? {\n panel: context.pattern.split(\"/\")[2] ?? null,\n method: request.method,\n route: context.pattern,\n }\n : {};\n\n await auth.audit(type, { auth: context.authenticated, meta: context.meta, detail });\n });\n\n // ---- Errors ---------------------------------------------------------\n instance.setErrorHandler(\n (error: Error & { statusCode?: number; code?: string }, request, reply) => {\n // A malformed grant exchange (bad JSON, too large) answers like any unknown URL.\n if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) {\n return notFound(request, reply);\n }\n\n if (error instanceof DevtoolsApiError) {\n return reply.code(error.statusCode).send(error.toBody());\n }\n\n const status = error.statusCode;\n\n // The request itself was wrong (bad JSON, too large): say so in the dashboard's own shape.\n if (status !== undefined && status >= 400 && status < 500) {\n return reply\n .code(status)\n .send(\n error.code?.startsWith(\"FST_ERR_\")\n ? new DevtoolsApiError(\"input.invalid\").toBody()\n : { error: error.message },\n );\n }\n\n const ref = createErrorRef();\n\n // Never rate limited: the reference the browser shows must always be findable in the log. The route is\n // written relative to the dashboard path, which never reaches the log.\n deps.warn?.(\n `Devtools dashboard error ${ref} on ${request.method} ${devtoolsRequestContext(request)?.pattern ?? \"(dashboard route)\"}: ${error.message}`,\n );\n request.log.error({ ref, err: error }, \"devtools dashboard error\");\n\n return reply.code(500).send({\n error: DEVTOOLS_ERROR_MESSAGES[\"server.error\"],\n code: \"server.error\",\n ref,\n });\n },\n );\n\n // ---- Routes ---------------------------------------------------------\n registerUiAssets(instance, { notFound });\n registerAuthRoutes(instance, deps);\n\n instance.get(\"/api/panels\", async () => listPanelInfos(deps.panels, deps.builtInPanels));\n\n registerRequestsRoutes(instance, routes);\n registerRouteRoutes(instance, routes);\n registerInsightsRoutes(instance, routes);\n registerLogRoutes(instance, routes);\n registerShapeExplainRoute(instance, routes);\n registerPanelRoutes(instance, deps.panels, { notFound });\n\n share?.register(instance, notFound);\n\n if (enabledTabs.has(\"mail\")) registerMailRoutes(instance, routes);\n if (enabledTabs.has(\"ai\") || enabledTabs.has(\"agents\")) registerAiRoutes(instance, routes);\n if (AI_REPORT_TABS.some((tab) => enabledTabs.has(tab)))\n registerAiReportRoutes(instance, routes);\n if (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n","import { createHash } from \"node:crypto\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport type { DevtoolsDashboardState } from \"./types\";\n\n/** SHA-256 hex of a dashboard path: what `disabledPathHash` holds. */\nexport function hashDashboardPath(path: string): string {\n return createHash(\"sha256\").update(path).digest(\"hex\");\n}\n\n/**\n * The open/closed state with a `ttlMs` cache (default 5000). Open means the\n * dashboard is not disabled for this path and not locked. A failed read is\n * not cached and rejects, so the caller can fail closed.\n */\nexport function createDashboardState(\n store: DevtoolsStore,\n path: string,\n options: { ttlMs?: number; now?: () => number } = {},\n): DevtoolsDashboardState {\n const ttlMs = options.ttlMs ?? 5000;\n const now = options.now ?? Date.now;\n const pathHash = hashDashboardPath(path);\n let cached: { open: boolean; at: number } | null = null;\n let pending: Promise<boolean> | null = null;\n let generation = 0;\n\n const read = async (): Promise<boolean> => {\n const started = generation;\n const state = await store.state.read();\n const at = now();\n const disabled = state.disabled && state.disabledPathHash === pathHash;\n const locked = state.lockedUntil !== null && state.lockedUntil > at;\n const open = !disabled && !locked;\n\n if (started === generation) cached = { open, at };\n\n return open;\n };\n\n return {\n async isOpen() {\n if (cached !== null && now() - cached.at < ttlMs) return cached.open;\n\n if (pending === null) {\n const current = read().finally(() => {\n if (pending === current) pending = null;\n });\n\n pending = current;\n }\n\n return pending;\n },\n invalidate() {\n generation += 1;\n cached = null;\n pending = null;\n },\n };\n}\n"],"mappings":";;;;;;;;;AAIA,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,QAA6B,EAAE,MAAM,QAAQ;AACnD,MAAM,QAA6B,EAAE,MAAM,QAAQ;AAEnD,MAAM,WAAW,GAAG,YACjB;CAAE,MAAM;CAAW;AAAO;AAE7B,MAAM,YAAY;CAAC;CAAmB;CAAa;AAAY;;;;;;;;;AAU/D,SAAgB,sBACd,UACA,UAA+B,CAAC,GACL;CAC3B,MAAM,QACJ,QACA,KACA,QACA,WAC6B;EAAE;EAAQ;EAAK;EAAQ,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;CAAG;CAElF,MAAM,QAAmC;EAEvC,KAAK,OAAO,KAAK,MAAM;EACvB,KAAK,OAAO,iBAAiB,MAAM;EACnC,KAAK,OAAO,qBAAqB,MAAM;EACvC,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