@warlock.js/devtools 5.60.0 → 5.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/cjs/{extract-8kaX_cUV.cjs → ai-source-CeHZDYG1.cjs} +449 -408
  3. package/cjs/ai-source-CeHZDYG1.cjs.map +1 -0
  4. package/cjs/{attach-D5aMqUnA.cjs → attach-D9gWc6lU.cjs} +19 -19
  5. package/cjs/attach-D9gWc6lU.cjs.map +1 -0
  6. package/cjs/{boot-Dg5YZGGR.cjs → boot-Guumt-du.cjs} +13 -10
  7. package/cjs/boot-Guumt-du.cjs.map +1 -0
  8. package/cjs/{capture-CBgONYhk.cjs → capture-D2k0GnBN.cjs} +21 -420
  9. package/cjs/capture-D2k0GnBN.cjs.map +1 -0
  10. package/cjs/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
  11. package/cjs/collector-BfC4v87v.cjs.map +1 -0
  12. package/cjs/errors-DNQ-g49I.cjs.map +1 -1
  13. package/cjs/{http-DCVCf44M.cjs → http-CPbhLN61.cjs} +13 -7
  14. package/cjs/http-CPbhLN61.cjs.map +1 -0
  15. package/cjs/index.cjs +1 -1
  16. package/cjs/{insights-CFof59kF.cjs → insights-COA3u37q.cjs} +53 -21
  17. package/cjs/insights-COA3u37q.cjs.map +1 -0
  18. package/cjs/{process-panel-D3D9Y_dc.cjs → process-panel-Dev6eg_f.cjs} +2 -2
  19. package/cjs/{process-panel-D3D9Y_dc.cjs.map → process-panel-Dev6eg_f.cjs.map} +1 -1
  20. package/cjs/query-shape-DShKQa0x.cjs +45 -0
  21. package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
  22. package/cjs/redact-DQ28mDzr.cjs +533 -0
  23. package/cjs/redact-DQ28mDzr.cjs.map +1 -0
  24. package/cjs/{runs-DECWPGnq.cjs → runs-DXTf_o5P.cjs} +10 -11
  25. package/cjs/runs-DXTf_o5P.cjs.map +1 -0
  26. package/cjs/{server-CC5DpObz.cjs → server-Dc0YdP6Y.cjs} +6 -6
  27. package/cjs/{server-CC5DpObz.cjs.map → server-Dc0YdP6Y.cjs.map} +1 -1
  28. package/cjs/{src-VyOjEEAo.cjs → src-Ca1gNdZj.cjs} +21 -18
  29. package/cjs/src-Ca1gNdZj.cjs.map +1 -0
  30. package/cjs/{stream-route-DFHuIWgg.cjs → stream-route-qEHoPVth.cjs} +25 -22
  31. package/cjs/stream-route-qEHoPVth.cjs.map +1 -0
  32. package/esm/ai/reports/runs.mjs +5 -6
  33. package/esm/ai/reports/runs.mjs.map +1 -1
  34. package/esm/ai/rollup/extract.mjs +21 -4
  35. package/esm/ai/rollup/extract.mjs.map +1 -1
  36. package/esm/devtools-connector.d.mts.map +1 -1
  37. package/esm/devtools-connector.mjs +4 -1
  38. package/esm/devtools-connector.mjs.map +1 -1
  39. package/esm/index.d.mts +2 -2
  40. package/esm/panels.mjs +14 -1
  41. package/esm/panels.mjs.map +1 -1
  42. package/esm/production/boot.mjs +5 -2
  43. package/esm/production/boot.mjs.map +1 -1
  44. package/esm/production/contracts.d.mts +17 -4
  45. package/esm/production/contracts.d.mts.map +1 -1
  46. package/esm/production/contracts.mjs.map +1 -1
  47. package/esm/production/http/mount.mjs +8 -2
  48. package/esm/production/http/mount.mjs.map +1 -1
  49. package/esm/production/http/share.mjs.map +1 -1
  50. package/esm/production/index.d.mts +2 -2
  51. package/esm/production/insights/jobs.mjs +45 -11
  52. package/esm/production/insights/jobs.mjs.map +1 -1
  53. package/esm/production/options.d.mts +5 -0
  54. package/esm/production/options.d.mts.map +1 -1
  55. package/esm/production/options.mjs.map +1 -1
  56. package/esm/server/ai-routes.mjs +11 -5
  57. package/esm/server/ai-routes.mjs.map +1 -1
  58. package/esm/server/panel-routes.mjs.map +1 -1
  59. package/esm/server/ui-assets.mjs +4 -7
  60. package/esm/server/ui-assets.mjs.map +1 -1
  61. package/esm/sources/ai-source.d.mts.map +1 -1
  62. package/esm/sources/ai-source.mjs +3 -3
  63. package/esm/sources/ai-source.mjs.map +1 -1
  64. package/esm/types.d.mts +7 -4
  65. package/esm/types.d.mts.map +1 -1
  66. package/llms-full.txt +27 -24
  67. package/package.json +8 -8
  68. package/skills/SKILL.md +27 -24
  69. package/ui/dashboard/assets/app.css +1 -1
  70. package/ui/dashboard/assets/app.js +2 -2
  71. package/ui/dashboard/build-info.json +7 -7
  72. package/cjs/attach-D5aMqUnA.cjs.map +0 -1
  73. package/cjs/boot-Dg5YZGGR.cjs.map +0 -1
  74. package/cjs/capture-CBgONYhk.cjs.map +0 -1
  75. package/cjs/collector-CJbQbzzK.cjs.map +0 -1
  76. package/cjs/extract-8kaX_cUV.cjs.map +0 -1
  77. package/cjs/histogram-CkoVizdf.cjs +0 -102
  78. package/cjs/histogram-CkoVizdf.cjs.map +0 -1
  79. package/cjs/http-DCVCf44M.cjs.map +0 -1
  80. package/cjs/insights-CFof59kF.cjs.map +0 -1
  81. package/cjs/runs-DECWPGnq.cjs.map +0 -1
  82. package/cjs/src-VyOjEEAo.cjs.map +0 -1
  83. package/cjs/stream-route-DFHuIWgg.cjs.map +0 -1
@@ -1,6 +1,6 @@
1
1
  const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
2
2
  const require_errors = require("./errors-DNQ-g49I.cjs");
3
- const require_extract = require("./extract-8kaX_cUV.cjs");
3
+ const require_ai_source = require("./ai-source-CeHZDYG1.cjs");
4
4
  let node_fs = require("node:fs");
5
5
  let node_path = require("node:path");
6
6
  node_path = require_app_versions.__toESM(node_path, 1);
@@ -183,10 +183,9 @@ const TYPES = /* @__PURE__ */ new Set([
183
183
  ]);
184
184
  /** The model identity a span reports, as `provider/model`. */
185
185
  function modelOf(span) {
186
- const model = span.attributes?.["agent.model.name"];
187
- const provider = span.attributes?.["agent.model.provider"];
188
- if (typeof model !== "string") return null;
189
- return typeof provider === "string" ? `${provider}/${model}` : model;
186
+ const { name, provider } = require_ai_source.spanModelOf(span);
187
+ if (name === void 0) return null;
188
+ return provider !== void 0 ? `${provider}/${name}` : name;
190
189
  }
191
190
  /** A span's own priced cost, else the sum of its children (a wrapper root carries tokens but no cost). */
192
191
  function spanCost(span, totalCost) {
@@ -307,7 +306,7 @@ function listAiRuns(traces, query, options) {
307
306
  count: matching.length,
308
307
  failed: matching.filter((trace) => trace.root.status === "failed").length,
309
308
  estimatedCostUsd: rows.reduce((sum, row) => sum + (row.cost ?? 0), 0),
310
- unpricedRuns: matching.filter((trace) => require_extract.traceToRollupDeltas(trace, totalCost).some((delta) => delta.unpricedRuns > 0)).length,
309
+ unpricedRuns: matching.filter((trace) => require_ai_source.traceToRollupDeltas(trace, totalCost).some((delta) => delta.unpricedRuns > 0)).length,
311
310
  p50Ms: durations.length > 0 ? helpers.percentile(durations, 50) : null,
312
311
  p95Ms: durations.length > 0 ? helpers.percentile(durations, 95) : null
313
312
  },
@@ -330,18 +329,18 @@ function recentAiFailures(traces, limit, filter) {
330
329
  const failures = [];
331
330
  for (const trace of traces) {
332
331
  const visit = (span) => {
333
- if (require_extract.isAiModelSpan(span) && FAILED_STATUSES.has(span.status)) {
332
+ if (require_ai_source.isAiModelSpan(span) && FAILED_STATUSES.has(span.status)) {
334
333
  const parsedEnd = Date.parse(span.endedAt);
335
334
  const endedAt = Number.isNaN(parsedEnd) ? Date.parse(trace.endedAt) || 0 : parsedEnd;
336
- const names = require_extract.aiRollupNamesOf(span);
335
+ const names = require_ai_source.aiRollupNamesOf(span);
337
336
  if (!filter || endedAt >= filter.from && endedAt < filter.to && (filter.agent === void 0 || names.agent === filter.agent) && (filter.provider === void 0 || names.provider === filter.provider) && (filter.model === void 0 || names.provider === filter.model.provider && names.model === filter.model.model)) {
338
337
  const message = span.error?.message;
339
338
  failures.push({
340
339
  traceId: trace.traceId,
341
340
  agent: span.name,
342
- model: typeof span.attributes?.["agent.model.name"] === "string" ? `${names.provider}/${names.model}` : null,
341
+ model: require_ai_source.spanModelOf(span).name !== void 0 ? `${names.provider}/${names.model}` : null,
343
342
  status: span.status,
344
- category: require_extract.classifyAiError(span.status, span.error?.type),
343
+ category: require_ai_source.classifyAiError(span.status, span.error?.type),
345
344
  code: span.error?.type ?? null,
346
345
  message: typeof message === "string" ? message.slice(0, MESSAGE_LIMIT) : null,
347
346
  endedAt,
@@ -387,4 +386,4 @@ Object.defineProperty(exports, "resolveUiRoot", {
387
386
  return resolveUiRoot;
388
387
  }
389
388
  });
390
- //# sourceMappingURL=runs-DECWPGnq.cjs.map
389
+ //# sourceMappingURL=runs-DXTf_o5P.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runs-DXTf_o5P.cjs","names":["existsSync","path","readFileSync","fileURLToPath","spanModelOf","DevtoolsApiError","traceToRollupDeltas","isAiModelSpan","aiRollupNamesOf","classifyAiError"],"sources":["../../../../../../../packages/devtools/src/ui-root.ts","../../../../../../../packages/devtools/src/sources/agent-trace-source.ts","../../../../../../../packages/devtools/src/ai/reports/runs.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet cachedUiRoot: string | undefined;\n\n/**\n * Whether `dir` is this package's root: it has the built dashboard\n * (`ui/dashboard/index.html`) or, before the first build, the Processes panel\n * view (`ui/panels/processes.js`), beside a `package.json` named\n * `@warlock.js/devtools`.\n */\nfunction isPackageRoot(dir: string): boolean {\n const hasUi =\n existsSync(path.join(dir, \"ui\", \"dashboard\", \"index.html\")) ||\n existsSync(path.join(dir, \"ui\", \"panels\", \"processes.js\"));\n const packageJson = path.join(dir, \"package.json\");\n\n if (!hasUi || !existsSync(packageJson)) {\n return false;\n }\n\n try {\n const parsed = JSON.parse(readFileSync(packageJson, \"utf8\")) as { name?: string };\n return parsed.name === \"@warlock.js/devtools\";\n } catch {\n return false;\n }\n}\n\n/**\n * Locate this package's `ui/` directory by walking up from the current\n * module's directory. Works from `src/` in development and from the built\n * `esm/`/`cjs/` output, since both sit beside `ui/` and `package.json` at\n * the package root.\n */\nexport function resolveUiRoot(): string {\n if (cachedUiRoot) {\n return cachedUiRoot;\n }\n\n let dir = path.dirname(fileURLToPath(import.meta.url));\n\n while (true) {\n if (isPackageRoot(dir)) {\n cachedUiRoot = path.join(dir, \"ui\");\n return cachedUiRoot;\n }\n\n const parent = path.dirname(dir);\n if (parent === dir) {\n throw new Error(\n \"Could not locate the devtools UI directory: no ancestor of \" +\n \"this module has ui/dashboard/index.html or ui/panels/processes.js beside a package.json named \" +\n \"@warlock.js/devtools.\",\n );\n }\n\n dir = parent;\n }\n}\n","import type { DevtoolsDisposer } from \"../types\";\n\n/**\n * Key `@warlock.js/ai` publishes its agent trace store under on\n * `globalThis`. Reading the store from the registry, not by importing the\n * package, keeps devtools free of an AI dependency and shares one store\n * even when two copies of the package are installed.\n */\nexport const AGENT_TRACES_KEY = Symbol.for(\"@warlock.js/ai.agentTraces\");\n\nexport const AGENT_TRACE_INSTALL_GUIDANCE =\n \"No agent traces yet. Install @warlock.js/ai 5.38 or newer and run an agent in development (agents record traces by default there; `trace: true` turns it on elsewhere), then reload.\";\n\n/** The part of `@warlock.js/ai`'s `AgentTrace` this panel reads; the rest passes through untouched. */\nexport type DevtoolsAgentTrace = {\n runId: string;\n agent: string;\n status: string;\n startedAt: string;\n durationMs?: number;\n model: { name: string; provider: string };\n usage: { input: number; output: number; total: number };\n cost?: number;\n /** The system prompt's hash; `text` is kept only when the agent records prompt text (development). */\n systemPrompt?: { hash: string; text?: string };\n turns: Array<{ toolCalls: Array<{ refusal?: string }> }>;\n};\n\n/** The part of `@warlock.js/ai`'s `AgentTraceStore` devtools uses. */\nexport type DevtoolsAgentTraceStore = {\n get(runId: string): DevtoolsAgentTrace | undefined;\n list(filter?: { limit?: number }): DevtoolsAgentTrace[];\n subscribe(listener: (event: { runId: string; status: string }) => void): () => void;\n};\n\nexport type DevtoolsAgentTraceEvent = { runId: string; status: string; requestId?: string };\n\n/** One row of the run list. */\nexport type DevtoolsAgentRun = {\n runId: string;\n agent: string;\n status: string;\n startedAt: string;\n durationMs?: number;\n model: string;\n turns: number;\n toolCalls: number;\n refusals: number;\n usage: { input: number; output: number };\n cost?: number;\n requestId?: string;\n};\n\n/** Reads agent traces from the shared store; the connector builds one in development only. */\nexport type DevtoolsAgentTraceSource = {\n /** `false` until `@warlock.js/ai` has created its store in this process. */\n available(): boolean;\n list(filter?: { requestId?: string }): DevtoolsAgentRun[];\n get(runId: string): DevtoolsAgentTrace | undefined;\n subscribe(listener: (event: DevtoolsAgentTraceEvent) => void): DevtoolsDisposer;\n dispose: DevtoolsDisposer;\n};\n\n/** One list row for a trace. */\nexport function summarizeAgentTrace(\n trace: DevtoolsAgentTrace,\n requestId?: string,\n): DevtoolsAgentRun {\n let toolCalls = 0;\n let refusals = 0;\n\n for (const turn of trace.turns) {\n toolCalls += turn.toolCalls.length;\n refusals += turn.toolCalls.filter((call) => call.refusal !== undefined).length;\n }\n\n return {\n runId: trace.runId,\n agent: trace.agent,\n status: trace.status,\n startedAt: trace.startedAt,\n durationMs: trace.durationMs,\n model: `${trace.model.provider}/${trace.model.name}`,\n turns: trace.turns.length,\n toolCalls,\n refusals,\n usage: { input: trace.usage.input, output: trace.usage.output },\n cost: trace.cost,\n ...(requestId ? { requestId } : {}),\n };\n}\n\nconst MAX_REQUEST_LINKS = 500;\n\n/**\n * Attach to the shared agent trace store. The store is looked up lazily on\n * every call, so it works whichever of devtools and `@warlock.js/ai` loads\n * first. Runs are linked to the HTTP request that was active when the\n * store first reported them.\n */\nexport async function attachAgentTraceSource(): Promise<DevtoolsAgentTraceSource> {\n const { currentRequestId } = await import(\"../current-request-id\");\n const listeners = new Set<(event: DevtoolsAgentTraceEvent) => void>();\n const requestIds = new Map<string, string>();\n let attachedStore: DevtoolsAgentTraceStore | undefined;\n let detach: (() => void) | undefined;\n\n const findStore = (): DevtoolsAgentTraceStore | undefined => {\n const store = (globalThis as { [AGENT_TRACES_KEY]?: DevtoolsAgentTraceStore })[\n AGENT_TRACES_KEY\n ];\n\n return store && typeof store.list === \"function\" ? store : undefined;\n };\n\n const ensureAttached = (): DevtoolsAgentTraceStore | undefined => {\n const store = findStore();\n\n if (store && store !== attachedStore) {\n detach?.();\n attachedStore = store;\n detach = store.subscribe((event) => {\n // Read the request id before anything asynchronous: the store\n // publishes synchronously from inside the agent run.\n let requestId = requestIds.get(event.runId);\n\n if (!requestId) {\n requestId = currentRequestId();\n\n if (requestId) {\n requestIds.set(event.runId, requestId);\n\n if (requestIds.size > MAX_REQUEST_LINKS) {\n const oldest = requestIds.keys().next();\n\n if (!oldest.done) requestIds.delete(oldest.value);\n }\n }\n }\n\n for (const listener of listeners) {\n try {\n listener({ ...event, ...(requestId ? { requestId } : {}) });\n } catch {\n /* isolate clients */\n }\n }\n });\n }\n\n return store;\n };\n\n ensureAttached();\n\n return {\n available: () => ensureAttached() !== undefined,\n\n list(filter) {\n const store = ensureAttached();\n\n if (!store) return [];\n\n return store\n .list()\n .map((trace) => summarizeAgentTrace(trace, requestIds.get(trace.runId)))\n .filter((run) => filter?.requestId === undefined || run.requestId === filter.requestId);\n },\n\n get: (runId) => ensureAttached()?.get(runId),\n\n subscribe(listener) {\n ensureAttached();\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n };\n },\n\n dispose() {\n detach?.();\n detach = undefined;\n attachedStore = undefined;\n listeners.clear();\n requestIds.clear();\n },\n };\n}\n","import type { Trace, TraceSpan } from \"@warlock.js/ai-panoptic\";\nimport type {\n DevtoolsAiFailedRun,\n DevtoolsAiRunGroup,\n DevtoolsAiRunRow,\n DevtoolsAiRunsView,\n} from \"../../production/contracts\";\nimport { DevtoolsApiError } from \"../../production/errors\";\nimport { classifyAiError } from \"../rollup/categories\";\nimport {\n aiRollupNamesOf,\n isAiModelSpan,\n spanModelOf,\n traceToRollupDeltas,\n} from \"../rollup/extract\";\nimport type { DevtoolsAiTotalCost } from \"../types\";\n\nconst DEFAULT_LIMIT = 200;\nconst MAX_LIMIT = 1000;\nconst GROUP_TRACE_IDS = 50;\nconst MESSAGE_LIMIT = 300;\nconst STATUSES = new Set([\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"incomplete\",\n \"max-iterations\",\n \"awaiting-input\",\n \"awaiting-approval\",\n]);\nconst TYPES = new Set([\n \"tool\",\n \"callback\",\n \"agent\",\n \"workflow\",\n \"supervisor\",\n \"team\",\n \"orchestrator\",\n \"batch\",\n \"planner\",\n \"image\",\n \"speech\",\n \"transcription\",\n \"video\",\n \"realtime\",\n]);\n\n/** The Panoptic helpers the Runs list uses, taken from the lazily loaded module (never a static import). */\nexport type DevtoolsAiRunHelpers = Pick<\n typeof import(\"@warlock.js/ai-panoptic\"),\n | \"filterTraces\"\n | \"groupBySession\"\n | \"groupByPrompt\"\n | \"groupByType\"\n | \"percentile\"\n | \"tracePromptKey\"\n>;\n\n/** `GET api/ai/runs` query string. */\nexport type DevtoolsAiRunsQuery = {\n /** Text in the run name, trace id, session id or model. */\n q?: string;\n /** Comma-separated root statuses. */\n status?: string;\n /** Comma-separated root span types. */\n type?: string;\n session?: string;\n /** Exact HTTP request id the run belongs to. */\n requestId?: string;\n /** `promptName@promptVersion`. */\n prompt?: string;\n groupBy?: \"session\" | \"prompt\" | \"type\";\n /** 1–1000, default 200. */\n limit?: string;\n};\n\n/** The model identity a span reports, as `provider/model`. */\nfunction modelOf(span: TraceSpan): string | null {\n const { name, provider } = spanModelOf(span);\n\n if (name === undefined) return null;\n\n return provider !== undefined ? `${provider}/${name}` : name;\n}\n\n/** A span's own priced cost, else the sum of its children (a wrapper root carries tokens but no cost). */\nfunction spanCost(span: TraceSpan, totalCost: DevtoolsAiTotalCost): number | undefined {\n const own = totalCost(span.usage);\n\n if (own !== undefined && own > 0) return own;\n\n let sum: number | undefined;\n\n for (const child of span.children) {\n const cost = spanCost(child, totalCost);\n\n if (cost !== undefined) sum = (sum ?? 0) + cost;\n }\n\n return sum;\n}\n\n/** One Runs row for a content-free trace. */\nexport function toAiRunRow(\n trace: Trace,\n options: { totalCost: DevtoolsAiTotalCost; helpers: DevtoolsAiRunHelpers },\n): DevtoolsAiRunRow {\n const models = new Set<string>();\n let toolCalls = 0;\n let retries = 0;\n let incomplete = false;\n const visit = (span: TraceSpan): void => {\n const model = modelOf(span);\n\n if (model !== null) models.add(model);\n\n if (span.type === \"tool\") toolCalls += 1;\n\n const spanRetries = span.attributes?.retries;\n\n if (typeof spanRetries === \"number\") retries += spanRetries;\n\n incomplete ||=\n span.status === \"incomplete\" ||\n span.error?.type === \"AgentIncompleteError\" ||\n span.error?.type === \"AGENT_INCOMPLETE\";\n span.children.forEach(visit);\n };\n\n visit(trace.root);\n\n const { usage } = trace;\n\n return {\n traceId: trace.traceId,\n requestId: trace.requestId ?? null,\n sessionId: trace.sessionId ?? null,\n name: trace.root.name,\n type: trace.root.type,\n status: trace.root.status,\n startedAt: trace.startedAt,\n duration: trace.duration,\n usage: {\n input: usage.input,\n output: usage.output,\n total: usage.total,\n cachedTokens: usage.cachedTokens ?? null,\n cacheWriteTokens: usage.cacheWriteTokens ?? null,\n inputIncludesCache: usage.inputIncludesCache ?? null,\n },\n cost: spanCost(trace.root, options.totalCost) ?? null,\n models: [...models],\n promptKey: options.helpers.tracePromptKey(trace) ?? null,\n toolCalls,\n retries,\n incomplete,\n };\n}\n\nfunction parseList(value: string | undefined, allowed: ReadonlySet<string>): string[] | undefined {\n if (value === undefined || value === \"\") return undefined;\n\n const items = value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n\n if (items.some((item) => !allowed.has(item))) throw new DevtoolsApiError(\"input.invalid\");\n\n return items;\n}\n\nfunction parseLimit(value: string | undefined): number {\n if (value === undefined || value === \"\") return DEFAULT_LIMIT;\n\n const limit = /^\\d{1,5}$/.test(value) ? Number(value) : Number.NaN;\n\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return limit;\n}\n\n/**\n * Filters (Panoptic's `filterTraces` rules), groups (`groupBySession`,\n * `groupByPrompt`, `groupByType`) and summarises the stored traces. A bad\n * `limit`, `groupBy` or status throws `DevtoolsApiError(\"input.invalid\")`.\n */\nexport function listAiRuns(\n traces: readonly Trace[],\n query: DevtoolsAiRunsQuery,\n options: { totalCost: DevtoolsAiTotalCost; capacity: number; helpers: DevtoolsAiRunHelpers },\n): Extract<DevtoolsAiRunsView, { available: true }> {\n const { helpers, totalCost } = options;\n const limit = parseLimit(query.limit);\n const statuses = parseList(query.status, STATUSES);\n const types = parseList(query.type, TYPES);\n const groupBy = query.groupBy;\n\n if (\n groupBy !== undefined &&\n (groupBy as string) !== \"\" &&\n ![\"session\", \"prompt\", \"type\"].includes(groupBy)\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const requestId = query.requestId?.trim();\n const matching = helpers\n .filterTraces(\n requestId ? traces.filter((trace) => trace.requestId === requestId) : [...traces],\n {\n ...(query.q?.trim() ? { text: query.q.trim() } : {}),\n ...(statuses ? { statuses: statuses as never } : {}),\n ...(types ? { types: types as never } : {}),\n ...(query.session ? { sessionId: query.session } : {}),\n ...(query.prompt ? { promptKey: query.prompt } : {}),\n },\n )\n .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || 0);\n const rows = matching.map((trace) => toAiRunRow(trace, { totalCost, helpers }));\n const rowOf = new Map(matching.map((trace, index) => [trace, rows[index]]));\n const durations = matching.map((trace) => trace.duration);\n const summarise = (key: string, members: Trace[]): DevtoolsAiRunGroup => {\n const memberRows = members.map((trace) => rowOf.get(trace));\n\n return {\n key,\n label: key,\n runs: members.length,\n failed: members.filter((trace) => trace.root.status === \"failed\").length,\n estimatedCostUsd: memberRows.reduce((sum, row) => sum + (row?.cost ?? 0), 0),\n p95Ms:\n members.length > 0\n ? helpers.percentile(\n members.map((trace) => trace.duration),\n 95,\n )\n : null,\n traceIds: members.slice(0, GROUP_TRACE_IDS).map((trace) => trace.traceId),\n };\n };\n let groups: DevtoolsAiRunGroup[] | null = null;\n\n if (groupBy === \"session\") {\n groups = helpers\n .groupBySession(matching)\n .map((group) => summarise(group.sessionId, group.traces));\n } else if (groupBy === \"prompt\") {\n groups = helpers\n .groupByPrompt(matching)\n .map((group) => summarise(group.promptKey, group.traces));\n } else if (groupBy === \"type\") {\n groups = helpers.groupByType(matching).map((group) => summarise(group.type, group.traces));\n }\n\n return {\n available: true,\n runs: rows.slice(0, limit),\n groups,\n stats: {\n count: matching.length,\n failed: matching.filter((trace) => trace.root.status === \"failed\").length,\n estimatedCostUsd: rows.reduce((sum, row) => sum + (row.cost ?? 0), 0),\n // A run with any model call that used tokens without pricing, by the same rule as the rollups.\n unpricedRuns: matching.filter((trace) =>\n traceToRollupDeltas(trace, totalCost).some((delta) => delta.unpricedRuns > 0),\n ).length,\n p50Ms: durations.length > 0 ? helpers.percentile(durations, 50) : null,\n p95Ms: durations.length > 0 ? helpers.percentile(durations, 95) : null,\n },\n capacity: options.capacity,\n };\n}\n\nconst FAILED_STATUSES: ReadonlySet<string> = new Set([\"failed\", \"incomplete\", \"max-iterations\"]);\n\n/** What the Errors page scopes recent failures by: its range and filters (names as the rollups count them). */\nexport type DevtoolsAiRecentFailuresFilter = {\n from: number;\n to: number;\n agent?: string;\n provider?: string;\n model?: { provider: string; model: string };\n};\n\n/**\n * The newest failed model spans (the same spans the rollups count as runs)\n * of the stored traces, at most `limit`, newest first (Errors page,\n * development). `model` is `provider/model` as the Models page keys it.\n * With a filter, only failures that ended inside its range and match its\n * agent, provider and model are listed.\n */\nexport function recentAiFailures(\n traces: readonly Trace[],\n limit: number,\n filter?: DevtoolsAiRecentFailuresFilter,\n): DevtoolsAiFailedRun[] {\n const failures: DevtoolsAiFailedRun[] = [];\n\n for (const trace of traces) {\n const visit = (span: TraceSpan): void => {\n if (isAiModelSpan(span) && FAILED_STATUSES.has(span.status)) {\n const parsedEnd = Date.parse(span.endedAt);\n const endedAt = Number.isNaN(parsedEnd) ? Date.parse(trace.endedAt) || 0 : parsedEnd;\n const names = aiRollupNamesOf(span);\n const matches =\n !filter ||\n (endedAt >= filter.from &&\n endedAt < filter.to &&\n (filter.agent === undefined || names.agent === filter.agent) &&\n (filter.provider === undefined || names.provider === filter.provider) &&\n (filter.model === undefined ||\n (names.provider === filter.model.provider && names.model === filter.model.model)));\n\n if (matches) {\n const message = span.error?.message;\n\n failures.push({\n traceId: trace.traceId,\n agent: span.name,\n model: spanModelOf(span).name !== undefined ? `${names.provider}/${names.model}` : null,\n status: span.status,\n category: classifyAiError(span.status, span.error?.type),\n code: span.error?.type ?? null,\n message: typeof message === \"string\" ? message.slice(0, MESSAGE_LIMIT) : null,\n endedAt,\n requestId: trace.requestId ?? null,\n });\n }\n }\n\n span.children.forEach(visit);\n };\n\n visit(trace.root);\n }\n\n return failures.sort((a, b) => b.endedAt - a.endedAt).slice(0, Math.max(0, limit));\n}\n"],"mappings":";;;;;;;;;AAIA,IAAI;;;;;;;AAQJ,SAAS,cAAc,KAAsB;CAC3C,MAAM,YACJA,oBAAWC,kBAAK,KAAK,KAAK,MAAM,aAAa,YAAY,CAAC,SAC1DD,oBAAWC,kBAAK,KAAK,KAAK,MAAM,UAAU,cAAc,CAAC;CAC3D,MAAM,cAAcA,kBAAK,KAAK,KAAK,cAAc;CAEjD,IAAI,CAAC,SAAS,KAACD,oBAAW,WAAW,GACnC,OAAO;CAGT,IAAI;EAEF,OADe,KAAK,UAAME,sBAAa,aAAa,MAAM,CAC9C,CAAC,CAAC,SAAS;CACzB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAgB,gBAAwB;CACtC,IAAI,cACF,OAAO;CAGT,IAAI,MAAMD,kBAAK,YAAQE,qEAA6B,CAAC;CAErD,OAAO,MAAM;EACX,IAAI,cAAc,GAAG,GAAG;GACtB,eAAeF,kBAAK,KAAK,KAAK,IAAI;GAClC,OAAO;EACT;EAEA,MAAM,SAASA,kBAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KACb,MAAM,IAAI,MACR,gLAGF;EAGF,MAAM;CACR;AACF;;;;;;;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BAAY,IAAI,CAAC,CAAC,SAAS,SAAY,GAAG,MAAM,SAAS,GAAG,MAAM,UAAU;MACnF,QAAQ,KAAK;MACb,UAAUK,kCAAgB,KAAK,QAAQ,KAAK,OAAO,IAAI;MACvD,MAAM,KAAK,OAAO,QAAQ;MAC1B,SAAS,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,aAAa,IAAI;MACzE;MACA,WAAW,MAAM,aAAa;KAChC,CAAC;IACH;GACF;GAEA,KAAK,SAAS,QAAQ,KAAK;EAC7B;EAEA,MAAM,MAAM,IAAI;CAClB;CAEA,OAAO,SAAS,MAAM,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,MAAM,GAAG,KAAK,IAAI,GAAG,KAAK,CAAC;AACnF"}
@@ -1,7 +1,7 @@
1
1
  const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
2
- const require_extract = require("./extract-8kaX_cUV.cjs");
3
- const require_process_panel = require("./process-panel-D3D9Y_dc.cjs");
4
- const require_stream_route = require("./stream-route-DFHuIWgg.cjs");
2
+ const require_ai_source = require("./ai-source-CeHZDYG1.cjs");
3
+ const require_process_panel = require("./process-panel-Dev6eg_f.cjs");
4
+ const require_stream_route = require("./stream-route-qEHoPVth.cjs");
5
5
 
6
6
  //#region ../../packages/devtools/src/server/background-routes.ts
7
7
  /** Registers the route that returns work recorded outside any request. */
@@ -130,7 +130,7 @@ function developmentSessionView(deps) {
130
130
  }
131
131
  /** The tabs `GET api/panels` lists: the built-in tabs in `deps.builtInPanels` (default all), then the package panels. */
132
132
  function panelInfos(deps, panels) {
133
- return require_extract.listPanelInfos(panels, deps.builtInPanels);
133
+ return require_ai_source.listPanelInfos(panels, deps.builtInPanels);
134
134
  }
135
135
  /**
136
136
  * Registers `GET /api/auth/session` (the development view: signed in as an
@@ -159,7 +159,7 @@ function registerSessionRoutes(server, deps, panels) {
159
159
  * Throws before mounting anything when a panel is invalid or reuses an id.
160
160
  */
161
161
  function mountDevtoolsRoutes(server, deps) {
162
- const panels = require_extract.checkDevtoolsPanels([require_process_panel.processesDevtoolsPanel(deps.processPanel), ...deps.panels ?? []]);
162
+ const panels = require_ai_source.checkDevtoolsPanels([require_process_panel.processesDevtoolsPanel(deps.processPanel), ...deps.panels ?? []]);
163
163
  server.register(async (instance) => {
164
164
  registerDevtoolsGuard(instance, deps);
165
165
  instance.setErrorHandler((error, _request, reply) => {
@@ -185,4 +185,4 @@ function mountDevtoolsRoutes(server, deps) {
185
185
 
186
186
  //#endregion
187
187
  exports.mountDevtoolsRoutes = mountDevtoolsRoutes;
188
- //# sourceMappingURL=server-CC5DpObz.cjs.map
188
+ //# sourceMappingURL=server-Dc0YdP6Y.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-CC5DpObz.cjs","names":["readVersions","listPanelInfos","checkDevtoolsPanels","processesDevtoolsPanel"],"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 { 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 reply.code(error.statusCode ?? 500).send({ error: error.message });\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;CAA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OAAO,UAAU,UAAU;EACnD,MAAM,OAAO,iBAAiB,UAAU;EAExC,OAAO,WAAW,MAAM,MAAM;CAChC,CAAC;AACH;;;;;;;;;;;;ACzBA,SAAgB,oBAAoB,QAAyB,MAAqC;CAChG,MAAM,SAASC,oCAAoB,CACjCC,6CAAuB,KAAK,YAAY,GACxC,GAAI,KAAK,UAAU,CAAC,CACtB,CAAC;CAED,OAAO,SACL,OAAO,aAAa;EAClB,sBAAsB,UAAU,IAAI;EAEpC,SAAS,iBAAiB,OAAqB,UAAU,UAAU;GACjE,MAAM,KAAK,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,EAAE,OAAO,MAAM,QAAQ,CAAC;EACnE,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"}
1
+ {"version":3,"file":"server-Dc0YdP6Y.cjs","names":["readVersions","listPanelInfos","checkDevtoolsPanels","processesDevtoolsPanel"],"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 { 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 reply.code(error.statusCode ?? 500).send({ error: error.message });\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;CAEtC,IAAI,MAAM,WAAW,GAAG,GAAG;EACzB,MAAM,MAAM,MAAM,QAAQ,GAAG;EAE7B,OAAO,QAAQ,KAAK,KAAK,MAAM,MAAM,GAAG,MAAM,CAAC;CACjD;CAEA,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,MAAM,OAAO,UAAU,KAAK,QAAQ,MAAM,MAAM,GAAG,KAAK;CAExD,OAAO,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AAClD;;;;;AAMA,SAAgB,sBACd,UACA,eAAkC,CAAC,GAC1B;CACT,IAAI,CAAC,UAAU,OAAO;CACtB,IAAI,eAAe,IAAI,QAAQ,KAA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CAA0B,UAAU,IAAI;EACxC,IAAI,KAAK,UAAU,4CAAuB,UAAU,IAAI;EACxD,yCAAoB,UAAU,IAAI;CACpC,GACA,EAAE,QAAQ,KAAK,QAAQ,KAAK,CAC9B;AACF"}
@@ -1,10 +1,10 @@
1
1
  const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
2
2
  const require_errors = require("./errors-DNQ-g49I.cjs");
3
- const require_extract = require("./extract-8kaX_cUV.cjs");
4
- const require_runs = require("./runs-DECWPGnq.cjs");
5
- const require_process_panel = require("./process-panel-D3D9Y_dc.cjs");
6
- const require_collector = require("./collector-CJbQbzzK.cjs");
7
- const require_attach = require("./attach-D5aMqUnA.cjs");
3
+ const require_ai_source = require("./ai-source-CeHZDYG1.cjs");
4
+ const require_runs = require("./runs-DXTf_o5P.cjs");
5
+ const require_process_panel = require("./process-panel-Dev6eg_f.cjs");
6
+ const require_collector = require("./collector-BfC4v87v.cjs");
7
+ const require_attach = require("./attach-D9gWc6lU.cjs");
8
8
  const require_current_request_id = require("./current-request-id-Badec-TH.cjs");
9
9
  let node_url = require("node:url");
10
10
  let _warlock_js_logger = require("@warlock.js/logger");
@@ -247,7 +247,7 @@ var DevtoolsLogChannel = class extends _warlock_js_logger.LogChannel {
247
247
  action: data.action,
248
248
  message: messageText(data.message),
249
249
  at: Date.now(),
250
- context: require_extract.toSafeValue(data.context)
250
+ context: require_ai_source.toSafeValue(data.context)
251
251
  };
252
252
  this.collector.addLog(require_current_request_id.currentRequestId(), entry);
253
253
  }
@@ -370,7 +370,7 @@ async function attachQuerySource(collector) {
370
370
  connection: event.connection,
371
371
  driver: event.driver,
372
372
  sql: event.sql,
373
- bindings: require_extract.toSafeValue(redactBindings(event.bindings)),
373
+ bindings: require_ai_source.toSafeValue(redactBindings(event.bindings)),
374
374
  collection: event.collection,
375
375
  command: event.command,
376
376
  pipeline: event.pipeline,
@@ -413,7 +413,7 @@ async function attachTracingSource(collector, options) {
413
413
  name: phase.name,
414
414
  durationMs: phase.durationMs,
415
415
  startedAt: phase.startedAt ?? performance.timeOrigin + performance.now() - phase.durationMs,
416
- attrs: phase.attrs === void 0 ? void 0 : require_extract.toSafeValue(phase.attrs)
416
+ attrs: phase.attrs === void 0 ? void 0 : require_ai_source.toSafeValue(phase.attrs)
417
417
  });
418
418
  },
419
419
  onRequestEnd(ctx, result) {
@@ -436,6 +436,8 @@ async function attachTracingSource(collector, options) {
436
436
  * that depends on it, so it simply goes last.
437
437
  */
438
438
  const DEVTOOLS_CONNECTOR_PRIORITY = 12;
439
+ /** The slot core reads to turn query events on; see `resolveDatabaseConnectionConfig`. */
440
+ const DEVTOOLS_PRODUCTION_REQUESTED = Symbol.for("@warlock.js/devtools.productionRequested");
439
441
  /**
440
442
  * The app's `src/config/devtools.ts`, or `{}` when there is none (or the
441
443
  * config store cannot be read, which must never stop the dev server).
@@ -471,6 +473,7 @@ function readConfiguredOptions(readConfig) {
471
473
  * import of this package); options passed here win over it.
472
474
  */
473
475
  function devtoolsConnector(options = {}) {
476
+ if (options.production?.enabled === true) globalThis[DEVTOOLS_PRODUCTION_REQUESTED] = true;
474
477
  let active = false;
475
478
  const disposers = [];
476
479
  const connector = {
@@ -501,7 +504,7 @@ function devtoolsConnector(options = {}) {
501
504
  await attachSource(log, "cache", () => attachCacheSource(collector));
502
505
  await attachSource(log, "mail", () => attachMailSource(collector));
503
506
  await attachSource(log, "log", () => attachLogSource(collector));
504
- const ai = await require_extract.attachAiSource(resolved.maxRequests);
507
+ const ai = await require_ai_source.attachAiSource(resolved.maxRequests);
505
508
  disposers.push(ai.dispose);
506
509
  const agentTraces = await require_runs.attachAgentTraceSource();
507
510
  disposers.push(agentTraces.dispose);
@@ -510,13 +513,13 @@ function devtoolsConnector(options = {}) {
510
513
  agentTraces,
511
514
  warn: (message) => log.warn("devtools", "evaluate", message)
512
515
  });
513
- const { mountDevtoolsRoutes } = await Promise.resolve().then(() => require("./server-CC5DpObz.cjs"));
516
+ const { mountDevtoolsRoutes } = await Promise.resolve().then(() => require("./server-Dc0YdP6Y.cjs"));
514
517
  const postmanBuilder = await findPostmanBuilder();
515
518
  const requestLog = await findRequestLogSource();
516
519
  const processPanel = await require_process_panel.loadProcessPanel();
517
520
  const builtIn = require_process_panel.processesDevtoolsPanel(processPanel);
518
521
  const panelErrors = createPanelErrorSource();
519
- const panels = await require_extract.loadDevtoolsPanels(resolved.panels ?? [], {
522
+ const panels = await require_ai_source.loadDevtoolsPanels(resolved.panels ?? [], {
520
523
  root: "rootPath" in core ? core.rootPath() : process.cwd(),
521
524
  warn: (message) => log.warn("devtools", "panel", message),
522
525
  taken: /* @__PURE__ */ new Map([[builtIn.id, builtIn.title]]),
@@ -594,8 +597,8 @@ function devtoolsConnector(options = {}) {
594
597
  async function wireDevelopmentInsights(collector, resolved, log, disposers) {
595
598
  const stops = [];
596
599
  try {
597
- const capture = await Promise.resolve().then(() => require("./capture-CBgONYhk.cjs"));
598
- const insights = await Promise.resolve().then(() => require("./insights-CFof59kF.cjs"));
600
+ const capture = await Promise.resolve().then(() => require("./capture-D2k0GnBN.cjs"));
601
+ const insights = await Promise.resolve().then(() => require("./insights-COA3u37q.cjs"));
599
602
  const instance = insights.createInstanceInfo();
600
603
  const queries = capture.createQueryStats({
601
604
  maxShapes: require_attach.DEVTOOLS_PRODUCTION_DEFAULTS.maxShapes,
@@ -656,7 +659,7 @@ async function wireDevelopmentInsights(collector, resolved, log, disposers) {
656
659
  */
657
660
  async function wireDevelopmentAiReports(ai, resolved, core, log, disposers) {
658
661
  const none = (reason) => ({
659
- ...require_extract.toAiUnavailableView(require_extract.describeAiUnavailable(reason)),
662
+ ...require_ai_source.toAiUnavailableView(require_ai_source.describeAiUnavailable(reason)),
660
663
  async dispose() {}
661
664
  });
662
665
  try {
@@ -685,12 +688,12 @@ async function wireDevelopmentAiReports(ai, resolved, core, log, disposers) {
685
688
  * `DevtoolsProductionConfigError`) when the configuration is incomplete.
686
689
  */
687
690
  async function bootProduction(core, log, resolved) {
688
- const { bootProductionDevtools } = await Promise.resolve().then(() => require("./boot-Dg5YZGGR.cjs"));
691
+ const { bootProductionDevtools } = await Promise.resolve().then(() => require("./boot-Guumt-du.cjs"));
689
692
  const requestLog = await findRequestLogSource();
690
693
  const processPanel = resolved.production?.panels?.processes === true ? await require_process_panel.loadProcessPanel() : void 0;
691
694
  const builtIn = require_process_panel.processesDevtoolsPanel(processPanel);
692
695
  const panelErrors = createPanelErrorSource();
693
- const packagePanels = await require_extract.loadDevtoolsPanels(resolved.panels ?? [], {
696
+ const packagePanels = await require_ai_source.loadDevtoolsPanels(resolved.panels ?? [], {
694
697
  root: "rootPath" in core ? core.rootPath() : process.cwd(),
695
698
  warn: (message) => log.warn("devtools", "panel", message),
696
699
  taken: /* @__PURE__ */ new Map([[builtIn.id, builtIn.title]]),
@@ -703,7 +706,7 @@ async function bootProduction(core, log, resolved) {
703
706
  options: resolved,
704
707
  env: process.env,
705
708
  server: core.getHttpServer(),
706
- panels: [...require_extract.checkDevtoolsPanels([builtIn]), ...packagePanels],
709
+ panels: [...require_ai_source.checkDevtoolsPanels([builtIn]), ...packagePanels],
707
710
  routes: {
708
711
  ...processPanel ? { processPanel } : {},
709
712
  ...requestLog ? { requestLog } : {},
@@ -845,4 +848,4 @@ Object.defineProperty(exports, "mail_source_exports", {
845
848
  return mail_source_exports;
846
849
  }
847
850
  });
848
- //# sourceMappingURL=src-VyOjEEAo.cjs.map
851
+ //# sourceMappingURL=src-Ca1gNdZj.cjs.map
@@ -0,0 +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,MAA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