@warlock.js/devtools 5.63.1 → 5.65.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.
@@ -1,4 +1,5 @@
1
1
  const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
2
+ const require_errors = require("./errors-DNQ-g49I.cjs");
2
3
  const require_ai_source = require("./ai-source-CeHZDYG1.cjs");
3
4
  const require_process_panel = require("./process-panel-Dev6eg_f.cjs");
4
5
  const require_stream_route = require("./stream-route-qEHoPVth.cjs");
@@ -162,8 +163,19 @@ function mountDevtoolsRoutes(server, deps) {
162
163
  const panels = require_ai_source.checkDevtoolsPanels([require_process_panel.processesDevtoolsPanel(deps.processPanel), ...deps.panels ?? []]);
163
164
  server.register(async (instance) => {
164
165
  registerDevtoolsGuard(instance, deps);
165
- instance.setErrorHandler((error, _request, reply) => {
166
- reply.code(error.statusCode ?? 500).send({ error: error.message });
166
+ instance.setErrorHandler((error, request, reply) => {
167
+ const status = error.statusCode ?? 500;
168
+ if (status < 500) return reply.code(status).send({ error: error.message });
169
+ const ref = require_errors.createErrorRef();
170
+ deps.warn?.(`Devtools error ${ref} on ${request.method} ${request.url}: ${error.message}`);
171
+ request.log.error({
172
+ ref,
173
+ err: error
174
+ }, "devtools error");
175
+ return reply.code(status).send({
176
+ error: error.message,
177
+ ref
178
+ });
167
179
  });
168
180
  require_stream_route.registerUiAssets(instance);
169
181
  registerSessionRoutes(instance, deps, panels);
@@ -185,4 +197,4 @@ function mountDevtoolsRoutes(server, deps) {
185
197
 
186
198
  //#endregion
187
199
  exports.mountDevtoolsRoutes = mountDevtoolsRoutes;
188
- //# sourceMappingURL=server-Dc0YdP6Y.cjs.map
200
+ //# sourceMappingURL=server-BhiUHfRi.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-BhiUHfRi.cjs","names":["readVersions","listPanelInfos","checkDevtoolsPanels","processesDevtoolsPanel","createErrorRef"],"sources":["../../../../../../../packages/devtools/src/server/background-routes.ts","../../../../../../../packages/devtools/src/server/guard.ts","../../../../../../../packages/devtools/src/server/session-routes.ts","../../../../../../../packages/devtools/src/server/index.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/** Registers the route that returns work recorded outside any request. */\nexport function registerBackgroundRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n server.get(\"/api/background\", async () => deps.collector.getBackground());\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\nconst LOOPBACK_ADDRESSES = new Set([\"127.0.0.1\", \"::1\", \"::ffff:127.0.0.1\"]);\n\n/** Host names that always reach this machine, so DNS cannot be pointed at them. */\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** Headers a proxy or tunnel adds; their presence means the loopback peer is not the visitor. */\nconst PROXY_HEADERS = [\"x-forwarded-for\", \"x-forwarded-host\", \"x-real-ip\", \"forwarded\"] as const;\n\n/** At most this many distinct refusals are logged per boot. */\nconst MAX_WARNINGS = 20;\n\n/**\n * Whether `address` is a loopback address. Deliberately reads\n * `request.socket.remoteAddress` rather than `request.ip`, which honours\n * `X-Forwarded-For` when the app trusts a proxy — a header any client can\n * set.\n */\nfunction isLoopbackAddress(address: string | undefined): boolean {\n return address !== undefined && LOOPBACK_ADDRESSES.has(address);\n}\n\n/** The lower-cased host name of a `Host` header value, without its port (`[::1]` keeps its brackets). */\nexport function hostnameOf(host: string): string {\n const value = host.trim().toLowerCase();\n\n if (value.startsWith(\"[\")) {\n const end = value.indexOf(\"]\");\n\n return end === -1 ? \"\" : value.slice(0, end + 1);\n }\n\n const colon = value.indexOf(\":\");\n const name = colon === -1 ? value : value.slice(0, colon);\n\n return name.endsWith(\".\") ? name.slice(0, -1) : name;\n}\n\n/**\n * Whether `hostname` is a loopback name or one of `allowedHosts`. An entry\n * starting with `.` matches that domain and every subdomain of it.\n */\nexport function isAllowedDevtoolsHost(\n hostname: string,\n allowedHosts: readonly string[] = [],\n): boolean {\n if (!hostname) return false;\n if (LOOPBACK_HOSTS.has(hostname) || hostname.endsWith(\".localhost\")) return true;\n\n return allowedHosts.some((entry) => {\n const allowed = entry.trim().toLowerCase();\n\n if (allowed.startsWith(\".\")) {\n return hostname === allowed.slice(1) || hostname.endsWith(allowed);\n }\n\n return hostname === allowed;\n });\n}\n\n/** The `Origin` header's host name, `\"\"` for `null` or an unparsable value. */\nfunction originHostname(origin: string): string {\n try {\n return new URL(origin).hostname.toLowerCase();\n } catch {\n return \"\";\n }\n}\n\n/**\n * Why `request` must be refused, or `undefined` when it may be served.\n * `\"not-local\"` is the silent case (production, or a remote socket). Beyond a\n * loopback socket, the request must be ADDRESSED to a loopback (or allowed)\n * host, come from such an origin, and not have passed through a proxy: a page\n * whose domain was re-pointed at 127.0.0.1, or a tunnel, also arrives on a\n * loopback socket.\n */\nfunction refusalReason(request: FastifyRequest, deps: MountDevtoolsRoutesDeps): string | undefined {\n if (!deps.isDevelopment() || !isLoopbackAddress(request.socket.remoteAddress)) {\n return \"not-local\";\n }\n\n const allowedHosts = deps.options.allowedHosts ?? [];\n const host = hostnameOf(request.headers.host ?? \"\");\n\n if (!isAllowedDevtoolsHost(host, allowedHosts)) {\n return `Devtools refused a request for host \"${host}\". Open the dashboard on localhost, or add the host to the devtools \"allowedHosts\" option.`;\n }\n\n const origin = request.headers.origin;\n\n if (origin !== undefined && !isAllowedDevtoolsHost(originHostname(origin), allowedHosts)) {\n return `Devtools refused a request from origin \"${origin}\". Only pages served from localhost or a host in the devtools \"allowedHosts\" option may call the dashboard.`;\n }\n\n if (\n !deps.options.allowProxied &&\n PROXY_HEADERS.some((name) => request.headers[name] !== undefined)\n ) {\n return 'Devtools refused a proxied request (it carries a forwarding header). Open the dashboard directly on localhost, or set the devtools \"allowProxied\" option for a local proxy nobody else can reach.';\n }\n\n return undefined;\n}\n\n/**\n * Registers the dev-only, local-only guard as an `onRequest` hook on\n * `server`. Callers must register this inside an encapsulated Fastify\n * context (a plugin/prefix) so the hook never reaches routes outside the\n * dashboard.\n */\nexport function registerDevtoolsGuard(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n // One terminal line per distinct refusal, so a misconfigured host is\n // explained once without flooding the log on every poll.\n const warned = new Set<string>();\n\n server.addHook(\"onRequest\", async (request: FastifyRequest, reply: FastifyReply) => {\n const reason = refusalReason(request, deps);\n\n if (reason === undefined) return;\n\n if (reason !== \"not-local\" && !warned.has(reason) && warned.size < MAX_WARNINGS) {\n warned.add(reason);\n deps.warn?.(reason);\n }\n\n // Returning the reply is what stops the lifecycle in an async hook;\n // without it Fastify still runs the handler after the 404 is sent.\n return reply.code(404).send();\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport { readVersions } from \"../app-versions\";\nimport { listPanelInfos, type MountedDevtoolsPanel } from \"../panels\";\nimport type { DevtoolsPanelInfo, DevtoolsSessionView } from \"../production/contracts\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/**\n * The session view of the development dashboard: there are no accounts, the\n * loopback guard is the access control, and the visitor is an admin.\n */\nexport function developmentSessionView(deps: MountDevtoolsRoutesDeps): DevtoolsSessionView {\n return {\n mode: \"development\",\n stage: \"active\",\n account: null,\n role: \"admin\",\n csrf: null,\n expiresAt: null,\n instance: deps.instance ?? null,\n methods: null,\n share: null,\n ...readVersions(),\n };\n}\n\n/** The tabs `GET api/panels` lists: the built-in tabs in `deps.builtInPanels` (default all), then the package panels. */\nexport function panelInfos(\n deps: MountDevtoolsRoutesDeps,\n panels: readonly (Pick<MountedDevtoolsPanel, \"id\" | \"title\"> &\n Partial<Pick<MountedDevtoolsPanel, \"share\">>)[],\n): DevtoolsPanelInfo[] {\n return listPanelInfos(panels, deps.builtInPanels);\n}\n\n/**\n * Registers `GET /api/auth/session` (the development view: signed in as an\n * admin, no accounts) and `GET /api/panels`, so the same dashboard shell\n * works in both modes. Production answers these from its own mount.\n */\nexport function registerSessionRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n panels: readonly MountedDevtoolsPanel[],\n): void {\n server.get(\"/api/auth/session\", async (_request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n\n return developmentSessionView(deps);\n });\n\n server.get(\"/api/panels\", async (_request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n\n return panelInfos(deps, panels);\n });\n}\n","import type { FastifyError, FastifyInstance } from \"fastify\";\nimport { checkDevtoolsPanels } from \"../panels\";\nimport { createErrorRef } from \"../production/errors\";\nimport { processesDevtoolsPanel } from \"../process-panel\";\nimport { registerAiReportRoutes } from \"./ai-report-routes\";\nimport { registerAiRoutes } from \"./ai-routes\";\nimport { registerBackgroundRoutes } from \"./background-routes\";\nimport { registerExplainRoute, registerShapeExplainRoute } from \"./explain-route\";\nimport { registerInsightsRoutes } from \"./insights-routes\";\nimport { registerDevtoolsGuard } from \"./guard\";\nimport { registerLogRoutes } from \"./log-routes\";\nimport { registerMailRoutes } from \"./mail-routes\";\nimport { registerOpenApiRoutes } from \"./openapi-routes\";\nimport { registerPanelRoutes } from \"./panel-routes\";\nimport { registerRequestsRoutes } from \"./requests-routes\";\nimport { registerRouteRoutes } from \"./route-routes\";\nimport { registerSessionRoutes } from \"./session-routes\";\nimport { registerStreamRoute } from \"./stream-route\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\nimport { registerUiAssets } from \"./ui-assets\";\n\nexport type { DevtoolsRequestLogSource, DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./types\";\n\n/**\n * Mounts the devtools dashboard and its API under `deps.options.path` on\n * `server`. Every route is registered inside a single encapsulated Fastify\n * context so the dev-only, loopback-only guard never reaches the app's\n * other routes — the registered panels' data routes and files included.\n *\n * Throws before mounting anything when a panel is invalid or reuses an id.\n */\nexport function mountDevtoolsRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n const panels = checkDevtoolsPanels([\n processesDevtoolsPanel(deps.processPanel),\n ...(deps.panels ?? []),\n ]);\n\n server.register(\n async (instance) => {\n registerDevtoolsGuard(instance, deps);\n\n instance.setErrorHandler((error: FastifyError, request, reply) => {\n const status = error.statusCode ?? 500;\n\n if (status < 500) return reply.code(status).send({ error: error.message });\n\n // A failure of the server itself carries a short reference, written to the log, that the dashboard shows.\n const ref = createErrorRef();\n\n deps.warn?.(`Devtools error ${ref} on ${request.method} ${request.url}: ${error.message}`);\n request.log.error({ ref, err: error }, \"devtools error\");\n\n return reply.code(status).send({ error: error.message, ref });\n });\n\n registerUiAssets(instance);\n registerSessionRoutes(instance, deps, panels);\n registerRequestsRoutes(instance, deps);\n registerAiRoutes(instance, deps);\n registerAiReportRoutes(instance, deps);\n registerBackgroundRoutes(instance, deps);\n registerMailRoutes(instance, deps);\n registerLogRoutes(instance, deps);\n registerRouteRoutes(instance, deps);\n registerPanelRoutes(instance, panels);\n registerOpenApiRoutes(instance, deps);\n registerExplainRoute(instance, deps);\n registerShapeExplainRoute(instance, deps);\n if (deps.insights) registerInsightsRoutes(instance, deps);\n registerStreamRoute(instance, deps);\n },\n { prefix: deps.options.path },\n );\n}\n"],"mappings":";;;;;;;;AAIA,SAAgB,yBACd,QACA,MACM;CACN,OAAO,IAAI,mBAAmB,YAAY,KAAK,UAAU,cAAc,CAAC;AAC1E;;;;ACNA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAa;CAAO;AAAkB,CAAC;;AAG3E,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;;AAGlE,MAAM,gBAAgB;CAAC;CAAmB;CAAoB;CAAa;AAAW;;AAGtF,MAAM,eAAe;;;;;;;AAQrB,SAAS,kBAAkB,SAAsC;CAC/D,OAAO,YAAY,UAAa,mBAAmB,IAAI,OAAO;AAChE;;AAGA,SAAgB,WAAW,MAAsB;CAC/C,MAAM,QAAQ,KAAK,KAAK,CAAC,CAAC,YAAY;CAEt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GAChE,MAAM,SAAS,MAAM,cAAc;GAEnC,IAAI,SAAS,KAAK,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,KAAK,EAAE,OAAO,MAAM,QAAQ,CAAC;GAGzE,MAAM,MAAMC,8BAAe;GAE3B,KAAK,OAAO,kBAAkB,IAAI,MAAM,QAAQ,OAAO,GAAG,QAAQ,IAAI,IAAI,MAAM,SAAS;GACzF,QAAQ,IAAI,MAAM;IAAE;IAAK,KAAK;GAAM,GAAG,gBAAgB;GAEvD,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,KAAK;IAAE,OAAO,MAAM;IAAS;GAAI,CAAC;EAC9D,CAAC;EAED,sCAAiB,QAAQ;EACzB,sBAAsB,UAAU,MAAM,MAAM;EAC5C,4CAAuB,UAAU,IAAI;EACrC,sCAAiB,UAAU,IAAI;EAC/B,4CAAuB,UAAU,IAAI;EACrC,yBAAyB,UAAU,IAAI;EACvC,wCAAmB,UAAU,IAAI;EACjC,uCAAkB,UAAU,IAAI;EAChC,yCAAoB,UAAU,IAAI;EAClC,yCAAoB,UAAU,MAAM;EACpC,2CAAsB,UAAU,IAAI;EACpC,0CAAqB,UAAU,IAAI;EACnC,+CAA0B,UAAU,IAAI;EACxC,IAAI,KAAK,UAAU,4CAAuB,UAAU,IAAI;EACxD,yCAAoB,UAAU,IAAI;CACpC,GACA,EAAE,QAAQ,KAAK,QAAQ,KAAK,CAC9B;AACF"}
@@ -513,7 +513,7 @@ function devtoolsConnector(options = {}) {
513
513
  agentTraces,
514
514
  warn: (message) => log.warn("devtools", "evaluate", message)
515
515
  });
516
- const { mountDevtoolsRoutes } = await Promise.resolve().then(() => require("./server-Dc0YdP6Y.cjs"));
516
+ const { mountDevtoolsRoutes } = await Promise.resolve().then(() => require("./server-BhiUHfRi.cjs"));
517
517
  const postmanBuilder = await findPostmanBuilder();
518
518
  const requestLog = await findRequestLogSource();
519
519
  const processPanel = await require_process_panel.loadProcessPanel();
@@ -688,7 +688,7 @@ async function wireDevelopmentAiReports(ai, resolved, core, log, disposers) {
688
688
  * `DevtoolsProductionConfigError`) when the configuration is incomplete.
689
689
  */
690
690
  async function bootProduction(core, log, resolved) {
691
- const { bootProductionDevtools } = await Promise.resolve().then(() => require("./boot-Guumt-du.cjs"));
691
+ const { bootProductionDevtools } = await Promise.resolve().then(() => require("./boot-Cy3jyixg.cjs"));
692
692
  const requestLog = await findRequestLogSource();
693
693
  const processPanel = resolved.production?.panels?.processes === true ? await require_process_panel.loadProcessPanel() : void 0;
694
694
  const builtIn = require_process_panel.processesDevtoolsPanel(processPanel);
@@ -848,4 +848,4 @@ Object.defineProperty(exports, "mail_source_exports", {
848
848
  return mail_source_exports;
849
849
  }
850
850
  });
851
- //# sourceMappingURL=src-Ca1gNdZj.cjs.map
851
+ //# sourceMappingURL=src-ChI4g-4B.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"src-Ca1gNdZj.cjs","names":["DevtoolsApiError","createErrorRef","currentRequestId","LogChannel","toSafeValue","currentRequestId","currentRequestId","fileURLToPath","applyRedact","log","currentRequestId","toSafeValue","toSafeValue","createCollector","attachAiSource","attachAgentTraceSource","loadProcessPanel","processesDevtoolsPanel","loadDevtoolsPanels","DEVTOOLS_MOUNTED_KEY","DEVTOOLS_PRODUCTION_DEFAULTS","toAiUnavailableView","describeAiUnavailable","loadAiFeed","attachAiReports","resolveDevtoolsAiOptions","recentAiFailures","checkDevtoolsPanels"],"sources":["../../../../../../../packages/devtools/src/panel-errors.ts","../../../../../../../packages/devtools/src/options.ts","../../../../../../../packages/devtools/src/ai/reports/evaluate.ts","../../../../../../../packages/devtools/src/sources/cache-source.ts","../../../../../../../packages/devtools/src/sources/log-source.ts","../../../../../../../packages/devtools/src/sources/mail-source.ts","../../../../../../../packages/devtools/src/caller-location.ts","../../../../../../../packages/devtools/src/sources/query-source.ts","../../../../../../../packages/devtools/src/sources/tracing-source.ts","../../../../../../../packages/devtools/src/devtools-connector.ts","../../../../../../../packages/devtools/src/panel-tokens.ts"],"sourcesContent":["import type { DevtoolsErrorsView } from \"./production/contracts\";\nimport type { DevtoolsPanelErrorSummary } from \"./types\";\n\n/** Captured errors are offered to panels for the last hour. */\nconst WINDOW_MS = 3_600_000;\n\n/** The most error groups one read maps. */\nconst MAX_GROUPS = 500;\n\n/** The part of the insights a panel's error counts come from. */\ntype ErrorInsights = {\n errors(query: { instance: string; limit: number }): Promise<DevtoolsErrorsView>;\n};\n\n/**\n * What a panel factory receives as `context.errors`. Panels load before the\n * capture starts, so this reads through a source the connector binds once the\n * insights exist; until then (and when they never start) it answers an empty\n * list. Only counts, the route and the class name leave: no message, no stack.\n */\nexport type PanelErrorSource = {\n read: () => Promise<readonly DevtoolsPanelErrorSummary[]>;\n /** Binds the insights (development: this process; production: every instance). */\n bind(insights: ErrorInsights | null): void;\n};\n\nexport function createPanelErrorSource(now: () => number = Date.now): PanelErrorSource {\n let insights: ErrorInsights | null = null;\n\n return {\n bind(next) {\n insights = next;\n },\n async read() {\n if (insights === null) return [];\n\n const since = now() - WINDOW_MS;\n const view = await insights.errors({ instance: \"all\", limit: MAX_GROUPS });\n\n return view.groups\n .filter((group) => group.lastSeen >= since)\n .map((group) => ({\n route: group.route,\n status: group.status,\n name: group.name,\n source: group.source,\n count: group.count,\n firstSeen: group.firstSeen,\n lastSeen: group.lastSeen,\n }));\n },\n };\n}\n","import { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport type { DevtoolsOptions, ResolvedDevtoolsOptions } from \"./types\";\n\n/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */\nexport function resolveDevtoolsOptions(options: DevtoolsOptions = {}): ResolvedDevtoolsOptions {\n const path = (options.path ?? \"/__warlock\").replace(/\\/+$/, \"\");\n const maxRequests = options.maxRequests ?? 200;\n const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;\n\n if (!path || !path.startsWith(\"/\")) {\n throw new Error('Devtools option \"path\" must be a non-root path starting with \"/\".');\n }\n\n if (maxRequests < 1) {\n throw new Error('Devtools option \"maxRequests\" must be at least 1.');\n }\n\n if (nPlusOneThreshold < 2) {\n throw new Error('Devtools option \"nPlusOneThreshold\" must be at least 2.');\n }\n\n // Validates the AI options; the mode defaults are applied where the mode is known.\n if (options.ai !== undefined) resolveDevtoolsAiOptions(options.ai, \"development\");\n\n return {\n path,\n maxRequests,\n nPlusOneThreshold,\n allowedHosts: options.allowedHosts ?? [],\n allowProxied: options.allowProxied ?? false,\n panels: options.panels ?? [],\n ...(options.ai === undefined ? {} : { ai: options.ai }),\n ...(options.production === undefined ? {} : { production: options.production }),\n };\n}\n","import type {\n DevtoolsAiEvaluateRequest,\n DevtoolsAiEvaluateResult,\n DevtoolsAiEvaluateView,\n} from \"../../production/contracts\";\nimport { createErrorRef, DevtoolsApiError } from \"../../production/errors\";\nimport type { DevtoolsAgentTraceSource } from \"../../sources/agent-trace-source\";\n\nconst MAX_PROMPTS = 50;\nconst MAX_RUNS_SCANNED = 300;\nconst MAX_SYSTEM_PROMPT = 100_000;\nconst MAX_INSTRUCTIONS = 4000;\nconst PREVIEW_LENGTH = 200;\n\ntype EvaluateModule = {\n getEvaluateConfig?: () => EvaluateConfigLike | undefined;\n evaluateSystemPrompt?: (\n systemPrompt: string,\n config: EvaluateConfigLike,\n instructions?: string,\n ) => Promise<{ score?: number; issues?: string[] }>;\n};\n\ntype ModelLike = { name?: string; provider?: string };\n\ntype EvaluateConfigLike = {\n model: ModelLike | (() => ModelLike | Promise<ModelLike>);\n instructions?: string;\n};\n\n/** What the Evaluate routes use; injected so specs need no model. */\nexport type DevtoolsAiEvaluator = {\n /** The page data: whether a judge is configured and the recent distinct system prompts. */\n view(): Promise<Extract<DevtoolsAiEvaluateView, { available: true }>>;\n /**\n * Grades a prompt with Panoptic's `evaluateSystemPrompt`. Throws\n * `DevtoolsApiError` `input.invalid` (both or neither of runId/systemPrompt,\n * sizes), `ai.evaluate-unavailable` (no judge configured),\n * `ai.prompt-not-found` (run gone or its text not kept) or\n * `ai.evaluate-failed` (the judge threw; logged with the reference).\n */\n evaluate(request: DevtoolsAiEvaluateRequest): Promise<DevtoolsAiEvaluateResult>;\n};\n\nfunction judgeLabel(model: ModelLike): string {\n return typeof model.provider === \"string\" && typeof model.name === \"string\"\n ? `${model.provider}/${model.name}`\n : (model.name ?? \"custom model\");\n}\n\n/** Builds the evaluator over the agent traces and Panoptic's evaluate helpers (loaded lazily). */\nexport function createAiEvaluator(input: {\n agentTraces: DevtoolsAgentTraceSource;\n load?: (name: string) => Promise<unknown>;\n warn?: (message: string) => void;\n}): DevtoolsAiEvaluator {\n const load = input.load ?? (() => import(\"@warlock.js/ai-panoptic\"));\n\n /** Panoptic's evaluate helpers, or `undefined` when Panoptic (or its evaluate support) is not there. */\n async function panoptic(): Promise<(EvaluateModule & Required<EvaluateModule>) | undefined> {\n try {\n const module = (await load(\"@warlock.js/ai-panoptic\")) as EvaluateModule;\n\n return typeof module.getEvaluateConfig === \"function\" &&\n typeof module.evaluateSystemPrompt === \"function\"\n ? (module as EvaluateModule & Required<EvaluateModule>)\n : undefined;\n } catch {\n return undefined;\n }\n }\n\n const unavailable = (): DevtoolsApiError => new DevtoolsApiError(\"ai.evaluate-unavailable\");\n\n return {\n async view() {\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n const byHash = new Map<\n string,\n { agents: string[]; runId: string; startedAt: string; text: string }\n >();\n const runs = input.agentTraces\n .list()\n .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || 0)\n .slice(0, MAX_RUNS_SCANNED);\n\n for (const run of runs) {\n const prompt = input.agentTraces.get(run.runId)?.systemPrompt;\n\n if (!prompt || typeof prompt.text !== \"string\" || prompt.text === \"\") continue;\n\n const known = byHash.get(prompt.hash);\n\n if (known) {\n if (!known.agents.includes(run.agent)) known.agents.push(run.agent);\n } else {\n byHash.set(prompt.hash, {\n agents: [run.agent],\n runId: run.runId,\n startedAt: run.startedAt,\n text: prompt.text,\n });\n }\n }\n\n return {\n available: true as const,\n configured: config !== undefined,\n judge:\n config === undefined\n ? null\n : typeof config.model === \"function\"\n ? \"custom model\"\n : judgeLabel(config.model),\n instructions: config?.instructions ?? \"\",\n prompts: [...byHash.entries()].slice(0, MAX_PROMPTS).map(([hash, item]) => ({\n hash,\n agents: item.agents,\n runId: item.runId,\n lastSeenAt: item.startedAt,\n preview: item.text.slice(0, PREVIEW_LENGTH),\n length: item.text.length,\n })),\n };\n },\n\n async evaluate(request) {\n const { runId, systemPrompt, instructions } = request;\n\n if ((runId === undefined) === (systemPrompt === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (\n (runId !== undefined && (typeof runId !== \"string\" || runId === \"\")) ||\n (systemPrompt !== undefined &&\n (typeof systemPrompt !== \"string\" ||\n systemPrompt.trim() === \"\" ||\n systemPrompt.length > MAX_SYSTEM_PROMPT)) ||\n (instructions !== undefined &&\n (typeof instructions !== \"string\" || instructions.length > MAX_INSTRUCTIONS))\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n if (!module || !config) throw unavailable();\n\n let text = systemPrompt;\n\n if (runId !== undefined) {\n text = input.agentTraces.get(runId)?.systemPrompt?.text;\n\n if (typeof text !== \"string\" || text === \"\")\n throw new DevtoolsApiError(\"ai.prompt-not-found\");\n }\n\n const started = Date.now();\n\n try {\n const model = typeof config.model === \"function\" ? await config.model() : config.model;\n const verdict = await module.evaluateSystemPrompt(\n text as string,\n { ...config, model },\n instructions,\n );\n\n return {\n score: typeof verdict.score === \"number\" ? verdict.score : null,\n issues: Array.isArray(verdict.issues) ? verdict.issues.map(String) : [],\n judge: judgeLabel(model),\n durationMs: Date.now() - started,\n };\n } catch (error) {\n const ref = createErrorRef();\n\n input.warn?.(\n `Devtools evaluate error ${ref}: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n throw new DevtoolsApiError(\"ai.evaluate-failed\", { ref, cause: error });\n }\n },\n };\n}\n","import { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCacheOperation, DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** Cache events the dashboard's waterfall and background bucket care about. */\nconst EVENT_TYPES = [\"hit\", \"miss\", \"set\", \"removed\", \"invalidated\", \"flushed\"] as const;\n\n/** The shape `cache.on(event, handler)` hands the handler. */\ntype CacheEventData = {\n key?: string;\n driver: string;\n tags?: string[];\n keys?: string[];\n durationMs?: number;\n};\n\n/**\n * Feeds cache hits, misses and mutations, from `@warlock.js/cache`, into the\n * collector. A no-op when `@warlock.js/cache` isn't installed — it is an\n * optional peer.\n */\nexport async function attachCacheSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let cache: {\n on(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n off(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n };\n\n try {\n ({ cache } = await import(\"@warlock.js/cache\"));\n } catch {\n return () => {};\n }\n\n const handlers = EVENT_TYPES.map((type) => {\n const handler = (data: CacheEventData) => {\n const operation: DevtoolsCacheOperation = {\n type,\n driver: data.driver,\n key: data.key,\n tags: data.tags,\n keys: data.keys,\n at: Date.now(),\n durationMs: data.durationMs,\n };\n\n collector.addCacheOperation(currentRequestId(), operation);\n };\n\n cache.on(type, handler);\n\n return { type, handler };\n });\n\n return () => {\n for (const { type, handler } of handlers) cache.off(type, handler);\n };\n}\n","import { LogChannel, log, type LoggingData } from \"@warlock.js/logger\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsLogEntry } from \"../types\";\n\n/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */\nfunction toDevtoolsLevel(type: LoggingData[\"type\"]): DevtoolsLogEntry[\"level\"] {\n return type === \"fatal\" ? \"error\" : type;\n}\n\n/**\n * The entry's message as text. `request.log(error)` and friends log an Error\n * (or any value) as the message; kept as is, it reached the dashboard as `{}`.\n */\nfunction messageText(message: unknown): string {\n if (typeof message === \"string\") return message;\n if (message instanceof Error) return `${message.name}: ${message.message}`;\n\n try {\n return JSON.stringify(message) ?? String(message);\n } catch {\n return String(message);\n }\n}\n\nclass DevtoolsLogChannel extends LogChannel {\n public override name = \"devtools\";\n public active = true;\n\n public constructor(private readonly collector: DevtoolsCollector) {\n super();\n }\n\n public log(data: LoggingData): void {\n if (!this.active) return;\n\n // Already passed through the logger's redaction floor (`Logger.log`\n // applies it before invoking any channel). It is still app data, and can\n // hold live objects (a request, its socket), so a JSON-safe snapshot is\n // kept instead of the object itself.\n const entry: DevtoolsLogEntry = {\n level: toDevtoolsLevel(data.type),\n module: data.module,\n action: data.action,\n message: messageText(data.message),\n at: Date.now(),\n context: toSafeValue(data.context),\n };\n\n this.collector.addLog(currentRequestId(), entry);\n }\n}\n\n/**\n * Feeds every log entry, from `@warlock.js/logger`, into the collector by\n * registering an additional channel. `Logger` has no way to remove a\n * channel, so the disposer flag-ignores further entries instead — the\n * channel stays registered for the process's lifetime.\n */\nexport async function attachLogSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const channel = new DevtoolsLogChannel(collector);\n\n log.addChannel(channel);\n\n return () => {\n channel.active = false;\n };\n}\n","import type { CapturedMail, MailAddress, MailAttachment } from \"@warlock.js/core\";\nimport { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsMailAttachment } from \"../types\";\n\nfunction addressToString(address: MailAddress | undefined): string | undefined {\n if (!address) return undefined;\n\n return typeof address === \"string\" ? address : `${address.name} <${address.address}>`;\n}\n\nfunction attachmentSize(attachment: MailAttachment): number | undefined {\n if (typeof attachment.content === \"string\") return Buffer.byteLength(attachment.content);\n if (Buffer.isBuffer(attachment.content)) return attachment.content.length;\n\n return undefined;\n}\n\nfunction toDevtoolsAttachment(attachment: MailAttachment): DevtoolsMailAttachment {\n return {\n filename: attachment.filename,\n contentType: attachment.contentType,\n size: attachmentSize(attachment),\n };\n}\n\n/**\n * Feeds mails captured in development mode, from core's `mailEvents`, into\n * the collector. The captured attachments carry their content, but only\n * metadata is stored — the bytes are never kept.\n */\nexport async function attachMailSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const { mailEvents } = await import(\"@warlock.js/core\");\n\n const subscription = mailEvents.onCaptured((mail: CapturedMail) => {\n const { normalized } = mail;\n\n collector.addMail({\n id: mail.id,\n requestId: currentRequestId(),\n capturedAt: mail.timestamp.getTime(),\n from: addressToString(normalized.from),\n to: normalized.to,\n cc: normalized.cc,\n bcc: normalized.bcc,\n subject: normalized.subject,\n html: normalized.html,\n text: normalized.text,\n headers: normalized.headers,\n attachments: normalized.attachments.map(toDevtoolsAttachment),\n });\n });\n\n return () => subscription.unsubscribe();\n}\n","import { fileURLToPath } from \"node:url\";\n\nimport type { DevtoolsCallerLocation } from \"./types\";\n\nconst packageDirectory = normalizePath(fileURLToPath(new URL(\"../\", import.meta.url)));\n\n/** Returns the first non-runtime, non-devtools frame in a V8 stack trace. */\nexport function captureCallerLocation(\n stack: string = new Error().stack ?? \"\",\n): DevtoolsCallerLocation | undefined {\n for (const line of stack.split(\"\\n\")) {\n const frame = parseFrame(line);\n if (!frame || shouldSkip(frame.file)) continue;\n return frame;\n }\n return undefined;\n}\n\nfunction parseFrame(frame: string): DevtoolsCallerLocation | undefined {\n const match = frame.match(/\\bat\\s+(?:.*?\\s+\\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/);\n const [, rawFile, line, column] = match ?? [];\n if (!rawFile || !line || !column) return undefined;\n const file = normalizePath(rawFile);\n return { file, line: Number(line), column: Number(column) };\n}\n\n/** A drive-letter file URL names a Windows path on whichever host decodes it. */\nconst WINDOWS_DRIVE_FILE_URL = /^file:\\/\\/\\/[A-Za-z]:/;\n\nfunction normalizePath(path: string): string {\n const decoded = !path.startsWith(\"file:\")\n ? path\n : WINDOWS_DRIVE_FILE_URL.test(path)\n ? fileURLToPath(path, { windows: true })\n : fileURLToPath(path);\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction shouldSkip(file: string): boolean {\n return (\n file.startsWith(\"node:\") ||\n file.includes(\"/node_modules/\") ||\n // Node's own frames (`node:internal/…`, or bare `internal/…` on older\n // runtimes); an app folder named `internal` is still an app frame.\n file.startsWith(\"internal/\") ||\n file.startsWith(packageDirectory)\n );\n}\n","import { applyRedact, log } from \"@warlock.js/logger\";\nimport { captureCallerLocation } from \"../caller-location\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** The shape of the event `dataSourceRegistry` emits for `\"query\"`. */\ntype QueryEvent = {\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n sql?: string;\n bindings?: unknown[];\n collection?: string;\n command?: string;\n pipeline?: unknown;\n durationMs: number;\n startedAt: number;\n rowCount?: number;\n error?: unknown;\n};\n\n/** Redacts query bindings through the logger's redaction rules. */\nfunction redactBindings(bindings: unknown[] | undefined): unknown[] | undefined {\n if (!bindings) return bindings;\n\n const redacted = applyRedact(\n {\n type: \"debug\",\n module: \"devtools\",\n action: \"query\",\n message: undefined,\n context: { bindings },\n },\n log.getRedact(),\n );\n\n return (redacted.context as { bindings: unknown[] }).bindings;\n}\n\n/**\n * Feeds every settled database query, from cascade's data source registry,\n * into the collector. A no-op when `@warlock.js/cascade` isn't installed —\n * it is an optional peer.\n */\nexport async function attachQuerySource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let dataSourceRegistry: {\n on(event: \"query\", listener: (event: QueryEvent) => void): void;\n off(event: \"query\", listener: (event: QueryEvent) => void): void;\n };\n\n try {\n ({ dataSourceRegistry } = await import(\"@warlock.js/cascade\"));\n } catch {\n return () => {};\n }\n\n const listener = (event: QueryEvent) => {\n collector.addQuery(currentRequestId(), {\n connection: event.connection,\n driver: event.driver,\n sql: event.sql,\n bindings: toSafeValue(redactBindings(event.bindings)) as unknown[] | undefined,\n collection: event.collection,\n command: event.command,\n pipeline: event.pipeline,\n startedAt: event.startedAt,\n durationMs: event.durationMs,\n rowCount: event.rowCount,\n error:\n event.error === undefined\n ? undefined\n : event.error instanceof Error\n ? event.error.message\n : String(event.error),\n caller: captureCallerLocation(),\n });\n };\n\n dataSourceRegistry.on(\"query\", listener);\n\n return () => dataSourceRegistry.off(\"query\", listener);\n}\n","import type { TracingContext, TracingPhaseInfo, TracingRequestEndInfo } from \"@warlock.js/core\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, ResolvedDevtoolsOptions } from \"../types\";\n\n/**\n * Feeds request timelines from core's tracing hooks into the collector: one\n * `startRequest`/`endRequest` pair per HTTP request, with every named phase\n * in between. Requests to the dashboard's own path are never recorded, so\n * the dashboard never watches itself.\n */\nexport async function attachTracingSource(\n collector: DevtoolsCollector,\n options: ResolvedDevtoolsOptions,\n): Promise<DevtoolsDisposer> {\n const { registerTracingHooks } = await import(\"@warlock.js/core\");\n\n const isDashboardPath = (path: string): boolean => path.startsWith(options.path);\n\n return registerTracingHooks({\n onRequestStart(ctx: TracingContext) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.startRequest({\n id: ctx.requestId,\n method: ctx.method,\n path: ctx.path,\n route: ctx.route,\n startedAt: performance.timeOrigin + performance.now(),\n });\n },\n onPhase(ctx: TracingContext, phase: TracingPhaseInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.addPhase(ctx.requestId, {\n name: phase.name,\n durationMs: phase.durationMs,\n startedAt: phase.startedAt ?? performance.timeOrigin + performance.now() - phase.durationMs,\n attrs:\n phase.attrs === undefined\n ? undefined\n : (toSafeValue(phase.attrs) as Record<string, unknown>),\n });\n },\n onRequestEnd(ctx: TracingContext, result: TracingRequestEndInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.endRequest(ctx.requestId, {\n status: result.status,\n durationMs: result.durationMs,\n error:\n result.error === undefined\n ? undefined\n : result.error instanceof Error\n ? result.error.message\n : String(result.error),\n route: ctx.route,\n });\n },\n });\n}\n","/**\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","/**\n * The CSS variables the dashboard defines for package panels, in both themes.\n *\n * A package panel's stylesheet may use only these variables, plus variables it\n * defines itself (in the same file). Anything else is undefined in the\n * dashboard and renders as the browser default, which is how a panel ends up\n * with unreadable text. The dashboard's own colours are checked for contrast\n * (4.5:1 for the text tokens on `--background` and `--card`) in both themes.\n */\nexport const DEVTOOLS_PANEL_TOKENS: readonly string[] = [\n \"--background\",\n \"--foreground\",\n \"--card\",\n \"--card-foreground\",\n \"--popover\",\n \"--popover-foreground\",\n \"--primary\",\n \"--primary-foreground\",\n \"--secondary\",\n \"--secondary-foreground\",\n \"--muted\",\n \"--muted-foreground\",\n \"--accent\",\n \"--accent-foreground\",\n \"--destructive\",\n \"--border\",\n \"--input\",\n \"--ring\",\n \"--radius\",\n \"--brand\",\n \"--brand-foreground\",\n \"--success\",\n \"--warning\",\n \"--info\",\n \"--chart-1\",\n \"--chart-2\",\n \"--chart-3\",\n \"--chart-4\",\n \"--chart-5\",\n];\n"],"mappings":";;;;;;;;;;;;;AAIA,MAAM,YAAY;;AAGlB,MAAM,aAAa;AAmBnB,SAAgB,uBAAuB,MAAoB,KAAK,KAAuB;CACrF,IAAI,WAAiC;CAErC,OAAO;EACL,KAAK,MAAM;GACT,WAAW;EACb;EACA,MAAM,OAAO;GACX,IAAI,aAAa,MAAM,OAAO,CAAC;GAE/B,MAAM,QAAQ,IAAI,IAAI;GAGtB,QAAO,MAFY,SAAS,OAAO;IAAE,UAAU;IAAO,OAAO;GAAW,CAAC,EAE9D,CAAC,OACT,QAAQ,UAAU,MAAM,YAAY,KAAK,CAAC,CAC1C,KAAK,WAAW;IACf,OAAO,MAAM;IACb,QAAQ,MA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QAAQ;EACN;CACF;AACF;;;;;;AAOA,eAAe,uBAAsE;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;;;;;;;;;;;;;AChhBA,MAAa,wBAA2C;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
1
+ {"version":3,"file":"src-ChI4g-4B.cjs","names":["DevtoolsApiError","createErrorRef","currentRequestId","LogChannel","toSafeValue","currentRequestId","currentRequestId","fileURLToPath","applyRedact","log","currentRequestId","toSafeValue","toSafeValue","createCollector","attachAiSource","attachAgentTraceSource","loadProcessPanel","processesDevtoolsPanel","loadDevtoolsPanels","DEVTOOLS_MOUNTED_KEY","DEVTOOLS_PRODUCTION_DEFAULTS","toAiUnavailableView","describeAiUnavailable","loadAiFeed","attachAiReports","resolveDevtoolsAiOptions","recentAiFailures","checkDevtoolsPanels"],"sources":["../../../../../../../packages/devtools/src/panel-errors.ts","../../../../../../../packages/devtools/src/options.ts","../../../../../../../packages/devtools/src/ai/reports/evaluate.ts","../../../../../../../packages/devtools/src/sources/cache-source.ts","../../../../../../../packages/devtools/src/sources/log-source.ts","../../../../../../../packages/devtools/src/sources/mail-source.ts","../../../../../../../packages/devtools/src/caller-location.ts","../../../../../../../packages/devtools/src/sources/query-source.ts","../../../../../../../packages/devtools/src/sources/tracing-source.ts","../../../../../../../packages/devtools/src/devtools-connector.ts","../../../../../../../packages/devtools/src/panel-tokens.ts"],"sourcesContent":["import type { DevtoolsErrorsView } from \"./production/contracts\";\nimport type { DevtoolsPanelErrorSummary } from \"./types\";\n\n/** Captured errors are offered to panels for the last hour. */\nconst WINDOW_MS = 3_600_000;\n\n/** The most error groups one read maps. */\nconst MAX_GROUPS = 500;\n\n/** The part of the insights a panel's error counts come from. */\ntype ErrorInsights = {\n errors(query: { instance: string; limit: number }): Promise<DevtoolsErrorsView>;\n};\n\n/**\n * What a panel factory receives as `context.errors`. Panels load before the\n * capture starts, so this reads through a source the connector binds once the\n * insights exist; until then (and when they never start) it answers an empty\n * list. Only counts, the route and the class name leave: no message, no stack.\n */\nexport type PanelErrorSource = {\n read: () => Promise<readonly DevtoolsPanelErrorSummary[]>;\n /** Binds the insights (development: this process; production: every instance). */\n bind(insights: ErrorInsights | null): void;\n};\n\nexport function createPanelErrorSource(now: () => number = Date.now): PanelErrorSource {\n let insights: ErrorInsights | null = null;\n\n return {\n bind(next) {\n insights = next;\n },\n async read() {\n if (insights === null) return [];\n\n const since = now() - WINDOW_MS;\n const view = await insights.errors({ instance: \"all\", limit: MAX_GROUPS });\n\n return view.groups\n .filter((group) => group.lastSeen >= since)\n .map((group) => ({\n route: group.route,\n status: group.status,\n name: group.name,\n source: group.source,\n count: group.count,\n firstSeen: group.firstSeen,\n lastSeen: group.lastSeen,\n }));\n },\n };\n}\n","import { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport type { DevtoolsOptions, ResolvedDevtoolsOptions } from \"./types\";\n\n/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */\nexport function resolveDevtoolsOptions(options: DevtoolsOptions = {}): ResolvedDevtoolsOptions {\n const path = (options.path ?? \"/__warlock\").replace(/\\/+$/, \"\");\n const maxRequests = options.maxRequests ?? 200;\n const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;\n\n if (!path || !path.startsWith(\"/\")) {\n throw new Error('Devtools option \"path\" must be a non-root path starting with \"/\".');\n }\n\n if (maxRequests < 1) {\n throw new Error('Devtools option \"maxRequests\" must be at least 1.');\n }\n\n if (nPlusOneThreshold < 2) {\n throw new Error('Devtools option \"nPlusOneThreshold\" must be at least 2.');\n }\n\n // Validates the AI options; the mode defaults are applied where the mode is known.\n if (options.ai !== undefined) resolveDevtoolsAiOptions(options.ai, \"development\");\n\n return {\n path,\n maxRequests,\n nPlusOneThreshold,\n allowedHosts: options.allowedHosts ?? [],\n allowProxied: options.allowProxied ?? false,\n panels: options.panels ?? [],\n ...(options.ai === undefined ? {} : { ai: options.ai }),\n ...(options.production === undefined ? {} : { production: options.production }),\n };\n}\n","import type {\n DevtoolsAiEvaluateRequest,\n DevtoolsAiEvaluateResult,\n DevtoolsAiEvaluateView,\n} from \"../../production/contracts\";\nimport { createErrorRef, DevtoolsApiError } from \"../../production/errors\";\nimport type { DevtoolsAgentTraceSource } from \"../../sources/agent-trace-source\";\n\nconst MAX_PROMPTS = 50;\nconst MAX_RUNS_SCANNED = 300;\nconst MAX_SYSTEM_PROMPT = 100_000;\nconst MAX_INSTRUCTIONS = 4000;\nconst PREVIEW_LENGTH = 200;\n\ntype EvaluateModule = {\n getEvaluateConfig?: () => EvaluateConfigLike | undefined;\n evaluateSystemPrompt?: (\n systemPrompt: string,\n config: EvaluateConfigLike,\n instructions?: string,\n ) => Promise<{ score?: number; issues?: string[] }>;\n};\n\ntype ModelLike = { name?: string; provider?: string };\n\ntype EvaluateConfigLike = {\n model: ModelLike | (() => ModelLike | Promise<ModelLike>);\n instructions?: string;\n};\n\n/** What the Evaluate routes use; injected so specs need no model. */\nexport type DevtoolsAiEvaluator = {\n /** The page data: whether a judge is configured and the recent distinct system prompts. */\n view(): Promise<Extract<DevtoolsAiEvaluateView, { available: true }>>;\n /**\n * Grades a prompt with Panoptic's `evaluateSystemPrompt`. Throws\n * `DevtoolsApiError` `input.invalid` (both or neither of runId/systemPrompt,\n * sizes), `ai.evaluate-unavailable` (no judge configured),\n * `ai.prompt-not-found` (run gone or its text not kept) or\n * `ai.evaluate-failed` (the judge threw; logged with the reference).\n */\n evaluate(request: DevtoolsAiEvaluateRequest): Promise<DevtoolsAiEvaluateResult>;\n};\n\nfunction judgeLabel(model: ModelLike): string {\n return typeof model.provider === \"string\" && typeof model.name === \"string\"\n ? `${model.provider}/${model.name}`\n : (model.name ?? \"custom model\");\n}\n\n/** Builds the evaluator over the agent traces and Panoptic's evaluate helpers (loaded lazily). */\nexport function createAiEvaluator(input: {\n agentTraces: DevtoolsAgentTraceSource;\n load?: (name: string) => Promise<unknown>;\n warn?: (message: string) => void;\n}): DevtoolsAiEvaluator {\n const load = input.load ?? (() => import(\"@warlock.js/ai-panoptic\"));\n\n /** Panoptic's evaluate helpers, or `undefined` when Panoptic (or its evaluate support) is not there. */\n async function panoptic(): Promise<(EvaluateModule & Required<EvaluateModule>) | undefined> {\n try {\n const module = (await load(\"@warlock.js/ai-panoptic\")) as EvaluateModule;\n\n return typeof module.getEvaluateConfig === \"function\" &&\n typeof module.evaluateSystemPrompt === \"function\"\n ? (module as EvaluateModule & Required<EvaluateModule>)\n : undefined;\n } catch {\n return undefined;\n }\n }\n\n const unavailable = (): DevtoolsApiError => new DevtoolsApiError(\"ai.evaluate-unavailable\");\n\n return {\n async view() {\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n const byHash = new Map<\n string,\n { agents: string[]; runId: string; startedAt: string; text: string }\n >();\n const runs = input.agentTraces\n .list()\n .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || 0)\n .slice(0, MAX_RUNS_SCANNED);\n\n for (const run of runs) {\n const prompt = input.agentTraces.get(run.runId)?.systemPrompt;\n\n if (!prompt || typeof prompt.text !== \"string\" || prompt.text === \"\") continue;\n\n const known = byHash.get(prompt.hash);\n\n if (known) {\n if (!known.agents.includes(run.agent)) known.agents.push(run.agent);\n } else {\n byHash.set(prompt.hash, {\n agents: [run.agent],\n runId: run.runId,\n startedAt: run.startedAt,\n text: prompt.text,\n });\n }\n }\n\n return {\n available: true as const,\n configured: config !== undefined,\n judge:\n config === undefined\n ? null\n : typeof config.model === \"function\"\n ? \"custom model\"\n : judgeLabel(config.model),\n instructions: config?.instructions ?? \"\",\n prompts: [...byHash.entries()].slice(0, MAX_PROMPTS).map(([hash, item]) => ({\n hash,\n agents: item.agents,\n runId: item.runId,\n lastSeenAt: item.startedAt,\n preview: item.text.slice(0, PREVIEW_LENGTH),\n length: item.text.length,\n })),\n };\n },\n\n async evaluate(request) {\n const { runId, systemPrompt, instructions } = request;\n\n if ((runId === undefined) === (systemPrompt === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (\n (runId !== undefined && (typeof runId !== \"string\" || runId === \"\")) ||\n (systemPrompt !== undefined &&\n (typeof systemPrompt !== \"string\" ||\n systemPrompt.trim() === \"\" ||\n systemPrompt.length > MAX_SYSTEM_PROMPT)) ||\n (instructions !== undefined &&\n (typeof instructions !== \"string\" || instructions.length > MAX_INSTRUCTIONS))\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const module = await panoptic();\n let config: EvaluateConfigLike | undefined;\n\n try {\n config = module?.getEvaluateConfig();\n } catch {\n config = undefined;\n }\n\n if (!module || !config) throw unavailable();\n\n let text = systemPrompt;\n\n if (runId !== undefined) {\n text = input.agentTraces.get(runId)?.systemPrompt?.text;\n\n if (typeof text !== \"string\" || text === \"\")\n throw new DevtoolsApiError(\"ai.prompt-not-found\");\n }\n\n const started = Date.now();\n\n try {\n const model = typeof config.model === \"function\" ? await config.model() : config.model;\n const verdict = await module.evaluateSystemPrompt(\n text as string,\n { ...config, model },\n instructions,\n );\n\n return {\n score: typeof verdict.score === \"number\" ? verdict.score : null,\n issues: Array.isArray(verdict.issues) ? verdict.issues.map(String) : [],\n judge: judgeLabel(model),\n durationMs: Date.now() - started,\n };\n } catch (error) {\n const ref = createErrorRef();\n\n input.warn?.(\n `Devtools evaluate error ${ref}: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n throw new DevtoolsApiError(\"ai.evaluate-failed\", { ref, cause: error });\n }\n },\n };\n}\n","import { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCacheOperation, DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** Cache events the dashboard's waterfall and background bucket care about. */\nconst EVENT_TYPES = [\"hit\", \"miss\", \"set\", \"removed\", \"invalidated\", \"flushed\"] as const;\n\n/** The shape `cache.on(event, handler)` hands the handler. */\ntype CacheEventData = {\n key?: string;\n driver: string;\n tags?: string[];\n keys?: string[];\n durationMs?: number;\n};\n\n/**\n * Feeds cache hits, misses and mutations, from `@warlock.js/cache`, into the\n * collector. A no-op when `@warlock.js/cache` isn't installed — it is an\n * optional peer.\n */\nexport async function attachCacheSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let cache: {\n on(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n off(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n };\n\n try {\n ({ cache } = await import(\"@warlock.js/cache\"));\n } catch {\n return () => {};\n }\n\n const handlers = EVENT_TYPES.map((type) => {\n const handler = (data: CacheEventData) => {\n const operation: DevtoolsCacheOperation = {\n type,\n driver: data.driver,\n key: data.key,\n tags: data.tags,\n keys: data.keys,\n at: Date.now(),\n durationMs: data.durationMs,\n };\n\n collector.addCacheOperation(currentRequestId(), operation);\n };\n\n cache.on(type, handler);\n\n return { type, handler };\n });\n\n return () => {\n for (const { type, handler } of handlers) cache.off(type, handler);\n };\n}\n","import { LogChannel, log, type LoggingData } from \"@warlock.js/logger\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsLogEntry } from \"../types\";\n\n/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */\nfunction toDevtoolsLevel(type: LoggingData[\"type\"]): DevtoolsLogEntry[\"level\"] {\n return type === \"fatal\" ? \"error\" : type;\n}\n\n/**\n * The entry's message as text. `request.log(error)` and friends log an Error\n * (or any value) as the message; kept as is, it reached the dashboard as `{}`.\n */\nfunction messageText(message: unknown): string {\n if (typeof message === \"string\") return message;\n if (message instanceof Error) return `${message.name}: ${message.message}`;\n\n try {\n return JSON.stringify(message) ?? String(message);\n } catch {\n return String(message);\n }\n}\n\nclass DevtoolsLogChannel extends LogChannel {\n public override name = \"devtools\";\n public active = true;\n\n public constructor(private readonly collector: DevtoolsCollector) {\n super();\n }\n\n public log(data: LoggingData): void {\n if (!this.active) return;\n\n // Already passed through the logger's redaction floor (`Logger.log`\n // applies it before invoking any channel). It is still app data, and can\n // hold live objects (a request, its socket), so a JSON-safe snapshot is\n // kept instead of the object itself.\n const entry: DevtoolsLogEntry = {\n level: toDevtoolsLevel(data.type),\n module: data.module,\n action: data.action,\n message: messageText(data.message),\n at: Date.now(),\n context: toSafeValue(data.context),\n };\n\n this.collector.addLog(currentRequestId(), entry);\n }\n}\n\n/**\n * Feeds every log entry, from `@warlock.js/logger`, into the collector by\n * registering an additional channel. `Logger` has no way to remove a\n * channel, so the disposer flag-ignores further entries instead — the\n * channel stays registered for the process's lifetime.\n */\nexport async function attachLogSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const channel = new DevtoolsLogChannel(collector);\n\n log.addChannel(channel);\n\n return () => {\n channel.active = false;\n };\n}\n","import type { CapturedMail, MailAddress, MailAttachment } from \"@warlock.js/core\";\nimport { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsMailAttachment } from \"../types\";\n\nfunction addressToString(address: MailAddress | undefined): string | undefined {\n if (!address) return undefined;\n\n return typeof address === \"string\" ? address : `${address.name} <${address.address}>`;\n}\n\nfunction attachmentSize(attachment: MailAttachment): number | undefined {\n if (typeof attachment.content === \"string\") return Buffer.byteLength(attachment.content);\n if (Buffer.isBuffer(attachment.content)) return attachment.content.length;\n\n return undefined;\n}\n\nfunction toDevtoolsAttachment(attachment: MailAttachment): DevtoolsMailAttachment {\n return {\n filename: attachment.filename,\n contentType: attachment.contentType,\n size: attachmentSize(attachment),\n };\n}\n\n/**\n * Feeds mails captured in development mode, from core's `mailEvents`, into\n * the collector. The captured attachments carry their content, but only\n * metadata is stored — the bytes are never kept.\n */\nexport async function attachMailSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const { mailEvents } = await import(\"@warlock.js/core\");\n\n const subscription = mailEvents.onCaptured((mail: CapturedMail) => {\n const { normalized } = mail;\n\n collector.addMail({\n id: mail.id,\n requestId: currentRequestId(),\n capturedAt: mail.timestamp.getTime(),\n from: addressToString(normalized.from),\n to: normalized.to,\n cc: normalized.cc,\n bcc: normalized.bcc,\n subject: normalized.subject,\n html: normalized.html,\n text: normalized.text,\n headers: normalized.headers,\n attachments: normalized.attachments.map(toDevtoolsAttachment),\n });\n });\n\n return () => subscription.unsubscribe();\n}\n","import { fileURLToPath } from \"node:url\";\n\nimport type { DevtoolsCallerLocation } from \"./types\";\n\nconst packageDirectory = normalizePath(fileURLToPath(new URL(\"../\", import.meta.url)));\n\n/** Returns the first non-runtime, non-devtools frame in a V8 stack trace. */\nexport function captureCallerLocation(\n stack: string = new Error().stack ?? \"\",\n): DevtoolsCallerLocation | undefined {\n for (const line of stack.split(\"\\n\")) {\n const frame = parseFrame(line);\n if (!frame || shouldSkip(frame.file)) continue;\n return frame;\n }\n return undefined;\n}\n\nfunction parseFrame(frame: string): DevtoolsCallerLocation | undefined {\n const match = frame.match(/\\bat\\s+(?:.*?\\s+\\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/);\n const [, rawFile, line, column] = match ?? [];\n if (!rawFile || !line || !column) return undefined;\n const file = normalizePath(rawFile);\n return { file, line: Number(line), column: Number(column) };\n}\n\n/** A drive-letter file URL names a Windows path on whichever host decodes it. */\nconst WINDOWS_DRIVE_FILE_URL = /^file:\\/\\/\\/[A-Za-z]:/;\n\nfunction normalizePath(path: string): string {\n const decoded = !path.startsWith(\"file:\")\n ? path\n : WINDOWS_DRIVE_FILE_URL.test(path)\n ? fileURLToPath(path, { windows: true })\n : fileURLToPath(path);\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction shouldSkip(file: string): boolean {\n return (\n file.startsWith(\"node:\") ||\n file.includes(\"/node_modules/\") ||\n // Node's own frames (`node:internal/…`, or bare `internal/…` on older\n // runtimes); an app folder named `internal` is still an app frame.\n file.startsWith(\"internal/\") ||\n file.startsWith(packageDirectory)\n );\n}\n","import { applyRedact, log } from \"@warlock.js/logger\";\nimport { captureCallerLocation } from \"../caller-location\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** The shape of the event `dataSourceRegistry` emits for `\"query\"`. */\ntype QueryEvent = {\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n sql?: string;\n bindings?: unknown[];\n collection?: string;\n command?: string;\n pipeline?: unknown;\n durationMs: number;\n startedAt: number;\n rowCount?: number;\n error?: unknown;\n};\n\n/** Redacts query bindings through the logger's redaction rules. */\nfunction redactBindings(bindings: unknown[] | undefined): unknown[] | undefined {\n if (!bindings) return bindings;\n\n const redacted = applyRedact(\n {\n type: \"debug\",\n module: \"devtools\",\n action: \"query\",\n message: undefined,\n context: { bindings },\n },\n log.getRedact(),\n );\n\n return (redacted.context as { bindings: unknown[] }).bindings;\n}\n\n/**\n * Feeds every settled database query, from cascade's data source registry,\n * into the collector. A no-op when `@warlock.js/cascade` isn't installed —\n * it is an optional peer.\n */\nexport async function attachQuerySource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let dataSourceRegistry: {\n on(event: \"query\", listener: (event: QueryEvent) => void): void;\n off(event: \"query\", listener: (event: QueryEvent) => void): void;\n };\n\n try {\n ({ dataSourceRegistry } = await import(\"@warlock.js/cascade\"));\n } catch {\n return () => {};\n }\n\n const listener = (event: QueryEvent) => {\n collector.addQuery(currentRequestId(), {\n connection: event.connection,\n driver: event.driver,\n sql: event.sql,\n bindings: toSafeValue(redactBindings(event.bindings)) as unknown[] | undefined,\n collection: event.collection,\n command: event.command,\n pipeline: event.pipeline,\n startedAt: event.startedAt,\n durationMs: event.durationMs,\n rowCount: event.rowCount,\n error:\n event.error === undefined\n ? undefined\n : event.error instanceof Error\n ? event.error.message\n : String(event.error),\n caller: captureCallerLocation(),\n });\n };\n\n dataSourceRegistry.on(\"query\", listener);\n\n return () => dataSourceRegistry.off(\"query\", listener);\n}\n","import type { TracingContext, TracingPhaseInfo, TracingRequestEndInfo } from \"@warlock.js/core\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, ResolvedDevtoolsOptions } from \"../types\";\n\n/**\n * Feeds request timelines from core's tracing hooks into the collector: one\n * `startRequest`/`endRequest` pair per HTTP request, with every named phase\n * in between. Requests to the dashboard's own path are never recorded, so\n * the dashboard never watches itself.\n */\nexport async function attachTracingSource(\n collector: DevtoolsCollector,\n options: ResolvedDevtoolsOptions,\n): Promise<DevtoolsDisposer> {\n const { registerTracingHooks } = await import(\"@warlock.js/core\");\n\n const isDashboardPath = (path: string): boolean => path.startsWith(options.path);\n\n return registerTracingHooks({\n onRequestStart(ctx: TracingContext) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.startRequest({\n id: ctx.requestId,\n method: ctx.method,\n path: ctx.path,\n route: ctx.route,\n startedAt: performance.timeOrigin + performance.now(),\n });\n },\n onPhase(ctx: TracingContext, phase: TracingPhaseInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.addPhase(ctx.requestId, {\n name: phase.name,\n durationMs: phase.durationMs,\n startedAt: phase.startedAt ?? performance.timeOrigin + performance.now() - phase.durationMs,\n attrs:\n phase.attrs === undefined\n ? undefined\n : (toSafeValue(phase.attrs) as Record<string, unknown>),\n });\n },\n onRequestEnd(ctx: TracingContext, result: TracingRequestEndInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.endRequest(ctx.requestId, {\n status: result.status,\n durationMs: result.durationMs,\n error:\n result.error === undefined\n ? undefined\n : result.error instanceof Error\n ? result.error.message\n : String(result.error),\n route: ctx.route,\n });\n },\n });\n}\n","/**\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","/**\n * The CSS variables the dashboard defines for package panels, in both themes.\n *\n * A package panel's stylesheet may use only these variables, plus variables it\n * defines itself (in the same file). Anything else is undefined in the\n * dashboard and renders as the browser default, which is how a panel ends up\n * with unreadable text. The dashboard's own colours are checked for contrast\n * (4.5:1 for the text tokens on `--background` and `--card`) in both themes.\n */\nexport const DEVTOOLS_PANEL_TOKENS: readonly string[] = [\n \"--background\",\n \"--foreground\",\n \"--card\",\n \"--card-foreground\",\n \"--popover\",\n \"--popover-foreground\",\n \"--primary\",\n \"--primary-foreground\",\n \"--secondary\",\n \"--secondary-foreground\",\n \"--muted\",\n \"--muted-foreground\",\n \"--accent\",\n \"--accent-foreground\",\n \"--destructive\",\n \"--border\",\n \"--input\",\n \"--ring\",\n \"--radius\",\n \"--brand\",\n \"--brand-foreground\",\n \"--success\",\n \"--warning\",\n \"--info\",\n \"--chart-1\",\n \"--chart-2\",\n \"--chart-3\",\n \"--chart-4\",\n \"--chart-5\",\n];\n"],"mappings":";;;;;;;;;;;;;AAIA,MAAM,YAAY;;AAGlB,MAAM,aAAa;AAmBnB,SAAgB,uBAAuB,MAAoB,KAAK,KAAuB;CACrF,IAAI,WAAiC;CAErC,OAAO;EACL,KAAK,MAAM;GACT,WAAW;EACb;EACA,MAAM,OAAO;GACX,IAAI,aAAa,MAAM,OAAO,CAAC;GAE/B,MAAM,QAAQ,IAAI,I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AM,EAAE,aAAa,MAAM,8BAA8B;CAEzD,OAAO;AACT;;;;;;;AAUA,eAAe,qBAA0D;CACvE,IAAI;EAEF,MAAM,SAAQ,MAD8B,OAAO,oBACjC,CAAC;EAEnB,OAAO,OAAO,UAAU,aAAc,QAA2B;CACnE,QAAQ;EACN;CACF;AACF;;;;;;AAOA,eAAe,uBAAsE;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;;;;;;;;;;;;;AChhBA,MAAa,wBAA2C;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
@@ -78,6 +78,14 @@ function tokenHash(token) {
78
78
  /** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */
79
79
  const uniformNotFound = /* @__PURE__ */ new WeakSet();
80
80
  /**
81
+ * Requests refused before their body was read. Fastify reads the body of such a
82
+ * request next, as it does for an unknown URL, and `preValidation` then answers
83
+ * the refusal: a malformed, oversized or unsupported body gets the app's own
84
+ * 400, 413 or 415 (the plugin's error handler hands those on), never a 404 that
85
+ * only a dashboard path would give.
86
+ */
87
+ const refusedBeforeBody = /* @__PURE__ */ new WeakSet();
88
+ /**
81
89
  * The origin the browser must send for an unsafe request: `production.origin`,
82
90
  * else the scheme and host the request was addressed to.
83
91
  */
@@ -132,6 +140,16 @@ function mountProductionDevtools(server, deps) {
132
140
  }
133
141
  return reply;
134
142
  };
143
+ /**
144
+ * Refuses a request in the gate with the uniform answer. A request that may
145
+ * carry a body is answered after Fastify has read it, so it gets the same
146
+ * parsing errors, in the same order and at the same cost, as an unknown URL.
147
+ */
148
+ const refuse = async (request, reply) => {
149
+ if (request.method === "GET" || request.method === "HEAD") return notFound(request, reply);
150
+ uniformNotFound.add(request);
151
+ refusedBeforeBody.add(request);
152
+ };
135
153
  const streamSession = async (request) => {
136
154
  const authenticated = devtoolsRequestContext(request)?.authenticated;
137
155
  if (!authenticated) throw new Error("A dashboard stream was opened without a session.");
@@ -184,10 +202,10 @@ function mountProductionDevtools(server, deps) {
184
202
  warn(`The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`);
185
203
  open = false;
186
204
  }
187
- if (!open) return notFound(request, reply);
205
+ if (!open) return refuse(request, reply);
188
206
  const client = resolveClient(request, production.trustedProxies);
189
- if (production.requireHttps && client.proto !== "https") return notFound(request, reply);
190
- if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) return notFound(request, reply);
207
+ if (production.requireHttps && client.proto !== "https") return refuse(request, reply);
208
+ if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) return refuse(request, reply);
191
209
  const userAgent = request.headers["user-agent"];
192
210
  const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;
193
211
  const meta = {
@@ -209,18 +227,18 @@ function mountProductionDevtools(server, deps) {
209
227
  pattern,
210
228
  authenticated: null
211
229
  });
212
- if (method !== "GET" && method !== "HEAD") return notFound(request, reply);
230
+ if (method !== "GET" && method !== "HEAD") return refuse(request, reply);
213
231
  const search = sent.includes("?") ? `?${sent.split("?").slice(1).join("?")}` : "";
214
232
  return reply.redirect(`${prefix}/${search}`, 308);
215
233
  }
216
234
  const tab = tabOf(pattern);
217
- if (tab !== void 0 && !enabledTabs.has(tab)) return notFound(request, reply);
235
+ if (tab !== void 0 && !enabledTabs.has(tab)) return refuse(request, reply);
218
236
  const rule = lookup(method, pattern);
219
237
  const access = rule?.access ?? { type: "admin" };
220
238
  let authenticated = null;
221
239
  if (access.type === "share") {
222
240
  const grant = share ? await share.authorize(request, meta) : null;
223
- if (grant === null) return notFound(request, reply);
241
+ if (grant === null) return refuse(request, reply);
224
242
  setDevtoolsRequestContext(request, {
225
243
  client,
226
244
  meta,
@@ -236,9 +254,9 @@ function mountProductionDevtools(server, deps) {
236
254
  authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));
237
255
  } catch (error) {
238
256
  warn(`The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`);
239
- return notFound(request, reply);
257
+ return refuse(request, reply);
240
258
  }
241
- if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) return notFound(request, reply);
259
+ if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) return refuse(request, reply);
242
260
  if (access.type === "admin" && authenticated.account.role !== "admin") {
243
261
  setDevtoolsRequestContext(request, {
244
262
  client,
@@ -259,11 +277,11 @@ function mountProductionDevtools(server, deps) {
259
277
  });
260
278
  if (SAFE_METHODS.has(method)) return;
261
279
  if (!originAllowed(request, expectedOrigin)) {
262
- if (authenticated === null) return notFound(request, reply);
280
+ if (authenticated === null) return refuse(request, reply);
263
281
  throw new DevtoolsApiError("csrf.invalid");
264
282
  }
265
283
  if (hasBody(request) && !isJson(request)) {
266
- if (pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);
284
+ if (pattern === SHARE_OPEN_PATTERN) return refuse(request, reply);
267
285
  throw new DevtoolsApiError("input.invalid");
268
286
  }
269
287
  if (authenticated !== null) {
@@ -271,6 +289,10 @@ function mountProductionDevtools(server, deps) {
271
289
  if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) throw new DevtoolsApiError("csrf.invalid");
272
290
  }
273
291
  });
292
+ instance.addHook("preValidation", async (request, reply) => {
293
+ if (!refusedBeforeBody.has(request)) return;
294
+ return notFound(request, reply);
295
+ });
274
296
  instance.addHook("onSend", async (request, reply, payload) => {
275
297
  if (uniformNotFound.has(request)) return payload;
276
298
  for (const name of Object.keys(reply.getHeaders())) if (name.startsWith("access-control-")) reply.removeHeader(name);