@warlock.js/devtools 5.60.0 → 5.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/cjs/{boot-Dg5YZGGR.cjs → boot-D0nF-7w3.cjs} +6 -5
  3. package/cjs/{boot-Dg5YZGGR.cjs.map → boot-D0nF-7w3.cjs.map} +1 -1
  4. package/cjs/{capture-CBgONYhk.cjs → capture-D2k0GnBN.cjs} +21 -420
  5. package/cjs/capture-D2k0GnBN.cjs.map +1 -0
  6. package/cjs/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
  7. package/cjs/collector-BfC4v87v.cjs.map +1 -0
  8. package/cjs/errors-DNQ-g49I.cjs.map +1 -1
  9. package/cjs/{http-DCVCf44M.cjs → http-1nnpAoI7.cjs} +10 -4
  10. package/cjs/http-1nnpAoI7.cjs.map +1 -0
  11. package/cjs/index.cjs +1 -1
  12. package/cjs/{insights-CFof59kF.cjs → insights-COA3u37q.cjs} +53 -21
  13. package/cjs/insights-COA3u37q.cjs.map +1 -0
  14. package/cjs/query-shape-DShKQa0x.cjs +45 -0
  15. package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
  16. package/cjs/redact-DQ28mDzr.cjs +533 -0
  17. package/cjs/redact-DQ28mDzr.cjs.map +1 -0
  18. package/cjs/{server-CC5DpObz.cjs → server-DLT3uPef.cjs} +2 -2
  19. package/cjs/{server-CC5DpObz.cjs.map → server-DLT3uPef.cjs.map} +1 -1
  20. package/cjs/{src-VyOjEEAo.cjs → src-BZiSv8A1.cjs} +9 -6
  21. package/cjs/src-BZiSv8A1.cjs.map +1 -0
  22. package/cjs/{stream-route-DFHuIWgg.cjs → stream-route-B6WAjbPG.cjs} +5 -8
  23. package/cjs/stream-route-B6WAjbPG.cjs.map +1 -0
  24. package/esm/devtools-connector.d.mts.map +1 -1
  25. package/esm/devtools-connector.mjs +4 -1
  26. package/esm/devtools-connector.mjs.map +1 -1
  27. package/esm/index.d.mts +2 -2
  28. package/esm/production/boot.mjs +1 -0
  29. package/esm/production/boot.mjs.map +1 -1
  30. package/esm/production/contracts.d.mts +17 -4
  31. package/esm/production/contracts.d.mts.map +1 -1
  32. package/esm/production/contracts.mjs.map +1 -1
  33. package/esm/production/http/mount.mjs +8 -2
  34. package/esm/production/http/mount.mjs.map +1 -1
  35. package/esm/production/http/share.mjs.map +1 -1
  36. package/esm/production/index.d.mts +2 -2
  37. package/esm/production/insights/jobs.mjs +45 -11
  38. package/esm/production/insights/jobs.mjs.map +1 -1
  39. package/esm/server/panel-routes.mjs.map +1 -1
  40. package/esm/server/ui-assets.mjs +4 -7
  41. package/esm/server/ui-assets.mjs.map +1 -1
  42. package/esm/types.d.mts +2 -2
  43. package/llms-full.txt +22 -22
  44. package/package.json +8 -8
  45. package/skills/SKILL.md +22 -22
  46. package/ui/dashboard/assets/app.css +1 -1
  47. package/ui/dashboard/assets/app.js +2 -2
  48. package/ui/dashboard/build-info.json +7 -7
  49. package/cjs/capture-CBgONYhk.cjs.map +0 -1
  50. package/cjs/collector-CJbQbzzK.cjs.map +0 -1
  51. package/cjs/histogram-CkoVizdf.cjs +0 -102
  52. package/cjs/histogram-CkoVizdf.cjs.map +0 -1
  53. package/cjs/http-DCVCf44M.cjs.map +0 -1
  54. package/cjs/insights-CFof59kF.cjs.map +0 -1
  55. package/cjs/src-VyOjEEAo.cjs.map +0 -1
  56. package/cjs/stream-route-DFHuIWgg.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"devtools-connector.mjs","names":[],"sources":["../../../../../../../packages/devtools/src/devtools-connector.ts"],"sourcesContent":["/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createPanelErrorSource } from \"./panel-errors\";\nimport { checkDevtoolsPanels, loadDevtoolsPanels } from \"./panels\";\nimport { loadProcessPanel, processesDevtoolsPanel } from \"./process-panel\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport { DEVTOOLS_PRODUCTION_DEFAULTS } from \"./production/options\";\nimport type { DevtoolsRequestLogSource, DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./server\";\nimport { attachAgentTraceSource } from \"./sources/agent-trace-source\";\nimport { attachAiReports, DEVTOOLS_MOUNTED_KEY, loadAiFeed } from \"./ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport { createAiEvaluator } from \"./ai/reports/evaluate\";\nimport { recentAiFailures } from \"./ai/reports/runs\";\nimport { attachAiSource, describeAiUnavailable, toAiUnavailableView } from \"./sources/ai-source\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/**\n * The app's `src/config/devtools.ts`, or `{}` when there is none (or the\n * config store cannot be read, which must never stop the dev server).\n */\nfunction readConfiguredOptions(readConfig: () => { get(name: string): unknown }): DevtoolsOptions {\n try {\n const value = readConfig().get(\"devtools\");\n\n return value !== null && typeof value === \"object\" ? (value as DevtoolsOptions) : {};\n } catch {\n return {};\n }\n}\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Outside development, `boot()` checks `Application.runtimeStrategy` and\n * `devtools.production.enabled`: unless both say production, it logs one\n * warning and returns without mounting a route or subscribing to anything.\n * With `enabled: true` in production it starts the signed-in production\n * monitor (`bootProductionDevtools`), which refuses to boot when its\n * configuration is incomplete. In development it attaches every source\n * (tracing, queries, cache, mail, logs), loads the panels listed in the\n * `panels` option, then mounts the dashboard's routes on the HTTP server —\n * before it starts listening, the only point in the boot sequence where\n * mounting is possible (see `queue/src/dashboard-boot.ts` for the same\n * constraint).\n *\n * In development apps don't call this: `warlock dev` registers it\n * automatically when the package is installed (`warlock add devtools`). To\n * run the production monitor, list `devtoolsConnector()` in\n * `warlock.config.ts > connectors` (and keep the package in `dependencies`).\n * Options come from the app's `src/config/devtools.ts` (a plain object, no\n * import of this package); options passed here win over it.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const core = await import(\"@warlock.js/core\");\n const { Application, getHttpServer } = core;\n const { log } = await import(\"@warlock.js/logger\");\n\n const resolved = resolveDevtoolsOptions({\n ...readConfiguredOptions(() => core.config),\n ...options,\n });\n\n if (Application.runtimeStrategy === \"production\" && resolved.production?.enabled === true) {\n disposers.push(await bootProduction(core, log, resolved));\n active = true;\n\n return;\n }\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development unless devtools.production.enabled is true; it is not mounted\",\n );\n return;\n }\n\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const ai = await attachAiSource(resolved.maxRequests);\n disposers.push(ai.dispose);\n\n const agentTraces = await attachAgentTraceSource();\n disposers.push(agentTraces.dispose);\n\n const aiWiring = await wireDevelopmentAiReports(ai, resolved, core, log, disposers);\n const aiEvaluator = createAiEvaluator({\n agentTraces,\n warn: (message) => log.warn(\"devtools\", \"evaluate\", message),\n });\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n const requestLog = await findRequestLogSource();\n const processPanel = await loadProcessPanel();\n const builtIn = processesDevtoolsPanel(processPanel);\n // A panel that fails to load or reuses an id is reported and left out;\n // it never stops the dashboard or the app.\n const panelErrors = createPanelErrorSource();\n const panels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n errors: panelErrors.read,\n });\n\n const insightsWiring = await wireDevelopmentInsights(collector, resolved, log, disposers);\n\n panelErrors.bind(insightsWiring.insights ?? null);\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n ai,\n agentTraces,\n aiReports: aiWiring,\n aiEvaluator,\n ...(processPanel ? { processPanel } : {}),\n panels,\n options: resolved,\n ...insightsWiring,\n requestLog,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n warn: (message) => log.warn(\"devtools\", \"refused\", message),\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n getPostmanCollection: postmanBuilder\n ? async () => unwrapCollection(await postmanBuilder())\n : undefined,\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = {\n path: resolved.path,\n mode: \"development\",\n };\n disposers.push(() => {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n });\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n // A disposer may return a promise (the AI totals' final flush): wait for it, never let one fail the rest.\n const finished: Promise<unknown>[] = [];\n\n for (const dispose of disposers.splice(0)) {\n try {\n finished.push(Promise.resolve(dispose()).catch(() => undefined));\n } catch {\n // The remaining disposers still run.\n }\n }\n\n await Promise.all(finished);\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\ntype ConnectorLogger = {\n info: (module: string, action: string, message: string) => unknown;\n warn: (module: string, action: string, message: string) => unknown;\n error: (module: string, action: string, message: string) => unknown;\n};\n\n/**\n * Development: the statistics, resources, health and jobs behind the\n * Resources, Queries (statistics), Routes (statistics), Errors, Health and\n * Jobs tabs. Wrapped as a whole: when anything fails to start, one line is\n * logged and the dashboard mounts without insights (those tabs then say they\n * are not available). It never stops the dashboard.\n */\nasync function wireDevelopmentInsights(\n collector: ReturnType<typeof createCollector>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<Pick<MountDevtoolsRoutesDeps, \"instance\" | \"insights\" | \"explainShape\">> {\n const stops: DevtoolsDisposer[] = [];\n\n try {\n const capture = await import(\"./production/capture\");\n const insights = await import(\"./production/insights\");\n const instance = insights.createInstanceInfo();\n const queries = capture.createQueryStats({\n maxShapes: DEVTOOLS_PRODUCTION_DEFAULTS.maxShapes,\n instance: instance.id,\n });\n const routes = capture.createRouteStats({\n maxRoutes: DEVTOOLS_PRODUCTION_DEFAULTS.maxRoutes,\n instance: instance.id,\n });\n const errors = capture.createErrorGroups({\n maxGroups: DEVTOOLS_PRODUCTION_DEFAULTS.maxErrorGroups,\n });\n const logs = capture.createRecentLogs({ maxEntries: 200 });\n\n stops.push(\n capture.attachDevelopmentStats(collector, {\n queries,\n routes,\n errors,\n logs,\n nPlusOneThreshold: resolved.nPlusOneThreshold,\n }),\n );\n\n const resources = insights.createResourceMonitor();\n const health = insights.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insights.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insights.createJobsReader(),\n queries,\n routes,\n errors,\n logs,\n counters: null,\n });\n const explainShape = capture.createShapeExplainer({\n queries,\n executing: false,\n instance: instance.id,\n });\n\n disposers.push(...stops);\n\n return { instance, insights: insights.createLocalInsights(reporter), explainShape };\n } catch (error) {\n for (const stop of stops) {\n try {\n stop();\n } catch {\n // Cleanup after a failed start must not hide the reason.\n }\n }\n\n log.warn(\n \"devtools\",\n \"insights-failed\",\n `devtools' statistics could not start, so the Resources, Queries, Routes, Errors, Health and Jobs tabs are not available: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return {};\n }\n}\n\n/**\n * Starts this process's AI totals in development: loads the Panoptic feed and\n * writes hourly rollups to `storage/devtools/ai-rollups`. Never throws; a\n * failure leaves the Reports, Models and Errors pages answering why.\n */\nasync function wireDevelopmentAiReports(\n ai: Awaited<ReturnType<typeof attachAiSource>>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<NonNullable<MountDevtoolsRoutesDeps[\"aiReports\"]>> {\n const none = (reason: \"ai-missing\" | \"reports-off\") => ({\n ...toAiUnavailableView(describeAiUnavailable(reason)),\n async dispose() {},\n });\n\n try {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) return { ...loaded.unavailable, async dispose() {} };\n\n const reports = await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(resolved.ai, \"development\"),\n ...(typeof core.storagePath === \"function\"\n ? { directory: core.storagePath(\"devtools/ai-rollups\") }\n : {}),\n recentFailures: (filter) =>\n ai.available ? recentAiFailures(ai.store.query(), 50, filter) : [],\n warn: (message) => log.warn(\"devtools\", \"ai-reports\", message),\n });\n\n disposers.push(() => reports.dispose());\n\n return reports;\n } catch (error) {\n log.warn(\n \"devtools\",\n \"ai-reports\",\n `AI reports could not start: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return none(\"reports-off\");\n }\n}\n\n/**\n * Starts the production monitor: loads the panels in production mode and\n * hands everything to `bootProductionDevtools`, which refuses to boot (throws\n * `DevtoolsProductionConfigError`) when the configuration is incomplete.\n */\nasync function bootProduction(\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n): Promise<DevtoolsDisposer> {\n const { bootProductionDevtools } = await import(\"./production/boot\");\n const requestLog = await findRequestLogSource();\n // The Processes panel reads an app file; load it only when the project turned that tab on.\n const processPanel =\n resolved.production?.panels?.processes === true ? await loadProcessPanel() : undefined;\n const builtIn = processesDevtoolsPanel(processPanel);\n const panelErrors = createPanelErrorSource();\n const packagePanels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n mode: \"production\",\n errors: panelErrors.read,\n });\n // `warlock start` registers no development OpenAPI provider: the API tab, when turned on, builds its own.\n const { createProductionOpenApi } = await import(\"./production/openapi\");\n const openApi = createProductionOpenApi(core);\n\n return bootProductionDevtools({\n options: resolved,\n env: process.env,\n server: core.getHttpServer(),\n panels: [...checkDevtoolsPanels([builtIn]), ...packagePanels],\n routes: {\n ...(processPanel ? { processPanel } : {}),\n ...(requestLog ? { requestLog } : {}),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: openApi.getOpenApiDocument,\n getPostmanCollection: openApi.getPostmanCollection,\n },\n log,\n onInsights: (insights) => panelErrors.bind(insights),\n });\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n\ntype PostmanBuilder = () => Promise<unknown>;\n\n/**\n * Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.\n * Older cores do not export it; the route then answers 503. The lookup is\n * guarded because a namespace without the export may throw on access. Core is\n * imported lazily, like the OpenAPI document above.\n */\nasync function findPostmanBuilder(): Promise<PostmanBuilder | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const build = core.getDevelopmentPostmanCollection;\n\n return typeof build === \"function\" ? (build as PostmanBuilder) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Looks up core's persistent request log reader. Older cores do not export\n * it; the dashboard then shows the in-memory requests only. Core is imported\n * lazily, like the builders above.\n */\nasync function findRequestLogSource(): Promise<DevtoolsRequestLogSource | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const { listRequestLogs, getRequestLog, requestLogToCurl, compileRequestLogFilter } = core;\n\n if (\n typeof listRequestLogs !== \"function\" ||\n typeof getRequestLog !== \"function\" ||\n typeof requestLogToCurl !== \"function\" ||\n typeof compileRequestLogFilter !== \"function\"\n ) {\n return undefined;\n }\n\n return {\n list: (filter) => listRequestLogs(filter),\n get: (id) => getRequestLog(id),\n curl: (record, baseUrl) => requestLogToCurl(record, baseUrl),\n compile: (filter) => compileRequestLogFilter(filter),\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Core may return the collection itself or wrap it in `{ collection, warnings }`,\n * like the OpenAPI generator's `{ document, warnings }`.\n */\nfunction unwrapCollection(result: unknown): object {\n if (result && typeof result === \"object\" && \"collection\" in result) {\n return (result as { collection: object }).collection;\n }\n\n return result as object;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,8BAA8B;;;;;AAM3C,SAAS,sBAAsB,YAAmE;CAChG,IAAI;EACF,MAAM,QAAQ,WAAW,CAAC,CAAC,IAAI,UAAU;EAEzC,OAAO,UAAU,QAAQ,OAAO,UAAU,WAAY,QAA4B,CAAC;CACrF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,kBAAkB,UAAoC,CAAC,GAAc;CACnF,IAAI,SAAS;CACb,MAA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sourcesContent":["/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createPanelErrorSource } from \"./panel-errors\";\nimport { checkDevtoolsPanels, loadDevtoolsPanels } from \"./panels\";\nimport { loadProcessPanel, processesDevtoolsPanel } from \"./process-panel\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport { DEVTOOLS_PRODUCTION_DEFAULTS } from \"./production/options\";\nimport type { DevtoolsRequestLogSource, DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./server\";\nimport { attachAgentTraceSource } from \"./sources/agent-trace-source\";\nimport { attachAiReports, DEVTOOLS_MOUNTED_KEY, loadAiFeed } from \"./ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport { createAiEvaluator } from \"./ai/reports/evaluate\";\nimport { recentAiFailures } from \"./ai/reports/runs\";\nimport { attachAiSource, describeAiUnavailable, toAiUnavailableView } from \"./sources/ai-source\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/** The slot core reads to turn query events on; see `resolveDatabaseConnectionConfig`. */\nexport const DEVTOOLS_PRODUCTION_REQUESTED = Symbol.for(\"@warlock.js/devtools.productionRequested\");\n\n/**\n * The app's `src/config/devtools.ts`, or `{}` when there is none (or the\n * config store cannot be read, which must never stop the dev server).\n */\nfunction readConfiguredOptions(readConfig: () => { get(name: string): unknown }): DevtoolsOptions {\n try {\n const value = readConfig().get(\"devtools\");\n\n return value !== null && typeof value === \"object\" ? (value as DevtoolsOptions) : {};\n } catch {\n return {};\n }\n}\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Outside development, `boot()` checks `Application.runtimeStrategy` and\n * `devtools.production.enabled`: unless both say production, it logs one\n * warning and returns without mounting a route or subscribing to anything.\n * With `enabled: true` in production it starts the signed-in production\n * monitor (`bootProductionDevtools`), which refuses to boot when its\n * configuration is incomplete. In development it attaches every source\n * (tracing, queries, cache, mail, logs), loads the panels listed in the\n * `panels` option, then mounts the dashboard's routes on the HTTP server —\n * before it starts listening, the only point in the boot sequence where\n * mounting is possible (see `queue/src/dashboard-boot.ts` for the same\n * constraint).\n *\n * In development apps don't call this: `warlock dev` registers it\n * automatically when the package is installed (`warlock add devtools`). To\n * run the production monitor, list `devtoolsConnector()` in\n * `warlock.config.ts > connectors` (and keep the package in `dependencies`).\n * Options come from the app's `src/config/devtools.ts` (a plain object, no\n * import of this package); options passed here win over it.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n // Core reads this slot when it connects the database, so the monitor's\n // Queries tab gets query events without `devtools.production.enabled` in config.\n if (options.production?.enabled === true) {\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_PRODUCTION_REQUESTED] = true;\n }\n\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const core = await import(\"@warlock.js/core\");\n const { Application, getHttpServer } = core;\n const { log } = await import(\"@warlock.js/logger\");\n\n const resolved = resolveDevtoolsOptions({\n ...readConfiguredOptions(() => core.config),\n ...options,\n });\n\n if (Application.runtimeStrategy === \"production\" && resolved.production?.enabled === true) {\n disposers.push(await bootProduction(core, log, resolved));\n active = true;\n\n return;\n }\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development unless devtools.production.enabled is true; it is not mounted\",\n );\n return;\n }\n\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const ai = await attachAiSource(resolved.maxRequests);\n disposers.push(ai.dispose);\n\n const agentTraces = await attachAgentTraceSource();\n disposers.push(agentTraces.dispose);\n\n const aiWiring = await wireDevelopmentAiReports(ai, resolved, core, log, disposers);\n const aiEvaluator = createAiEvaluator({\n agentTraces,\n warn: (message) => log.warn(\"devtools\", \"evaluate\", message),\n });\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n const requestLog = await findRequestLogSource();\n const processPanel = await loadProcessPanel();\n const builtIn = processesDevtoolsPanel(processPanel);\n // A panel that fails to load or reuses an id is reported and left out;\n // it never stops the dashboard or the app.\n const panelErrors = createPanelErrorSource();\n const panels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n errors: panelErrors.read,\n });\n\n const insightsWiring = await wireDevelopmentInsights(collector, resolved, log, disposers);\n\n panelErrors.bind(insightsWiring.insights ?? null);\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n ai,\n agentTraces,\n aiReports: aiWiring,\n aiEvaluator,\n ...(processPanel ? { processPanel } : {}),\n panels,\n options: resolved,\n ...insightsWiring,\n requestLog,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n warn: (message) => log.warn(\"devtools\", \"refused\", message),\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n getPostmanCollection: postmanBuilder\n ? async () => unwrapCollection(await postmanBuilder())\n : undefined,\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = {\n path: resolved.path,\n mode: \"development\",\n };\n disposers.push(() => {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n });\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n // A disposer may return a promise (the AI totals' final flush): wait for it, never let one fail the rest.\n const finished: Promise<unknown>[] = [];\n\n for (const dispose of disposers.splice(0)) {\n try {\n finished.push(Promise.resolve(dispose()).catch(() => undefined));\n } catch {\n // The remaining disposers still run.\n }\n }\n\n await Promise.all(finished);\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\ntype ConnectorLogger = {\n info: (module: string, action: string, message: string) => unknown;\n warn: (module: string, action: string, message: string) => unknown;\n error: (module: string, action: string, message: string) => unknown;\n};\n\n/**\n * Development: the statistics, resources, health and jobs behind the\n * Resources, Queries (statistics), Routes (statistics), Errors, Health and\n * Jobs tabs. Wrapped as a whole: when anything fails to start, one line is\n * logged and the dashboard mounts without insights (those tabs then say they\n * are not available). It never stops the dashboard.\n */\nasync function wireDevelopmentInsights(\n collector: ReturnType<typeof createCollector>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<Pick<MountDevtoolsRoutesDeps, \"instance\" | \"insights\" | \"explainShape\">> {\n const stops: DevtoolsDisposer[] = [];\n\n try {\n const capture = await import(\"./production/capture\");\n const insights = await import(\"./production/insights\");\n const instance = insights.createInstanceInfo();\n const queries = capture.createQueryStats({\n maxShapes: DEVTOOLS_PRODUCTION_DEFAULTS.maxShapes,\n instance: instance.id,\n });\n const routes = capture.createRouteStats({\n maxRoutes: DEVTOOLS_PRODUCTION_DEFAULTS.maxRoutes,\n instance: instance.id,\n });\n const errors = capture.createErrorGroups({\n maxGroups: DEVTOOLS_PRODUCTION_DEFAULTS.maxErrorGroups,\n });\n const logs = capture.createRecentLogs({ maxEntries: 200 });\n\n stops.push(\n capture.attachDevelopmentStats(collector, {\n queries,\n routes,\n errors,\n logs,\n nPlusOneThreshold: resolved.nPlusOneThreshold,\n }),\n );\n\n const resources = insights.createResourceMonitor();\n const health = insights.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insights.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insights.createJobsReader(),\n queries,\n routes,\n errors,\n logs,\n counters: null,\n });\n const explainShape = capture.createShapeExplainer({\n queries,\n executing: false,\n instance: instance.id,\n });\n\n disposers.push(...stops);\n\n return { instance, insights: insights.createLocalInsights(reporter), explainShape };\n } catch (error) {\n for (const stop of stops) {\n try {\n stop();\n } catch {\n // Cleanup after a failed start must not hide the reason.\n }\n }\n\n log.warn(\n \"devtools\",\n \"insights-failed\",\n `devtools' statistics could not start, so the Resources, Queries, Routes, Errors, Health and Jobs tabs are not available: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return {};\n }\n}\n\n/**\n * Starts this process's AI totals in development: loads the Panoptic feed and\n * writes hourly rollups to `storage/devtools/ai-rollups`. Never throws; a\n * failure leaves the Reports, Models and Errors pages answering why.\n */\nasync function wireDevelopmentAiReports(\n ai: Awaited<ReturnType<typeof attachAiSource>>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<NonNullable<MountDevtoolsRoutesDeps[\"aiReports\"]>> {\n const none = (reason: \"ai-missing\" | \"reports-off\") => ({\n ...toAiUnavailableView(describeAiUnavailable(reason)),\n async dispose() {},\n });\n\n try {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) return { ...loaded.unavailable, async dispose() {} };\n\n const reports = await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(resolved.ai, \"development\"),\n ...(typeof core.storagePath === \"function\"\n ? { directory: core.storagePath(\"devtools/ai-rollups\") }\n : {}),\n recentFailures: (filter) =>\n ai.available ? recentAiFailures(ai.store.query(), 50, filter) : [],\n warn: (message) => log.warn(\"devtools\", \"ai-reports\", message),\n });\n\n disposers.push(() => reports.dispose());\n\n return reports;\n } catch (error) {\n log.warn(\n \"devtools\",\n \"ai-reports\",\n `AI reports could not start: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return none(\"reports-off\");\n }\n}\n\n/**\n * Starts the production monitor: loads the panels in production mode and\n * hands everything to `bootProductionDevtools`, which refuses to boot (throws\n * `DevtoolsProductionConfigError`) when the configuration is incomplete.\n */\nasync function bootProduction(\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n): Promise<DevtoolsDisposer> {\n const { bootProductionDevtools } = await import(\"./production/boot\");\n const requestLog = await findRequestLogSource();\n // The Processes panel reads an app file; load it only when the project turned that tab on.\n const processPanel =\n resolved.production?.panels?.processes === true ? await loadProcessPanel() : undefined;\n const builtIn = processesDevtoolsPanel(processPanel);\n const panelErrors = createPanelErrorSource();\n const packagePanels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n mode: \"production\",\n errors: panelErrors.read,\n });\n // `warlock start` registers no development OpenAPI provider: the API tab, when turned on, builds its own.\n const { createProductionOpenApi } = await import(\"./production/openapi\");\n const openApi = createProductionOpenApi(core);\n\n return bootProductionDevtools({\n options: resolved,\n env: process.env,\n server: core.getHttpServer(),\n panels: [...checkDevtoolsPanels([builtIn]), ...packagePanels],\n routes: {\n ...(processPanel ? { processPanel } : {}),\n ...(requestLog ? { requestLog } : {}),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: openApi.getOpenApiDocument,\n getPostmanCollection: openApi.getPostmanCollection,\n },\n log,\n onInsights: (insights) => panelErrors.bind(insights),\n });\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n\ntype PostmanBuilder = () => Promise<unknown>;\n\n/**\n * Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.\n * Older cores do not export it; the route then answers 503. The lookup is\n * guarded because a namespace without the export may throw on access. Core is\n * imported lazily, like the OpenAPI document above.\n */\nasync function findPostmanBuilder(): Promise<PostmanBuilder | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const build = core.getDevelopmentPostmanCollection;\n\n return typeof build === \"function\" ? (build as PostmanBuilder) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Looks up core's persistent request log reader. Older cores do not export\n * it; the dashboard then shows the in-memory requests only. Core is imported\n * lazily, like the builders above.\n */\nasync function findRequestLogSource(): Promise<DevtoolsRequestLogSource | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const { listRequestLogs, getRequestLog, requestLogToCurl, compileRequestLogFilter } = core;\n\n if (\n typeof listRequestLogs !== \"function\" ||\n typeof getRequestLog !== \"function\" ||\n typeof requestLogToCurl !== \"function\" ||\n typeof compileRequestLogFilter !== \"function\"\n ) {\n return undefined;\n }\n\n return {\n list: (filter) => listRequestLogs(filter),\n get: (id) => getRequestLog(id),\n curl: (record, baseUrl) => requestLogToCurl(record, baseUrl),\n compile: (filter) => compileRequestLogFilter(filter),\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Core may return the collection itself or wrap it in `{ collection, warnings }`,\n * like the OpenAPI generator's `{ document, warnings }`.\n */\nfunction unwrapCollection(result: unknown): object {\n if (result && typeof result === \"object\" && \"collection\" in result) {\n return (result as { collection: object }).collection;\n }\n\n return result as object;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,8BAA8B;;AAG3C,MAAa,gCAAgC,OAAO,IAAI,0CAA0C;;;;;AAMlG,SAAS,sBAAsB,YAAmE;CAChG,IAAI;EACF,MAAM,QAAQ,WAAW,CAAC,CAAC,IAAI,UAAU;EAEzC,OAAO,UAAU,QAAQ,OAAO,UAAU,WAAY,QAA4B,CAAC;CACrF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,kBAAkB,UAAoC,CAAC,GAAc;CAGnF,IAAI,QAAQ,YAAY,YAAY,MAClC,AAAC,WAAuC,iCAAiC;CAG3E,IAAI,SAAS;CACb,MAAM,YAAgC,CAAC;CAEvC,MAAM,YAAuB;EAC3B,MAAM;EACN;EAGA,gBAAgB;EAChB,gBAAgB;EAChB,MAAM,OAAO;GACX,MAAM,OAAO,MAAM,OAAO;GAC1B,MAAM,EAAE,aAAa,kBAAkB;GACvC,MAAM,EAAE,QAAQ,MAAM,OAAO;GAE7B,MAAM,WAAW,uBAAuB;IACtC,GAAG,4BAA4B,KAAK,MAAM;IAC1C,GAAG;GACL,CAAC;GAED,IAAI,YAAY,oBAAoB,gBAAgB,SAAS,YAAY,YAAY,MAAM;IACzF,UAAU,KAAK,MAAM,eAAe,MAAM,KAAK,QAAQ,CAAC;IACxD,SAAS;IAET;GACF;GAEA,IAAI,YAAY,oBAAoB,eAAe;IACjD,IAAI,KACF,YACA,YACA,6GACF;IACA;GACF;GAEA,MAAM,YAAY,gBAAgB,QAAQ;GAE1C,MAAM,aAAa,KAAK,iBAAiB,oBAAoB,WAAW,QAAQ,CAAC;GACjF,MAAM,aAAa,KAAK,eAAe,kBAAkB,SAAS,CAAC;GACnE,MAAM,aAAa,KAAK,eAAe,kB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AAsE;CACnF,IAAI;EAEF,MAAM,EAAE,iBAAiB,eAAe,kBAAkB,4BAA4B,MAD1C,OAAO;EAGnD,IACE,OAAO,oBAAoB,cAC3B,OAAO,kBAAkB,cACzB,OAAO,qBAAqB,cAC5B,OAAO,4BAA4B,YAEnC;EAGF,OAAO;GACL,OAAO,WAAW,gBAAgB,MAAM;GACxC,MAAM,OAAO,cAAc,EAAE;GAC7B,OAAO,QAAQ,YAAY,iBAAiB,QAAQ,OAAO;GAC3D,UAAU,WAAW,wBAAwB,MAAM;EACrD;CACF,QAAQ;EACN;CACF;AACF;;;;;AAMA,SAAS,iBAAiB,QAAyB;CACjD,IAAI,UAAU,OAAO,WAAW,YAAY,gBAAgB,QAC1D,OAAQ,OAAkC;CAG5C,OAAO;AACT"}
package/esm/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { DevtoolsAgentRun, DevtoolsAgentTraceEvent } from "./sources/agent-trace-source.mjs";
2
- import { DEVTOOLS_AI_ERROR_CATEGORIES, DEVTOOLS_AI_LATENCY_BUCKETS_MS, DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_FAILURE_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_SHARE_LABEL_MAX, DevtoolsAccountView, DevtoolsAiBreakdownRow, DevtoolsAiCostTotals, DevtoolsAiErrorCategory, DevtoolsAiErrorGroup, DevtoolsAiErrorsView, DevtoolsAiEvaluatePrompt, DevtoolsAiEvaluateRequest, DevtoolsAiEvaluateResult, DevtoolsAiEvaluateView, DevtoolsAiFailedRun, DevtoolsAiFilterOptions, DevtoolsAiLatencyTotals, DevtoolsAiModelRow, DevtoolsAiModelsView, DevtoolsAiPricingState, DevtoolsAiRangePreset, DevtoolsAiRatePoint, DevtoolsAiReportView, DevtoolsAiResolvedRange, DevtoolsAiRunGroup, DevtoolsAiRunRow, DevtoolsAiRunsView, DevtoolsAiSeriesSet, DevtoolsAiTokenTotals, DevtoolsAiTotals, DevtoolsAiUnavailableReasonView, DevtoolsAiUnavailableView, DevtoolsAiUsageView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsCreatedShare, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsShareCreateInput, DevtoolsShareList, DevtoolsShareOpenAnswer, DevtoolsShareStatus, DevtoolsShareView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./production/contracts.mjs";
2
+ import { DEVTOOLS_AI_ERROR_CATEGORIES, DEVTOOLS_AI_LATENCY_BUCKETS_MS, DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_FAILURE_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_SHARE_LABEL_MAX, DevtoolsAccountView, DevtoolsAiBreakdownRow, DevtoolsAiCostTotals, DevtoolsAiErrorCategory, DevtoolsAiErrorGroup, DevtoolsAiErrorsView, DevtoolsAiEvaluatePrompt, DevtoolsAiEvaluateRequest, DevtoolsAiEvaluateResult, DevtoolsAiEvaluateView, DevtoolsAiFailedRun, DevtoolsAiFilterOptions, DevtoolsAiLatencyTotals, DevtoolsAiModelRow, DevtoolsAiModelsView, DevtoolsAiPricingState, DevtoolsAiRangePreset, DevtoolsAiRatePoint, DevtoolsAiReportView, DevtoolsAiResolvedRange, DevtoolsAiRunGroup, DevtoolsAiRunRow, DevtoolsAiRunsView, DevtoolsAiSeriesSet, DevtoolsAiTokenTotals, DevtoolsAiTotals, DevtoolsAiUnavailableReasonView, DevtoolsAiUnavailableView, DevtoolsAiUsageView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsCreatedShare, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsQueueInfo, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsScheduleRun, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsShareCreateInput, DevtoolsShareList, DevtoolsShareOpenAnswer, DevtoolsShareStatus, DevtoolsShareView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./production/contracts.mjs";
3
3
  import { DevtoolsAiOptions } from "./ai/types.mjs";
4
4
  import { DevtoolsAiEvent, DevtoolsAiRun } from "./sources/ai-source.mjs";
5
5
  import { DevtoolsBackground, DevtoolsCacheOperation, DevtoolsCallerLocation, DevtoolsCollector, DevtoolsDisposer, DevtoolsLogEntry, DevtoolsMail, DevtoolsMailAttachment, DevtoolsMailSummary, DevtoolsOptions, DevtoolsPanel, DevtoolsPanelEntry, DevtoolsPanelErrorSummary, DevtoolsPanelExport, DevtoolsPanelFactoryContext, DevtoolsPanelFiles, DevtoolsPanelMethod, DevtoolsPanelRequest, DevtoolsPanelRoute, DevtoolsPanelShare, DevtoolsPanels, DevtoolsPhase, DevtoolsProductionOptions, DevtoolsQuery, DevtoolsRequest, DevtoolsRequestDetail, DevtoolsRequestSummary, DevtoolsStreamEvent, DevtoolsWarning, ResolvedDevtoolsOptions } from "./types.mjs";
6
6
  import { devtoolsConnector } from "./devtools-connector.mjs";
7
7
  import { DEVTOOLS_PANEL_TOKENS } from "./panel-tokens.mjs";
8
- export { type DEVTOOLS_AI_ERROR_CATEGORIES, type DEVTOOLS_AI_LATENCY_BUCKETS_MS, type DEVTOOLS_BUILT_IN_PANELS, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_PANEL_TOKENS, type DEVTOOLS_SHARE_LABEL_MAX, type DevtoolsAccountView, type DevtoolsAgentRun, type DevtoolsAgentTraceEvent, type DevtoolsAiBreakdownRow, type DevtoolsAiCostTotals, type DevtoolsAiErrorCategory, type DevtoolsAiErrorGroup, type DevtoolsAiErrorsView, type DevtoolsAiEvaluatePrompt, type DevtoolsAiEvaluateRequest, type DevtoolsAiEvaluateResult, type DevtoolsAiEvaluateView, type DevtoolsAiEvent, type DevtoolsAiFailedRun, type DevtoolsAiFilterOptions, type DevtoolsAiLatencyTotals, type DevtoolsAiModelRow, type DevtoolsAiModelsView, type DevtoolsAiOptions, type DevtoolsAiPricingState, type DevtoolsAiRangePreset, type DevtoolsAiRatePoint, type DevtoolsAiReportView, type DevtoolsAiResolvedRange, type DevtoolsAiRun, type DevtoolsAiRunGroup, type DevtoolsAiRunRow, type DevtoolsAiRunsView, type DevtoolsAiSeriesSet, type DevtoolsAiTokenTotals, type DevtoolsAiTotals, type DevtoolsAiUnavailableReasonView, type DevtoolsAiUnavailableView, type DevtoolsAiUsageView, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBackground, type DevtoolsBuiltInPanelId, type DevtoolsCacheOperation, type DevtoolsCallerLocation, type DevtoolsCaptureCounters, type DevtoolsCollector, type DevtoolsCreatedInvite, type DevtoolsCreatedShare, type DevtoolsDisposer, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogEntry, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMail, type DevtoolsMailAttachment, type DevtoolsMailSummary, type DevtoolsMode, type DevtoolsOptions, type DevtoolsPanel, type DevtoolsPanelEntry, type DevtoolsPanelErrorSummary, type DevtoolsPanelExport, type DevtoolsPanelFactoryContext, type DevtoolsPanelFiles, type DevtoolsPanelInfo, type DevtoolsPanelMethod, type DevtoolsPanelRequest, type DevtoolsPanelRoute, type DevtoolsPanelShare, type DevtoolsPanels, type DevtoolsPasswordSource, type DevtoolsPhase, type DevtoolsProductionOptions, type DevtoolsQuery, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsRequest, type DevtoolsRequestDetail, type DevtoolsRequestSummary, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsShareCreateInput, type DevtoolsShareList, type DevtoolsShareOpenAnswer, type DevtoolsShareStatus, type DevtoolsShareView, type DevtoolsStreamEvent, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type DevtoolsWarning, type ResolvedDevtoolsOptions, devtoolsConnector };
8
+ export { type DEVTOOLS_AI_ERROR_CATEGORIES, type DEVTOOLS_AI_LATENCY_BUCKETS_MS, type DEVTOOLS_BUILT_IN_PANELS, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_PANEL_TOKENS, type DEVTOOLS_SHARE_LABEL_MAX, type DevtoolsAccountView, type DevtoolsAgentRun, type DevtoolsAgentTraceEvent, type DevtoolsAiBreakdownRow, type DevtoolsAiCostTotals, type DevtoolsAiErrorCategory, type DevtoolsAiErrorGroup, type DevtoolsAiErrorsView, type DevtoolsAiEvaluatePrompt, type DevtoolsAiEvaluateRequest, type DevtoolsAiEvaluateResult, type DevtoolsAiEvaluateView, type DevtoolsAiEvent, type DevtoolsAiFailedRun, type DevtoolsAiFilterOptions, type DevtoolsAiLatencyTotals, type DevtoolsAiModelRow, type DevtoolsAiModelsView, type DevtoolsAiOptions, type DevtoolsAiPricingState, type DevtoolsAiRangePreset, type DevtoolsAiRatePoint, type DevtoolsAiReportView, type DevtoolsAiResolvedRange, type DevtoolsAiRun, type DevtoolsAiRunGroup, type DevtoolsAiRunRow, type DevtoolsAiRunsView, type DevtoolsAiSeriesSet, type DevtoolsAiTokenTotals, type DevtoolsAiTotals, type DevtoolsAiUnavailableReasonView, type DevtoolsAiUnavailableView, type DevtoolsAiUsageView, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBackground, type DevtoolsBuiltInPanelId, type DevtoolsCacheOperation, type DevtoolsCallerLocation, type DevtoolsCaptureCounters, type DevtoolsCollector, type DevtoolsCreatedInvite, type DevtoolsCreatedShare, type DevtoolsDisposer, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogEntry, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMail, type DevtoolsMailAttachment, type DevtoolsMailSummary, type DevtoolsMode, type DevtoolsOptions, type DevtoolsPanel, type DevtoolsPanelEntry, type DevtoolsPanelErrorSummary, type DevtoolsPanelExport, type DevtoolsPanelFactoryContext, type DevtoolsPanelFiles, type DevtoolsPanelInfo, type DevtoolsPanelMethod, type DevtoolsPanelRequest, type DevtoolsPanelRoute, type DevtoolsPanelShare, type DevtoolsPanels, type DevtoolsPasswordSource, type DevtoolsPhase, type DevtoolsProductionOptions, type DevtoolsQuery, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsQueueInfo, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsRequest, type DevtoolsRequestDetail, type DevtoolsRequestSummary, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsScheduleRun, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsShareCreateInput, type DevtoolsShareList, type DevtoolsShareOpenAnswer, type DevtoolsShareStatus, type DevtoolsShareView, type DevtoolsStreamEvent, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type DevtoolsWarning, type ResolvedDevtoolsOptions, devtoolsConnector };
@@ -180,6 +180,7 @@ async function bootProductionDevtools(input) {
180
180
  builtInPanels: builtIn,
181
181
  state,
182
182
  warn,
183
+ ...typeof core.answerUnknownUrl === "function" ? { answerUnknownUrl: core.answerUnknownUrl } : {},
183
184
  hmac: (value) => crypto.hmac(value)
184
185
  });
185
186
  publishMounted(production.path);
@@ -1 +1 @@
1
- {"version":3,"file":"boot.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/boot.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport {\n attachAiReports,\n DEVTOOLS_MOUNTED_KEY,\n type DevtoolsAiReports,\n loadAiFeed,\n} from \"../ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"../ai/options\";\nimport { type MountedDevtoolsPanel, productionPanels } from \"../panels\";\nimport type { MountDevtoolsRoutesDeps } from \"../server/types\";\nimport type { ResolvedDevtoolsOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport type { DevtoolsInsights } from \"./insights/types\";\nimport { resolveProductionOptions } from \"./options\";\nimport { describeAiUnavailable, toAiUnavailableView } from \"../sources/ai-source\";\n\n/** What the connector hands production boot. */\nexport type BootProductionDevtoolsInput = {\n options: ResolvedDevtoolsOptions;\n env: Readonly<Record<string, string | undefined>>;\n server: FastifyInstance;\n /** Package panels loaded with `mode: \"production\"` (not yet filtered). */\n panels: readonly MountedDevtoolsPanel[];\n /** The route deps the connector builds for development, reused (requestLog, listRoutes, ai, …). */\n routes: Omit<MountDevtoolsRoutesDeps, \"collector\" | \"options\" | \"isDevelopment\">;\n /** Reads one config value (`encryption.key`); defaults to core's `config.get`. */\n readConfig?: (key: string) => unknown;\n /** Called once the shared insights exist (panels read captured error counts through them). */\n onInsights?: (insights: DevtoolsInsights) => void;\n log: {\n info(module: string, action: string, message: string): unknown;\n warn(module: string, action: string, message: string): unknown;\n error(module: string, action: string, message: string): unknown;\n };\n};\n\nconst AI_REPORT_TABS: readonly string[] = [\"ai-reports\", \"ai-models\", \"ai-errors\"];\n\n/** Tells other packages (Panoptic) that devtools is mounted here and where. */\nfunction publishMounted(path: string): void {\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = { path, mode: \"production\" };\n}\n\nfunction clearMounted(): void {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n}\n\n/**\n * Loads the AI feed and starts this process's rollup writer (every process of\n * a deployment adds into the same table). Never throws: a failure leaves the\n * AI report tabs answering their unavailable view.\n */\nasync function attachProductionAi(\n options: ResolvedDevtoolsOptions,\n warn: (message: string) => void,\n): Promise<{ feedAvailable: boolean; reports: DevtoolsAiReports }> {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) {\n return { feedAvailable: false, reports: { ...loaded.unavailable, async dispose() {} } };\n }\n\n try {\n return {\n feedAvailable: true,\n reports: await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(options.ai, \"production\"),\n warn,\n }),\n };\n } catch (error) {\n warn(`AI reports could not start: ${error instanceof Error ? error.message : String(error)}`);\n\n return {\n feedAvailable: true,\n reports: { ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")), async dispose() {} },\n };\n }\n}\n\n/** `/ops-…`: the first part of the path, enough to recognise it and not enough to use it. */\nexport function maskDashboardPath(path: string): string {\n const match = /^\\/[A-Za-z]{1,8}-/.exec(path);\n\n return `${match ? match[0] : \"/\"}…`;\n}\n\n/** The key core encrypts with: 64 hex characters. */\nfunction hasEncryptionKey(value: unknown): boolean {\n return typeof value === \"string\" && /^[0-9a-fA-F]{64}$/.test(value);\n}\n\n/**\n * Starts the production monitor, in this order: resolve options (env) →\n * check `encryption.key` (DT006) → cascade store (DT005) → `store.verify()`\n * (DT008) → `ensureFirstAdmin()` (DT003/DT004) → instance info → capture\n * (attach hooks) → resource monitor, health history, jobs reader → local\n * reporter → report writer → shared insights → `excludeFromRequestLog(path)`\n * → mount. Logs one line with the path masked (`/ops-…`), never the full path.\n * Any `DevtoolsProductionConfigError` propagates: the app does not boot.\n *\n * Returns the disposer the connector calls at shutdown (flush samples, stop\n * timers, detach hooks).\n */\nexport async function bootProductionDevtools(\n input: BootProductionDevtoolsInput,\n): Promise<() => Promise<void>> {\n const { options, env, server, log } = input;\n const production = resolveProductionOptions(options.production, env);\n const core = await import(\"@warlock.js/core\");\n const readConfig = input.readConfig ?? ((key: string) => core.config.get(key));\n\n if (!hasEncryptionKey(readConfig(\"encryption.key\"))) {\n throw new DevtoolsProductionConfigError(\"DT006\");\n }\n\n const [{ createCascadeStore }, authModule, captureModule, insightsModule, httpModule] =\n await Promise.all([\n import(\"./store\"),\n import(\"./auth\"),\n import(\"./capture\"),\n import(\"./insights\"),\n import(\"./http\"),\n ]);\n\n const store = await createCascadeStore({ shares: production.share.enabled });\n\n await store.verify();\n\n const warn = (message: string): void => {\n log.warn(\"devtools\", \"production\", message);\n };\n if (production.twoFactor === \"off\") {\n warn(\n 'Two-factor sign-in is off for the dashboard (production.twoFactor is \"off\"): anyone with a password can sign in. Set it to \"admins\" or \"everyone\" to require an authenticator app or passkey.',\n );\n }\n\n const instance = insightsModule.createInstanceInfo();\n const [crypto, passkeys] = await Promise.all([\n authModule.defaultDevtoolsCrypto(),\n authModule.loadDevtoolsPasskeys(),\n ]);\n const auth = authModule.createDevtoolsAuth({\n store,\n options: production,\n instance,\n crypto,\n passkeys,\n warn,\n });\n\n await auth.ensureFirstAdmin();\n\n const isDashboardPath = (path: string): boolean =>\n path === production.path || path.startsWith(`${production.path}/`);\n const capture = captureModule.createProductionCapture({\n options,\n production,\n instance,\n store,\n isDashboardPath,\n warn,\n });\n const stops: (() => unknown)[] = [];\n\n try {\n stops.push(await capture.attach());\n\n const resources = insightsModule.createResourceMonitor();\n const health = insightsModule.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insightsModule.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insightsModule.createJobsReader(),\n queries: capture.queries,\n routes: capture.routes,\n errors: capture.errors,\n logs: capture.logs,\n counters: () => capture.counters(),\n });\n const writer = insightsModule.startReportWriter({ reporter, store, production, warn });\n\n stops.push(() => writer.stop());\n\n const insights = insightsModule.createSharedInsights({\n store,\n reporter,\n sampleRate: production.sampleRate,\n });\n input.onInsights?.(insights);\n\n const state = httpModule.createDashboardState(store, production.path);\n const { builtIn: shownTabs, panels } = productionPanels(input.panels, production.panels);\n\n // The AI report tabs are listed only when the app has the AI feed (Panoptic), unless the project turned one on.\n // With every report tab turned off, no totals are written (and no missing-table warning is logged).\n const aiWiring = shownTabs.some((tab) => AI_REPORT_TABS.includes(tab))\n ? await attachProductionAi(options, warn)\n : {\n feedAvailable: false,\n reports: {\n ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")),\n async dispose() {},\n },\n };\n const builtIn = aiWiring.feedAvailable\n ? shownTabs\n : shownTabs.filter((tab) => !AI_REPORT_TABS.includes(tab) || production.panels[tab] === true);\n\n stops.push(() => aiWiring.reports.dispose());\n\n // The dashboard's own requests are not worth a line in the request log, and its sign-in bodies must not reach it.\n if (typeof core.excludeFromRequestLog === \"function\") {\n stops.push(core.excludeFromRequestLog(production.path));\n }\n\n // Mail previews exist only when the project turned that tab on.\n if (builtIn.includes(\"mail\")) {\n const { attachMailSource } = await import(\"../sources/mail-source\");\n\n stops.push(await attachMailSource(capture.collector));\n }\n\n httpModule.mountProductionDevtools(server, {\n routes: {\n ...input.routes,\n aiReports: aiWiring.reports,\n collector: capture.collector,\n options,\n isDevelopment: () => false,\n },\n production,\n store,\n auth,\n capture,\n insights,\n instance,\n panels,\n builtInPanels: builtIn,\n state,\n warn,\n hmac: (value) => crypto.hmac(value),\n });\n\n publishMounted(production.path);\n stops.push(clearMounted);\n\n log.info(\n \"devtools\",\n \"ready\",\n `devtools production monitor mounted at ${maskDashboardPath(production.path)} (DEVTOOLS_PATH)`,\n );\n } catch (error) {\n for (const stop of stops.splice(0).reverse()) {\n try {\n void Promise.resolve(stop()).catch(() => undefined);\n } catch {\n // Cleanup after a failed boot must not hide the real error.\n }\n }\n\n void capture.dispose().catch(() => undefined);\n\n throw error;\n }\n\n // Returns the promise of the stops so the connector can wait for the final AI totals flush.\n return () => {\n const finished: Promise<unknown>[] = [];\n\n for (const stop of stops.splice(0).reverse()) {\n try {\n finished.push(Promise.resolve(stop()).catch(() => undefined));\n } catch {\n // Shutdown continues past a failing step.\n }\n }\n\n finished.push(capture.dispose().catch(() => undefined));\n\n return Promise.all(finished).then(() => undefined);\n };\n}\n"],"mappings":";;;;;;;;AAoCA,MAAM,iBAAoC;CAAC;CAAc;CAAa;AAAW;;AAGjF,SAAS,eAAe,MAAoB;CAC1C,AAAC,WAAuC,wBAAwB;EAAE;EAAM,MAAM;CAAa;AAC7F;AAEA,SAAS,eAAqB;CAC5B,OAAQ,WAAuC;AACjD;;;;;;AAOA,eAAe,mBACb,SACA,MACiE;CACjE,MAAM,SAAS,MAAM,WAAW;CAEhC,IAAI,iBAAiB,QACnB,OAAO;EAAE,eAAe;EAAO,SAAS;GAAE,GAAG,OAAO;GAAa,MAAM,UAAU,CAAC;EAAE;CAAE;CAGxF,IAAI;EACF,OAAO;GACL,eAAe;GACf,SAAS,MAAM,gBAAgB;IAC7B,MAAM,OAAO;IACb,SAAS,yBAAyB,QAAQ,IAAI,YAAY;IAC1D;GACF,CAAC;EACH;CACF,SAAS,OAAO;EACd,KAAK,+BAA+B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;EAE5F,OAAO;GACL,eAAe;GACf,SAAS;IAAE,GAAG,oBAAoB,sBAAsB,aAAa,CAAC;IAAG,MAAM,UAAU,CAAC;GAAE;EAC9F;CACF;AACF;;AAGA,SAAgB,kBAAkB,MAA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EAAE,qBAAqB,MAAM,OAAO;GAE1C,MAAM,KAAK,MAAM,iBAAiB,QAAQ,SAAS,CAAC;EACtD;EAEA,WAAW,wBAAwB,QAAQ;GACzC,QAAQ;IACN,GAAG,MAAM;IACT,WAAW,SAAS;IACpB,WAAW,QAAQ;IACnB;IACA,qBAAqB;GACvB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,eAAe;GACf;GACA;GACA,OAAO,UAAU,OAAO,KAAK,KAAK;EACpC,CAAC;EAED,eAAe,WAAW,IAAI;EAC9B,MAAM,KAAK,YAAY;EAEvB,IAAI,KACF,YACA,SACA,0CAA0C,kBAAkB,WAAW,IAAI,EAAE,iBAC/E;CACF,SAAS,OAAO;EACd,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,AAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS;EACpD,QAAQ,CAER;EAGF,AAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS;EAE5C,MAAM;CACR;CAGA,aAAa;EACX,MAAM,WAA+B,CAAC;EAEtC,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,SAAS,KAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS,CAAC;EAC9D,QAAQ,CAER;EAGF,SAAS,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS,CAAC;EAEtD,OAAO,QAAQ,IAAI,QAAQ,CAAC,CAAC,WAAW,MAAS;CACnD;AACF"}
1
+ {"version":3,"file":"boot.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/boot.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport {\n attachAiReports,\n DEVTOOLS_MOUNTED_KEY,\n type DevtoolsAiReports,\n loadAiFeed,\n} from \"../ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"../ai/options\";\nimport { type MountedDevtoolsPanel, productionPanels } from \"../panels\";\nimport type { MountDevtoolsRoutesDeps } from \"../server/types\";\nimport type { ResolvedDevtoolsOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport type { DevtoolsInsights } from \"./insights/types\";\nimport { resolveProductionOptions } from \"./options\";\nimport { describeAiUnavailable, toAiUnavailableView } from \"../sources/ai-source\";\n\n/** What the connector hands production boot. */\nexport type BootProductionDevtoolsInput = {\n options: ResolvedDevtoolsOptions;\n env: Readonly<Record<string, string | undefined>>;\n server: FastifyInstance;\n /** Package panels loaded with `mode: \"production\"` (not yet filtered). */\n panels: readonly MountedDevtoolsPanel[];\n /** The route deps the connector builds for development, reused (requestLog, listRoutes, ai, …). */\n routes: Omit<MountDevtoolsRoutesDeps, \"collector\" | \"options\" | \"isDevelopment\">;\n /** Reads one config value (`encryption.key`); defaults to core's `config.get`. */\n readConfig?: (key: string) => unknown;\n /** Called once the shared insights exist (panels read captured error counts through them). */\n onInsights?: (insights: DevtoolsInsights) => void;\n log: {\n info(module: string, action: string, message: string): unknown;\n warn(module: string, action: string, message: string): unknown;\n error(module: string, action: string, message: string): unknown;\n };\n};\n\nconst AI_REPORT_TABS: readonly string[] = [\"ai-reports\", \"ai-models\", \"ai-errors\"];\n\n/** Tells other packages (Panoptic) that devtools is mounted here and where. */\nfunction publishMounted(path: string): void {\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = { path, mode: \"production\" };\n}\n\nfunction clearMounted(): void {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n}\n\n/**\n * Loads the AI feed and starts this process's rollup writer (every process of\n * a deployment adds into the same table). Never throws: a failure leaves the\n * AI report tabs answering their unavailable view.\n */\nasync function attachProductionAi(\n options: ResolvedDevtoolsOptions,\n warn: (message: string) => void,\n): Promise<{ feedAvailable: boolean; reports: DevtoolsAiReports }> {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) {\n return { feedAvailable: false, reports: { ...loaded.unavailable, async dispose() {} } };\n }\n\n try {\n return {\n feedAvailable: true,\n reports: await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(options.ai, \"production\"),\n warn,\n }),\n };\n } catch (error) {\n warn(`AI reports could not start: ${error instanceof Error ? error.message : String(error)}`);\n\n return {\n feedAvailable: true,\n reports: { ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")), async dispose() {} },\n };\n }\n}\n\n/** `/ops-…`: the first part of the path, enough to recognise it and not enough to use it. */\nexport function maskDashboardPath(path: string): string {\n const match = /^\\/[A-Za-z]{1,8}-/.exec(path);\n\n return `${match ? match[0] : \"/\"}…`;\n}\n\n/** The key core encrypts with: 64 hex characters. */\nfunction hasEncryptionKey(value: unknown): boolean {\n return typeof value === \"string\" && /^[0-9a-fA-F]{64}$/.test(value);\n}\n\n/**\n * Starts the production monitor, in this order: resolve options (env) →\n * check `encryption.key` (DT006) → cascade store (DT005) → `store.verify()`\n * (DT008) → `ensureFirstAdmin()` (DT003/DT004) → instance info → capture\n * (attach hooks) → resource monitor, health history, jobs reader → local\n * reporter → report writer → shared insights → `excludeFromRequestLog(path)`\n * → mount. Logs one line with the path masked (`/ops-…`), never the full path.\n * Any `DevtoolsProductionConfigError` propagates: the app does not boot.\n *\n * Returns the disposer the connector calls at shutdown (flush samples, stop\n * timers, detach hooks).\n */\nexport async function bootProductionDevtools(\n input: BootProductionDevtoolsInput,\n): Promise<() => Promise<void>> {\n const { options, env, server, log } = input;\n const production = resolveProductionOptions(options.production, env);\n const core = await import(\"@warlock.js/core\");\n const readConfig = input.readConfig ?? ((key: string) => core.config.get(key));\n\n if (!hasEncryptionKey(readConfig(\"encryption.key\"))) {\n throw new DevtoolsProductionConfigError(\"DT006\");\n }\n\n const [{ createCascadeStore }, authModule, captureModule, insightsModule, httpModule] =\n await Promise.all([\n import(\"./store\"),\n import(\"./auth\"),\n import(\"./capture\"),\n import(\"./insights\"),\n import(\"./http\"),\n ]);\n\n const store = await createCascadeStore({ shares: production.share.enabled });\n\n await store.verify();\n\n const warn = (message: string): void => {\n log.warn(\"devtools\", \"production\", message);\n };\n if (production.twoFactor === \"off\") {\n warn(\n 'Two-factor sign-in is off for the dashboard (production.twoFactor is \"off\"): anyone with a password can sign in. Set it to \"admins\" or \"everyone\" to require an authenticator app or passkey.',\n );\n }\n\n const instance = insightsModule.createInstanceInfo();\n const [crypto, passkeys] = await Promise.all([\n authModule.defaultDevtoolsCrypto(),\n authModule.loadDevtoolsPasskeys(),\n ]);\n const auth = authModule.createDevtoolsAuth({\n store,\n options: production,\n instance,\n crypto,\n passkeys,\n warn,\n });\n\n await auth.ensureFirstAdmin();\n\n const isDashboardPath = (path: string): boolean =>\n path === production.path || path.startsWith(`${production.path}/`);\n const capture = captureModule.createProductionCapture({\n options,\n production,\n instance,\n store,\n isDashboardPath,\n warn,\n });\n const stops: (() => unknown)[] = [];\n\n try {\n stops.push(await capture.attach());\n\n const resources = insightsModule.createResourceMonitor();\n const health = insightsModule.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insightsModule.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insightsModule.createJobsReader(),\n queries: capture.queries,\n routes: capture.routes,\n errors: capture.errors,\n logs: capture.logs,\n counters: () => capture.counters(),\n });\n const writer = insightsModule.startReportWriter({ reporter, store, production, warn });\n\n stops.push(() => writer.stop());\n\n const insights = insightsModule.createSharedInsights({\n store,\n reporter,\n sampleRate: production.sampleRate,\n });\n input.onInsights?.(insights);\n\n const state = httpModule.createDashboardState(store, production.path);\n const { builtIn: shownTabs, panels } = productionPanels(input.panels, production.panels);\n\n // The AI report tabs are listed only when the app has the AI feed (Panoptic), unless the project turned one on.\n // With every report tab turned off, no totals are written (and no missing-table warning is logged).\n const aiWiring = shownTabs.some((tab) => AI_REPORT_TABS.includes(tab))\n ? await attachProductionAi(options, warn)\n : {\n feedAvailable: false,\n reports: {\n ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")),\n async dispose() {},\n },\n };\n const builtIn = aiWiring.feedAvailable\n ? shownTabs\n : shownTabs.filter((tab) => !AI_REPORT_TABS.includes(tab) || production.panels[tab] === true);\n\n stops.push(() => aiWiring.reports.dispose());\n\n // The dashboard's own requests are not worth a line in the request log, and its sign-in bodies must not reach it.\n if (typeof core.excludeFromRequestLog === \"function\") {\n stops.push(core.excludeFromRequestLog(production.path));\n }\n\n // Mail previews exist only when the project turned that tab on.\n if (builtIn.includes(\"mail\")) {\n const { attachMailSource } = await import(\"../sources/mail-source\");\n\n stops.push(await attachMailSource(capture.collector));\n }\n\n httpModule.mountProductionDevtools(server, {\n routes: {\n ...input.routes,\n aiReports: aiWiring.reports,\n collector: capture.collector,\n options,\n isDevelopment: () => false,\n },\n production,\n store,\n auth,\n capture,\n insights,\n instance,\n panels,\n builtInPanels: builtIn,\n state,\n warn,\n ...(typeof core.answerUnknownUrl === \"function\"\n ? { answerUnknownUrl: core.answerUnknownUrl }\n : {}),\n hmac: (value) => crypto.hmac(value),\n });\n\n publishMounted(production.path);\n stops.push(clearMounted);\n\n log.info(\n \"devtools\",\n \"ready\",\n `devtools production monitor mounted at ${maskDashboardPath(production.path)} (DEVTOOLS_PATH)`,\n );\n } catch (error) {\n for (const stop of stops.splice(0).reverse()) {\n try {\n void Promise.resolve(stop()).catch(() => undefined);\n } catch {\n // Cleanup after a failed boot must not hide the real error.\n }\n }\n\n void capture.dispose().catch(() => undefined);\n\n throw error;\n }\n\n // Returns the promise of the stops so the connector can wait for the final AI totals flush.\n return () => {\n const finished: Promise<unknown>[] = [];\n\n for (const stop of stops.splice(0).reverse()) {\n try {\n finished.push(Promise.resolve(stop()).catch(() => undefined));\n } catch {\n // Shutdown continues past a failing step.\n }\n }\n\n finished.push(capture.dispose().catch(() => undefined));\n\n return Promise.all(finished).then(() => undefined);\n };\n}\n"],"mappings":";;;;;;;;AAoCA,MAAM,iBAAoC;CAAC;CAAc;CAAa;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,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,AAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS;EACpD,QAAQ,CAER;EAGF,AAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS;EAE5C,MAAM;CACR;CAGA,aAAa;EACX,MAAM,WAA+B,CAAC;EAEtC,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,SAAS,KAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS,CAAC;EAC9D,QAAQ,CAER;EAGF,SAAS,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS,CAAC;EAEtD,OAAO,QAAQ,IAAI,QAAQ,CAAC,CAAC,WAAW,MAAS;CACnD;AACF"}
@@ -186,6 +186,16 @@ export type DevtoolsScheduleInfo = {
186
186
  lastError: string | null;
187
187
  runs: number;
188
188
  failures: number;
189
+ /** The latest runs, newest first (at most 10). Absent when the scheduler keeps no history. */
190
+ recentRuns?: DevtoolsScheduleRun[];
191
+ };
192
+ /** One recorded run of a scheduled job; the error is a message, never a stack. */
193
+ export type DevtoolsScheduleRun = {
194
+ startedAt: number;
195
+ durationMs: number;
196
+ outcome: "success" | "failed" | "skipped";
197
+ error?: string;
198
+ skipReason?: string;
189
199
  };
190
200
  /** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */
191
201
  export type DevtoolsJobsReport = {
@@ -195,10 +205,13 @@ export type DevtoolsJobsReport = {
195
205
  };
196
206
  schedules: DevtoolsScheduleInfo[];
197
207
  /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */
198
- queues: {
199
- name: string;
200
- counts: Record<string, number>;
201
- }[];
208
+ queues: DevtoolsQueueInfo[];
209
+ };
210
+ /** One queue's job counts. `countsAvailable: false` when the active driver cannot count. */
211
+ export type DevtoolsQueueInfo = {
212
+ name: string;
213
+ counts: Record<string, number>;
214
+ countsAvailable?: boolean;
202
215
  };
203
216
  /** What the capture did since the process started. */
204
217
  export type DevtoolsCaptureCounters = {
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/production/contracts.ts"],"mappings":";;;;;;;;;;YAcY;;YAGA;;;;;YAMA;;YAQA;;YAOA;;EAEV;;EAEA;EACA;EACA;;EAEA;EACA;;EAEA;EACA;;;;;;;;qBAaW;;YAKD;;EAEV;EACA;EACA;EACA;;;YAQU;;EAEV;;EAEA;EACA;EACA;EACA;EACA;EACA,WAAW;;EAEX;IAAY;IAAkB;;;EAE9B;IACE;IACA;IACA;IACA;IACA;;EAEF;EACA;;EAEA;;;YAIU;EACV;EACA;EACA;EACA;;;YAIU;;EAEV;EACA;EACA;EACA;;EAEA;EACA,WAAW;;EAEX,QAAQ;EACR;IAAW;IAAoB;IAAY;IAA0B;;;;YAI3D;;EAEV;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;;YAIU;EACV;EACA;EACA;;EAEA;EACA;EACA;;;YAQU;EACV;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;;YAIU,2BAA2B;EACrC;EACA;;EAEA,UAAU;IAEN;IAAe;;;;YAKT;EACV;EACA;EACA,QAAQ;;EAER;IAAW;IAAY;IAAwB;;;;YAIrC;EACV;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;YAIU;EACV;IAAa;IAAoB;;EACjC,WAAW;;EAEX;IAAU;IAAc,QAAQ;;;;YAItB;EACV;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;;EAEA;;;;;;;YAQU;EACV,UAAU;EACV;EACA;IAAa,UAAU;IAA0B,SAAS;;;EAE1D,SAAS;;EAET,QAAQ;;EAER,QAAQ;;EAER,MAAM;EACN,QAAQ;EACR,MAAM;EACN,SAAS;;;;;;YAWC;EAC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;;EAER;;;YAIU;EACV;;EAEA;EACA;;;YAIU,uBACR;EAEE;EACA,OAAO;;EAEP;IAAiB;IAAc;;;EAE/B;EACA,QAAQ;EACR,UAAU;;EAEV,aAAa;;EAEb,QAAQ;EACR,WAAW;;EAEX,WAAW;EACX,WAAW;;EAEX;EACA,SAAS;;EAET;EACA;;;YAIM;;YAGA;;EAEV;EACA;EACA;EACA,QAAQ;EACR,SAAS;;EAET;;EAEA;;EAEA;;EAEA;;;YAIU,uBACR;EAEE;EACA,OAAO;EACP,QAAQ;;EAER,QAAQ;;EAER,aAAa;EACb,SAAS;EACT;EACA;;;YAIM;;qBAYC;;YAaD;EACV,UAAU;;EAEV;EACA;;EAEA;EACA;;EAEA;IAAW;IAAa;;EACxB;IAAW;IAAa;;;;YAId;EACV;;EAEA;;EAEA;EACA;EACA,UAAU;;EAEV;;EAEA;EACA;EACA;;;YAIU,uBACR;EAEE;EACA,OAAO;EACP,QAAQ;EACR,UAAU;;EAEV;;EAEA,QAAQ;;EAER,UAAU;;EAEV,QAAQ;EACR,SAAS;EACT;EACA;;;YAIM;EACV;EACA;EACA;EACA;EACA;;EAEA;;;YAIU;EACV;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA,OAAO;;EAEP;EACA;;EAEA;EACA;EACA;EACA;;;YAIU;EACV;EACA;EACA;EACA;EACA;EACA;;EAEA;;;YAIU,qBACR;EAEE;;EAEA,MAAM;;EAEN,QAAQ;EACR;;IAEE;IACA;;IAEA;;IAEA;IACA;IACA;;;EAGF;;;YAIM;;EAEV;;EAEA;;EAEA;EACA;;EAEA;EACA;;;YAIU,yBACR;EAEE;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;;YAIH;;EAEV;;EAEA;;EAEA;;;YAIU;;EAEV;EACA;;EAEA;EACA"}
1
+ {"version":3,"file":"contracts.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/production/contracts.ts"],"mappings":";;;;;;;;;;YAcY;;YAGA;;;;;YAMA;;YAQA;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,WAAW;EACX,WAAW;;EAEX;EACA,SAAS;;EAET;EACA;;;YAIM;;YAGA;;EAEV;EACA;EACA;EACA,QAAQ;EACR,SAAS;;EAET;;EAEA;;EAEA;;EAEA;;;YAIU,uBACR;EAEE;EACA,OAAO;EACP,QAAQ;;EAER,QAAQ;;EAER,aAAa;EACb,SAAS;EACT;EACA;;;YAIM;;qBAYC;;YAaD;EACV,UAAU;;EAEV;EACA;;EAEA;EACA;;EAEA;IAAW;IAAa;;EACxB;IAAW;IAAa;;;;YAId;EACV;;EAEA;;EAEA;EACA;EACA,UAAU;;EAEV;;EAEA;EACA;EACA;;;YAIU,uBACR;EAEE;EACA,OAAO;EACP,QAAQ;EACR,UAAU;;EAEV;;EAEA,QAAQ;;EAER,UAAU;;EAEV,QAAQ;EACR,SAAS;EACT;EACA;;;YAIM;EACV;EACA;EACA;EACA;EACA;;EAEA;;;YAIU;EACV;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA,OAAO;;EAEP;EACA;;EAEA;EACA;EACA;EACA;;;YAIU;EACV;EACA;EACA;EACA;EACA;EACA;;EAEA;;;YAIU,qBACR;EAEE;;EAEA,MAAM;;EAEN,QAAQ;EACR;;IAEE;IACA;;IAEA;;IAEA;IACA;IACA;;;EAGF;;;YAIM;;EAEV;;EAEA;;EAEA;EACA;;EAEA;EACA;;;YAIU,yBACR;EAEE;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;;YAIH;;EAEV;;EAEA;;EAEA;;;YAIU;;EAEV;EACA;;EAEA;EACA"}
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/contracts.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: { name: string; counts: Record<string, number> }[];\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n *\n * The AI section (`ai-reports`, `ai`, `agents`, `ai-models`, `ai-errors`,\n * `ai-evaluate`) sits under \"AI\" in the sidebar. `ai` keeps its id (it is the\n * Runs page) so existing links and `production.panels.ai` keep working. In\n * production the three report tabs show only when the AI feed is available\n * (Panoptic loads), unless `production.panels` turns one on explicitly.\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai-reports\", title: \"Reports\", production: true },\n { id: \"ai\", title: \"Runs\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"ai-models\", title: \"Models\", production: true },\n { id: \"ai-errors\", title: \"Errors\", production: true },\n { id: \"ai-evaluate\", title: \"Evaluate\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n /** The installed `@warlock.js/core` version; `null` when signed out or not found. */\n warlockVersion: string | null;\n /** The app's own `package.json` name and version (nothing else is read); `null` when signed out or not found. */\n app: { name: string; version: string } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"ai.range-invalid\"\n | \"ai.evaluate-unavailable\"\n | \"ai.prompt-not-found\"\n | \"ai.evaluate-failed\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n\n// ---------------------------------------------------------------------------\n// AI section: reports, runs, models, errors, evaluate\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets of the AI rollups.\n * Model calls take seconds, so these differ from `DEVTOOLS_LATENCY_BUCKETS_MS`.\n * A histogram has one more count than this list: the last counts everything\n * above five minutes. Fixed bounds make rollups from several processes add up\n * exactly. Changing them is a breaking change of the stored rollups.\n */\nexport const DEVTOOLS_AI_LATENCY_BUCKETS_MS = [\n 250, 500, 1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 30000, 45000, 60000, 120000, 300000,\n] as const;\n\n/** The date-range presets of the Reports, Models and Errors pages. */\nexport type DevtoolsAiRangePreset = \"24h\" | \"7d\" | \"30d\";\n\n/** The range a report covers, after the server aligned it to its buckets. */\nexport type DevtoolsAiResolvedRange = {\n preset: DevtoolsAiRangePreset | \"custom\";\n /** Inclusive start, on an hour boundary. */\n from: number;\n /** Exclusive end, on an hour boundary. */\n to: number;\n /** Bucket width of the charts: 1 hour, 6 hours or 1 day. */\n stepMs: number;\n /** The browser's offset from UTC (minutes east), used to align day buckets. */\n utcOffsetMinutes: number;\n};\n\n/** Why an AI page has nothing to show; `title`, `message` and `command` are written for the page. */\nexport type DevtoolsAiUnavailableReasonView =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** The answer of any AI route that cannot serve its data. */\nexport type DevtoolsAiUnavailableView = {\n available: false;\n reason: DevtoolsAiUnavailableReasonView;\n title: string;\n message: string;\n /** A command or config line to copy; `null` when there is none. */\n command: string | null;\n /** The load error and versions for `panoptic-failed`; otherwise `null`. */\n detail: string | null;\n};\n\n/** Token counts. `input` is the whole prompt (cache reads and writes included) on every provider. */\nexport type DevtoolsAiTokenTotals = {\n input: number;\n output: number;\n /** Prompt tokens read from the provider's cache (part of `input`). */\n cached: number;\n /** Prompt tokens written to the provider's cache (part of `input`). */\n cacheWrite: number;\n /** Reasoning tokens (part of `output`). */\n reasoning: number;\n};\n\n/**\n * Estimated cost. `estimatedUsd` sums only runs whose model has pricing; runs\n * that used tokens on a model without pricing are counted in `unpricedRuns`\n * and `unpricedTokens`, never as zero cost.\n */\nexport type DevtoolsAiCostTotals = {\n estimatedUsd: number;\n pricedRuns: number;\n unpricedRuns: number;\n unpricedTokens: number;\n};\n\n/** Latency from the bucketed histogram: each figure is a bucket's upper bound (`null` with no runs). */\nexport type DevtoolsAiLatencyTotals = {\n p50Ms: number | null;\n p95Ms: number | null;\n meanMs: number | null;\n};\n\n/** Totals over a range (or one row of a breakdown). */\nexport type DevtoolsAiTotals = {\n runs: number;\n completed: number;\n failed: number;\n /** Runs that stopped early: `incomplete` and `max-iterations`. */\n incomplete: number;\n cancelled: number;\n /** `(failed + incomplete) / runs`, from 0 to 1; 0 with no runs. Cancelled runs are not errors. */\n errorRate: number;\n tokens: DevtoolsAiTokenTotals;\n cost: DevtoolsAiCostTotals;\n latency: DevtoolsAiLatencyTotals;\n /** Runs where a `fallbackModel()` chain answered from a later model at least once. */\n fallbackRuns: number;\n /** Runs where the provider refused at least once (finish reason `refusal` or a content filter). */\n refusals: number;\n};\n\n/**\n * Time series for a stacked chart: `values[i]` belongs to `buckets[i]`. At\n * most five named series; the rest are summed into one `other` series.\n */\nexport type DevtoolsAiSeriesSet = {\n /** Bucket starts, oldest first. */\n buckets: number[];\n series: {\n /** Stable identity (`provider/model`, an agent name, a category); the UI keys colours on it. */\n key: string;\n label: string;\n values: number[];\n /** `true` for the summed \"Other\" series. */\n other: boolean;\n }[];\n};\n\n/** One bucket of the error-rate line. */\nexport type DevtoolsAiRatePoint = {\n at: number;\n runs: number;\n /** Failed plus incomplete runs. */\n errors: number;\n /** `errors / runs`; `null` for a bucket without runs (the line has a gap there). */\n rate: number | null;\n};\n\n/** A row of the top agents or top models table. */\nexport type DevtoolsAiBreakdownRow = {\n /** The agent name, or `provider/model`. */\n key: string;\n label: string;\n /** The provider for a model row; `null` for an agent row. */\n provider: string | null;\n totals: DevtoolsAiTotals;\n /** Share of the range's estimated cost, 0 to 1 (share of runs when nothing was priced). */\n share: number;\n};\n\n/** The filter values present in a range, for the filter row. */\nexport type DevtoolsAiFilterOptions = {\n agents: string[];\n /** `provider/model` keys. */\n models: string[];\n providers: string[];\n};\n\n/** `GET api/ai/reports`. */\nexport type DevtoolsAiReportView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n /** The period of the same length just before `range`. */\n previousRange: { from: number; to: number };\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** Estimated USD per bucket, by model (top five plus Other). */\n costByModel: DevtoolsAiSeriesSet;\n /** Tokens per bucket: series `uncached`, `cached`, `output`. */\n tokens: DevtoolsAiSeriesSet;\n errorRate: DevtoolsAiRatePoint[];\n /** Up to 10 rows, highest estimated cost first (most runs when nothing was priced). */\n topAgents: DevtoolsAiBreakdownRow[];\n topModels: DevtoolsAiBreakdownRow[];\n /** `provider/model` keys that used tokens without pricing in the range. */\n unpricedModels: string[];\n filters: DevtoolsAiFilterOptions;\n /** `true` when `@warlock.js/ai` observes nothing, so new runs are not counted. */\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Whether a model's runs carried pricing in the range; `no-tokens` when no run used tokens. */\nexport type DevtoolsAiPricingState = \"set\" | \"missing\" | \"partial\" | \"no-tokens\";\n\n/** One row of the Models page. */\nexport type DevtoolsAiModelRow = {\n /** `provider/model`. */\n key: string;\n model: string;\n provider: string;\n totals: DevtoolsAiTotals;\n pricing: DevtoolsAiPricingState;\n /** Estimated USD per priced run; `null` when no run was priced. */\n costPerRunUsd: number | null;\n /** `fallbackRuns / runs`, 0 to 1. */\n fallbackRate: number;\n /** Agents that used the model, most runs first (at most 5). */\n agents: string[];\n /** Start of the last hour with a run. */\n lastSeenAt: number;\n};\n\n/** `GET api/ai/models`. */\nexport type DevtoolsAiModelsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n /** Most runs first. */\n models: DevtoolsAiModelRow[];\n /** Runs per bucket by model (top five plus Other). */\n runsByModel: DevtoolsAiSeriesSet;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** How failed runs are grouped on the Errors page. */\nexport type DevtoolsAiErrorCategory =\n | \"rate-limit\"\n | \"timeout\"\n | \"refusal\"\n | \"provider\"\n | \"budget\"\n | \"tool\"\n | \"schema\"\n | \"incomplete\"\n | \"other\";\n\n/** Every category, in the order the Errors page lists them. */\nexport const DEVTOOLS_AI_ERROR_CATEGORIES = [\n \"rate-limit\",\n \"timeout\",\n \"refusal\",\n \"provider\",\n \"budget\",\n \"tool\",\n \"schema\",\n \"incomplete\",\n \"other\",\n] as const satisfies readonly DevtoolsAiErrorCategory[];\n\n/** One category of failed runs. */\nexport type DevtoolsAiErrorGroup = {\n category: DevtoolsAiErrorCategory;\n /** \"Rate limit\", \"Timeout\", \"Refusal\", \"Provider error\", \"Budget\", \"Tool failed\", \"Invalid output\", \"Incomplete\", \"Other\". */\n label: string;\n count: number;\n /** Share of all failed runs in the range, 0 to 1. */\n share: number;\n previousCount: number;\n /** At most 5 each, most first. */\n byModel: { key: string; count: number }[];\n byAgent: { key: string; count: number }[];\n};\n\n/** A recent failed run (development only: production keeps no run details). */\nexport type DevtoolsAiFailedRun = {\n traceId: string;\n /** The agent span that failed. */\n agent: string;\n /** `provider/model`, or `null` when unreported. */\n model: string | null;\n status: string;\n category: DevtoolsAiErrorCategory;\n /** The error code (`PROVIDER_RATE_LIMIT`) or error name. */\n code: string | null;\n /** The error message, secrets scrubbed, at most 300 characters. */\n message: string | null;\n endedAt: number;\n requestId: string | null;\n};\n\n/** `GET api/ai/errors`. */\nexport type DevtoolsAiErrorsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n /** Categories with at least one failed run, most first. */\n groups: DevtoolsAiErrorGroup[];\n /** Failed runs per bucket by category (top five plus Other). */\n overTime: DevtoolsAiSeriesSet;\n /** Newest first, at most 50; `null` in production. */\n recent: DevtoolsAiFailedRun[] | null;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Usage of one run as the Runs page shows it. */\nexport type DevtoolsAiUsageView = {\n input: number;\n output: number;\n total: number;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n /** `false` when `input` excludes cache tokens (the provider reports them on top). */\n inputIncludesCache: boolean | null;\n};\n\n/** One row of the Runs page (a Panoptic trace, content-free). */\nexport type DevtoolsAiRunRow = {\n traceId: string;\n requestId: string | null;\n sessionId: string | null;\n name: string;\n /** The root span type: `agent`, `workflow`, `supervisor`, … */\n type: string;\n status: string;\n startedAt: string;\n duration: number;\n usage: DevtoolsAiUsageView;\n /** Estimated USD; `null` when the run carried no pricing. */\n cost: number | null;\n models: string[];\n /** `promptName@promptVersion` of the root agent, or `null`. */\n promptKey: string | null;\n toolCalls: number;\n retries: number;\n incomplete: boolean;\n};\n\n/** A group of the Runs page (`groupBy=session|prompt|type`). */\nexport type DevtoolsAiRunGroup = {\n key: string;\n label: string;\n runs: number;\n failed: number;\n estimatedCostUsd: number;\n p95Ms: number | null;\n /** Trace ids of the group, newest first (at most 50). */\n traceIds: string[];\n};\n\n/** `GET api/ai/runs`. */\nexport type DevtoolsAiRunsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Newest first, at most `limit` (default 200). */\n runs: DevtoolsAiRunRow[];\n /** `null` unless `groupBy` was given. */\n groups: DevtoolsAiRunGroup[] | null;\n stats: {\n /** Runs matching the filter (before `limit`). */\n count: number;\n failed: number;\n /** Priced runs only. */\n estimatedCostUsd: number;\n /** Runs that used tokens on a model without pricing (not in `estimatedCostUsd`). */\n unpricedRuns: number;\n p50Ms: number | null;\n p95Ms: number | null;\n };\n /** How many traces the dashboard keeps (`maxRequests`). */\n capacity: number;\n };\n\n/** A distinct system prompt seen in recent agent runs (the Evaluate picker). */\nexport type DevtoolsAiEvaluatePrompt = {\n /** The prompt's hash from the agent trace. */\n hash: string;\n /** Agents that used it, most recent first. */\n agents: string[];\n /** The newest run that carried its text. */\n runId: string;\n lastSeenAt: string;\n /** The first 200 characters. */\n preview: string;\n length: number;\n};\n\n/** `GET api/ai/evaluate`. */\nexport type DevtoolsAiEvaluateView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Whether `panoptic.evaluate` (or `panoptic.dashboard.evaluate`) has a judge model. */\n configured: boolean;\n /** The judge model as `provider/name`; `null` when not configured. */\n judge: string | null;\n /** The configured default grading instructions; `\"\"` when none. */\n instructions: string;\n /** Newest first, at most 50. */\n prompts: DevtoolsAiEvaluatePrompt[];\n };\n\n/** `POST api/ai/evaluate` body: exactly one of `runId` and `systemPrompt`. */\nexport type DevtoolsAiEvaluateRequest = {\n /** An agent run whose system prompt text is kept. */\n runId?: string;\n /** A pasted prompt, 1 to 100,000 characters. */\n systemPrompt?: string;\n /** Overrides the configured instructions for this run; at most 4,000 characters. */\n instructions?: string;\n};\n\n/** `POST api/ai/evaluate` answer. */\nexport type DevtoolsAiEvaluateResult = {\n /** 0 to 1; `null` when the judge returned no score. */\n score: number | null;\n issues: string[];\n /** The judge model as `provider/name`. */\n judge: string;\n durationMs: number;\n};\n"],"mappings":";;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;;;;;;;;;;AAsXA,MAAa,2BAA2B;CACtC;EAAE,IAAI;EAAY,OAAO;EAAY,YAAY;CAAK;CACtD;EAAE,IAAI;EAAW,OAAO;EAAW,YAAY;CAAK;CACpD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAa,OAAO;EAAa,YAAY;CAAK;CACxD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAM;CAC/C;EAAE,IAAI;EAAc,OAAO;EAAW,YAAY;CAAK;CACvD;EAAE,IAAI;EAAM,OAAO;EAAQ,YAAY;CAAM;CAC7C;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAM;CACnD;EAAE,IAAI;EAAa,OAAO;EAAU,YAAY;CAAK;CACrD;EAAE,IAAI;EAAa,OAAO;EAAU,YAAY;CAAK;CACrD;EAAE,IAAI;EAAe,OAAO;EAAY,YAAY;CAAM;CAC1D;EAAE,IAAI;EAAO,OAAO;EAAO,YAAY;CAAM;AAC/C;;AAwMA,MAAa,+BAA6D;CACxE;CACA;CACA;AACF;;;;;;;;AAwFA,MAAa,iCAAiC;CAC5C;CAAK;CAAK;CAAM;CAAM;CAAM;CAAM;CAAM;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAQ;AAC5F;;AAuNA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
1
+ {"version":3,"file":"contracts.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/contracts.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n /** The latest runs, newest first (at most 10). Absent when the scheduler keeps no history. */\n recentRuns?: DevtoolsScheduleRun[];\n};\n\n/** One recorded run of a scheduled job; the error is a message, never a stack. */\nexport type DevtoolsScheduleRun = {\n startedAt: number;\n durationMs: number;\n outcome: \"success\" | \"failed\" | \"skipped\";\n error?: string;\n skipReason?: string;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: DevtoolsQueueInfo[];\n};\n\n/** One queue's job counts. `countsAvailable: false` when the active driver cannot count. */\nexport type DevtoolsQueueInfo = {\n name: string;\n counts: Record<string, number>;\n countsAvailable?: boolean;\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n *\n * The AI section (`ai-reports`, `ai`, `agents`, `ai-models`, `ai-errors`,\n * `ai-evaluate`) sits under \"AI\" in the sidebar. `ai` keeps its id (it is the\n * Runs page) so existing links and `production.panels.ai` keep working. In\n * production the three report tabs show only when the AI feed is available\n * (Panoptic loads), unless `production.panels` turns one on explicitly.\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai-reports\", title: \"Reports\", production: true },\n { id: \"ai\", title: \"Runs\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"ai-models\", title: \"Models\", production: true },\n { id: \"ai-errors\", title: \"Errors\", production: true },\n { id: \"ai-evaluate\", title: \"Evaluate\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n /** The installed `@warlock.js/core` version; `null` when signed out or not found. */\n warlockVersion: string | null;\n /** The app's own `package.json` name and version (nothing else is read); `null` when signed out or not found. */\n app: { name: string; version: string } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"ai.range-invalid\"\n | \"ai.evaluate-unavailable\"\n | \"ai.prompt-not-found\"\n | \"ai.evaluate-failed\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n\n// ---------------------------------------------------------------------------\n// AI section: reports, runs, models, errors, evaluate\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets of the AI rollups.\n * Model calls take seconds, so these differ from `DEVTOOLS_LATENCY_BUCKETS_MS`.\n * A histogram has one more count than this list: the last counts everything\n * above five minutes. Fixed bounds make rollups from several processes add up\n * exactly. Changing them is a breaking change of the stored rollups.\n */\nexport const DEVTOOLS_AI_LATENCY_BUCKETS_MS = [\n 250, 500, 1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 30000, 45000, 60000, 120000, 300000,\n] as const;\n\n/** The date-range presets of the Reports, Models and Errors pages. */\nexport type DevtoolsAiRangePreset = \"24h\" | \"7d\" | \"30d\";\n\n/** The range a report covers, after the server aligned it to its buckets. */\nexport type DevtoolsAiResolvedRange = {\n preset: DevtoolsAiRangePreset | \"custom\";\n /** Inclusive start, on an hour boundary. */\n from: number;\n /** Exclusive end, on an hour boundary. */\n to: number;\n /** Bucket width of the charts: 1 hour, 6 hours or 1 day. */\n stepMs: number;\n /** The browser's offset from UTC (minutes east), used to align day buckets. */\n utcOffsetMinutes: number;\n};\n\n/** Why an AI page has nothing to show; `title`, `message` and `command` are written for the page. */\nexport type DevtoolsAiUnavailableReasonView =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** The answer of any AI route that cannot serve its data. */\nexport type DevtoolsAiUnavailableView = {\n available: false;\n reason: DevtoolsAiUnavailableReasonView;\n title: string;\n message: string;\n /** A command or config line to copy; `null` when there is none. */\n command: string | null;\n /** The load error and versions for `panoptic-failed`; otherwise `null`. */\n detail: string | null;\n};\n\n/** Token counts. `input` is the whole prompt (cache reads and writes included) on every provider. */\nexport type DevtoolsAiTokenTotals = {\n input: number;\n output: number;\n /** Prompt tokens read from the provider's cache (part of `input`). */\n cached: number;\n /** Prompt tokens written to the provider's cache (part of `input`). */\n cacheWrite: number;\n /** Reasoning tokens (part of `output`). */\n reasoning: number;\n};\n\n/**\n * Estimated cost. `estimatedUsd` sums only runs whose model has pricing; runs\n * that used tokens on a model without pricing are counted in `unpricedRuns`\n * and `unpricedTokens`, never as zero cost.\n */\nexport type DevtoolsAiCostTotals = {\n estimatedUsd: number;\n pricedRuns: number;\n unpricedRuns: number;\n unpricedTokens: number;\n};\n\n/** Latency from the bucketed histogram: each figure is a bucket's upper bound (`null` with no runs). */\nexport type DevtoolsAiLatencyTotals = {\n p50Ms: number | null;\n p95Ms: number | null;\n meanMs: number | null;\n};\n\n/** Totals over a range (or one row of a breakdown). */\nexport type DevtoolsAiTotals = {\n runs: number;\n completed: number;\n failed: number;\n /** Runs that stopped early: `incomplete` and `max-iterations`. */\n incomplete: number;\n cancelled: number;\n /** `(failed + incomplete) / runs`, from 0 to 1; 0 with no runs. Cancelled runs are not errors. */\n errorRate: number;\n tokens: DevtoolsAiTokenTotals;\n cost: DevtoolsAiCostTotals;\n latency: DevtoolsAiLatencyTotals;\n /** Runs where a `fallbackModel()` chain answered from a later model at least once. */\n fallbackRuns: number;\n /** Runs where the provider refused at least once (finish reason `refusal` or a content filter). */\n refusals: number;\n};\n\n/**\n * Time series for a stacked chart: `values[i]` belongs to `buckets[i]`. At\n * most five named series; the rest are summed into one `other` series.\n */\nexport type DevtoolsAiSeriesSet = {\n /** Bucket starts, oldest first. */\n buckets: number[];\n series: {\n /** Stable identity (`provider/model`, an agent name, a category); the UI keys colours on it. */\n key: string;\n label: string;\n values: number[];\n /** `true` for the summed \"Other\" series. */\n other: boolean;\n }[];\n};\n\n/** One bucket of the error-rate line. */\nexport type DevtoolsAiRatePoint = {\n at: number;\n runs: number;\n /** Failed plus incomplete runs. */\n errors: number;\n /** `errors / runs`; `null` for a bucket without runs (the line has a gap there). */\n rate: number | null;\n};\n\n/** A row of the top agents or top models table. */\nexport type DevtoolsAiBreakdownRow = {\n /** The agent name, or `provider/model`. */\n key: string;\n label: string;\n /** The provider for a model row; `null` for an agent row. */\n provider: string | null;\n totals: DevtoolsAiTotals;\n /** Share of the range's estimated cost, 0 to 1 (share of runs when nothing was priced). */\n share: number;\n};\n\n/** The filter values present in a range, for the filter row. */\nexport type DevtoolsAiFilterOptions = {\n agents: string[];\n /** `provider/model` keys. */\n models: string[];\n providers: string[];\n};\n\n/** `GET api/ai/reports`. */\nexport type DevtoolsAiReportView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n /** The period of the same length just before `range`. */\n previousRange: { from: number; to: number };\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** Estimated USD per bucket, by model (top five plus Other). */\n costByModel: DevtoolsAiSeriesSet;\n /** Tokens per bucket: series `uncached`, `cached`, `output`. */\n tokens: DevtoolsAiSeriesSet;\n errorRate: DevtoolsAiRatePoint[];\n /** Up to 10 rows, highest estimated cost first (most runs when nothing was priced). */\n topAgents: DevtoolsAiBreakdownRow[];\n topModels: DevtoolsAiBreakdownRow[];\n /** `provider/model` keys that used tokens without pricing in the range. */\n unpricedModels: string[];\n filters: DevtoolsAiFilterOptions;\n /** `true` when `@warlock.js/ai` observes nothing, so new runs are not counted. */\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Whether a model's runs carried pricing in the range; `no-tokens` when no run used tokens. */\nexport type DevtoolsAiPricingState = \"set\" | \"missing\" | \"partial\" | \"no-tokens\";\n\n/** One row of the Models page. */\nexport type DevtoolsAiModelRow = {\n /** `provider/model`. */\n key: string;\n model: string;\n provider: string;\n totals: DevtoolsAiTotals;\n pricing: DevtoolsAiPricingState;\n /** Estimated USD per priced run; `null` when no run was priced. */\n costPerRunUsd: number | null;\n /** `fallbackRuns / runs`, 0 to 1. */\n fallbackRate: number;\n /** Agents that used the model, most runs first (at most 5). */\n agents: string[];\n /** Start of the last hour with a run. */\n lastSeenAt: number;\n};\n\n/** `GET api/ai/models`. */\nexport type DevtoolsAiModelsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n /** Most runs first. */\n models: DevtoolsAiModelRow[];\n /** Runs per bucket by model (top five plus Other). */\n runsByModel: DevtoolsAiSeriesSet;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** How failed runs are grouped on the Errors page. */\nexport type DevtoolsAiErrorCategory =\n | \"rate-limit\"\n | \"timeout\"\n | \"refusal\"\n | \"provider\"\n | \"budget\"\n | \"tool\"\n | \"schema\"\n | \"incomplete\"\n | \"other\";\n\n/** Every category, in the order the Errors page lists them. */\nexport const DEVTOOLS_AI_ERROR_CATEGORIES = [\n \"rate-limit\",\n \"timeout\",\n \"refusal\",\n \"provider\",\n \"budget\",\n \"tool\",\n \"schema\",\n \"incomplete\",\n \"other\",\n] as const satisfies readonly DevtoolsAiErrorCategory[];\n\n/** One category of failed runs. */\nexport type DevtoolsAiErrorGroup = {\n category: DevtoolsAiErrorCategory;\n /** \"Rate limit\", \"Timeout\", \"Refusal\", \"Provider error\", \"Budget\", \"Tool failed\", \"Invalid output\", \"Incomplete\", \"Other\". */\n label: string;\n count: number;\n /** Share of all failed runs in the range, 0 to 1. */\n share: number;\n previousCount: number;\n /** At most 5 each, most first. */\n byModel: { key: string; count: number }[];\n byAgent: { key: string; count: number }[];\n};\n\n/** A recent failed run (development only: production keeps no run details). */\nexport type DevtoolsAiFailedRun = {\n traceId: string;\n /** The agent span that failed. */\n agent: string;\n /** `provider/model`, or `null` when unreported. */\n model: string | null;\n status: string;\n category: DevtoolsAiErrorCategory;\n /** The error code (`PROVIDER_RATE_LIMIT`) or error name. */\n code: string | null;\n /** The error message, secrets scrubbed, at most 300 characters. */\n message: string | null;\n endedAt: number;\n requestId: string | null;\n};\n\n/** `GET api/ai/errors`. */\nexport type DevtoolsAiErrorsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n /** Categories with at least one failed run, most first. */\n groups: DevtoolsAiErrorGroup[];\n /** Failed runs per bucket by category (top five plus Other). */\n overTime: DevtoolsAiSeriesSet;\n /** Newest first, at most 50; `null` in production. */\n recent: DevtoolsAiFailedRun[] | null;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Usage of one run as the Runs page shows it. */\nexport type DevtoolsAiUsageView = {\n input: number;\n output: number;\n total: number;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n /** `false` when `input` excludes cache tokens (the provider reports them on top). */\n inputIncludesCache: boolean | null;\n};\n\n/** One row of the Runs page (a Panoptic trace, content-free). */\nexport type DevtoolsAiRunRow = {\n traceId: string;\n requestId: string | null;\n sessionId: string | null;\n name: string;\n /** The root span type: `agent`, `workflow`, `supervisor`, … */\n type: string;\n status: string;\n startedAt: string;\n duration: number;\n usage: DevtoolsAiUsageView;\n /** Estimated USD; `null` when the run carried no pricing. */\n cost: number | null;\n models: string[];\n /** `promptName@promptVersion` of the root agent, or `null`. */\n promptKey: string | null;\n toolCalls: number;\n retries: number;\n incomplete: boolean;\n};\n\n/** A group of the Runs page (`groupBy=session|prompt|type`). */\nexport type DevtoolsAiRunGroup = {\n key: string;\n label: string;\n runs: number;\n failed: number;\n estimatedCostUsd: number;\n p95Ms: number | null;\n /** Trace ids of the group, newest first (at most 50). */\n traceIds: string[];\n};\n\n/** `GET api/ai/runs`. */\nexport type DevtoolsAiRunsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Newest first, at most `limit` (default 200). */\n runs: DevtoolsAiRunRow[];\n /** `null` unless `groupBy` was given. */\n groups: DevtoolsAiRunGroup[] | null;\n stats: {\n /** Runs matching the filter (before `limit`). */\n count: number;\n failed: number;\n /** Priced runs only. */\n estimatedCostUsd: number;\n /** Runs that used tokens on a model without pricing (not in `estimatedCostUsd`). */\n unpricedRuns: number;\n p50Ms: number | null;\n p95Ms: number | null;\n };\n /** How many traces the dashboard keeps (`maxRequests`). */\n capacity: number;\n };\n\n/** A distinct system prompt seen in recent agent runs (the Evaluate picker). */\nexport type DevtoolsAiEvaluatePrompt = {\n /** The prompt's hash from the agent trace. */\n hash: string;\n /** Agents that used it, most recent first. */\n agents: string[];\n /** The newest run that carried its text. */\n runId: string;\n lastSeenAt: string;\n /** The first 200 characters. */\n preview: string;\n length: number;\n};\n\n/** `GET api/ai/evaluate`. */\nexport type DevtoolsAiEvaluateView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Whether `panoptic.evaluate` (or `panoptic.dashboard.evaluate`) has a judge model. */\n configured: boolean;\n /** The judge model as `provider/name`; `null` when not configured. */\n judge: string | null;\n /** The configured default grading instructions; `\"\"` when none. */\n instructions: string;\n /** Newest first, at most 50. */\n prompts: DevtoolsAiEvaluatePrompt[];\n };\n\n/** `POST api/ai/evaluate` body: exactly one of `runId` and `systemPrompt`. */\nexport type DevtoolsAiEvaluateRequest = {\n /** An agent run whose system prompt text is kept. */\n runId?: string;\n /** A pasted prompt, 1 to 100,000 characters. */\n systemPrompt?: string;\n /** Overrides the configured instructions for this run; at most 4,000 characters. */\n instructions?: string;\n};\n\n/** `POST api/ai/evaluate` answer. */\nexport type DevtoolsAiEvaluateResult = {\n /** 0 to 1; `null` when the judge returned no score. */\n score: number | null;\n issues: string[];\n /** The judge model as `provider/name`. */\n judge: string;\n durationMs: number;\n};\n"],"mappings":";;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;;;;;;;;;;AAwYA,MAAa,2BAA2B;CACtC;EAAE,IAAI;EAAY,OAAO;EAAY,YAAY;CAAK;CACtD;EAAE,IAAI;EAAW,OAAO;EAAW,YAAY;CAAK;CACpD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAa,OAAO;EAAa,YAAY;CAAK;CACxD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAM;CAC/C;EAAE,IAAI;EAAc,OAAO;EAAW,YAAY;CAAK;CACvD;EAAE,IAAI;EAAM,OAAO;EAAQ,YAAY;CAAM;CAC7C;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAM;CACnD;EAAE,IAAI;EAAa,OAAO;EAAU,YAAY;CAAK;CACrD;EAAE,IAAI;EAAa,OAAO;EAAU,YAAY;CAAK;CACrD;EAAE,IAAI;EAAe,OAAO;EAAY,YAAY;CAAM;CAC1D;EAAE,IAAI;EAAO,OAAO;EAAO,YAAY;CAAM;AAC/C;;AAwMA,MAAa,+BAA6D;CACxE;CACA;CACA;AACF;;;;;;;;AAwFA,MAAa,iCAAiC;CAC5C;CAAK;CAAK;CAAM;CAAM;CAAM;CAAM;CAAM;CAAO;CAAO;CAAO;CAAO;CAAO;CAAO;CAAQ;AAC5F;;AAuNA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
@@ -122,9 +122,14 @@ function mountProductionDevtools(server, deps) {
122
122
  lastWarningAt = now;
123
123
  deps.warn?.(message);
124
124
  };
125
- const notFound = (request, reply) => {
125
+ const notFound = async (request, reply) => {
126
126
  uniformNotFound.add(request);
127
- reply.callNotFound();
127
+ try {
128
+ if (!(await deps.answerUnknownUrl?.(request, reply) ?? false)) reply.callNotFound();
129
+ } catch (error) {
130
+ warn(`The app's answer for an unknown URL failed, the dashboard answers with the plain 404: ${error instanceof Error ? error.message : String(error)}`);
131
+ if (!reply.sent) reply.callNotFound();
132
+ }
128
133
  return reply;
129
134
  };
130
135
  const streamSession = async (request) => {
@@ -296,6 +301,7 @@ function mountProductionDevtools(server, deps) {
296
301
  });
297
302
  });
298
303
  instance.setErrorHandler((error, request, reply) => {
304
+ if (uniformNotFound.has(request)) throw error;
299
305
  if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);
300
306
  if (error instanceof DevtoolsApiError) return reply.code(error.statusCode).send(error.toBody());
301
307
  const status = error.statusCode;