@warlock.js/devtools 5.61.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 (46) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/cjs/{extract-8kaX_cUV.cjs → ai-source-CeHZDYG1.cjs} +449 -408
  3. package/cjs/ai-source-CeHZDYG1.cjs.map +1 -0
  4. package/cjs/{attach-D5aMqUnA.cjs → attach-D9gWc6lU.cjs} +19 -19
  5. package/cjs/attach-D9gWc6lU.cjs.map +1 -0
  6. package/cjs/{boot-D0nF-7w3.cjs → boot-Guumt-du.cjs} +10 -8
  7. package/cjs/boot-Guumt-du.cjs.map +1 -0
  8. package/cjs/{http-1nnpAoI7.cjs → http-CPbhLN61.cjs} +5 -5
  9. package/cjs/{http-1nnpAoI7.cjs.map → http-CPbhLN61.cjs.map} +1 -1
  10. package/cjs/index.cjs +1 -1
  11. package/cjs/{process-panel-D3D9Y_dc.cjs → process-panel-Dev6eg_f.cjs} +2 -2
  12. package/cjs/{process-panel-D3D9Y_dc.cjs.map → process-panel-Dev6eg_f.cjs.map} +1 -1
  13. package/cjs/{runs-DECWPGnq.cjs → runs-DXTf_o5P.cjs} +10 -11
  14. package/cjs/runs-DXTf_o5P.cjs.map +1 -0
  15. package/cjs/{server-DLT3uPef.cjs → server-Dc0YdP6Y.cjs} +6 -6
  16. package/cjs/{server-DLT3uPef.cjs.map → server-Dc0YdP6Y.cjs.map} +1 -1
  17. package/cjs/{src-BZiSv8A1.cjs → src-Ca1gNdZj.cjs} +15 -15
  18. package/cjs/{src-BZiSv8A1.cjs.map → src-Ca1gNdZj.cjs.map} +1 -1
  19. package/cjs/{stream-route-B6WAjbPG.cjs → stream-route-qEHoPVth.cjs} +21 -15
  20. package/cjs/stream-route-qEHoPVth.cjs.map +1 -0
  21. package/esm/ai/reports/runs.mjs +5 -6
  22. package/esm/ai/reports/runs.mjs.map +1 -1
  23. package/esm/ai/rollup/extract.mjs +21 -4
  24. package/esm/ai/rollup/extract.mjs.map +1 -1
  25. package/esm/panels.mjs +14 -1
  26. package/esm/panels.mjs.map +1 -1
  27. package/esm/production/boot.mjs +4 -2
  28. package/esm/production/boot.mjs.map +1 -1
  29. package/esm/production/options.d.mts +5 -0
  30. package/esm/production/options.d.mts.map +1 -1
  31. package/esm/production/options.mjs.map +1 -1
  32. package/esm/server/ai-routes.mjs +11 -5
  33. package/esm/server/ai-routes.mjs.map +1 -1
  34. package/esm/sources/ai-source.d.mts.map +1 -1
  35. package/esm/sources/ai-source.mjs +3 -3
  36. package/esm/sources/ai-source.mjs.map +1 -1
  37. package/esm/types.d.mts +5 -2
  38. package/esm/types.d.mts.map +1 -1
  39. package/llms-full.txt +5 -2
  40. package/package.json +8 -8
  41. package/skills/SKILL.md +5 -2
  42. package/cjs/attach-D5aMqUnA.cjs.map +0 -1
  43. package/cjs/boot-D0nF-7w3.cjs.map +0 -1
  44. package/cjs/extract-8kaX_cUV.cjs.map +0 -1
  45. package/cjs/runs-DECWPGnq.cjs.map +0 -1
  46. package/cjs/stream-route-B6WAjbPG.cjs.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { DevtoolsApiError } from "../../production/errors.mjs";
2
2
  import { classifyAiError } from "../rollup/categories.mjs";
3
- import { aiRollupNamesOf, isAiModelSpan, traceToRollupDeltas } from "../rollup/extract.mjs";
3
+ import { aiRollupNamesOf, isAiModelSpan, spanModelOf, traceToRollupDeltas } from "../rollup/extract.mjs";
4
4
 
5
5
  //#region ../../packages/devtools/src/ai/reports/runs.ts
6
6
  const DEFAULT_LIMIT = 200;
@@ -34,10 +34,9 @@ const TYPES = /* @__PURE__ */ new Set([
34
34
  ]);
35
35
  /** The model identity a span reports, as `provider/model`. */
36
36
  function modelOf(span) {
37
- const model = span.attributes?.["agent.model.name"];
38
- const provider = span.attributes?.["agent.model.provider"];
39
- if (typeof model !== "string") return null;
40
- return typeof provider === "string" ? `${provider}/${model}` : model;
37
+ const { name, provider } = spanModelOf(span);
38
+ if (name === void 0) return null;
39
+ return provider !== void 0 ? `${provider}/${name}` : name;
41
40
  }
42
41
  /** A span's own priced cost, else the sum of its children (a wrapper root carries tokens but no cost). */
43
42
  function spanCost(span, totalCost) {
@@ -190,7 +189,7 @@ function recentAiFailures(traces, limit, filter) {
190
189
  failures.push({
191
190
  traceId: trace.traceId,
192
191
  agent: span.name,
193
- model: typeof span.attributes?.["agent.model.name"] === "string" ? `${names.provider}/${names.model}` : null,
192
+ model: spanModelOf(span).name !== void 0 ? `${names.provider}/${names.model}` : null,
194
193
  status: span.status,
195
194
  category: classifyAiError(span.status, span.error?.type),
196
195
  code: span.error?.type ?? null,
@@ -1 +1 @@
1
- {"version":3,"file":"runs.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/reports/runs.ts"],"sourcesContent":["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 { aiRollupNamesOf, isAiModelSpan, traceToRollupDeltas } 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 model = span.attributes?.[\"agent.model.name\"];\n const provider = span.attributes?.[\"agent.model.provider\"];\n\n if (typeof model !== \"string\") return null;\n\n return typeof provider === \"string\" ? `${provider}/${model}` : model;\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:\n typeof span.attributes?.[\"agent.model.name\"] === \"string\"\n ? `${names.provider}/${names.model}`\n : 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":";;;;;AAYA,MAAM,gBAAgB;AACtB,MAAM,YAAY;AAClB,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,2BAAW,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,wBAAQ,IAAI,IAAI;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAgCD,SAAS,QAAQ,MAAgC;CAC/C,MAAM,QAAQ,KAAK,aAAa;CAChC,MAAM,WAAW,KAAK,aAAa;CAEnC,IAAI,OAAO,UAAU,UAAU,OAAO;CAEtC,OAAO,OAAO,aAAa,WAAW,GAAG,SAAS,GAAG,UAAU;AACjE;;AAGA,SAAS,SAAS,MAAiB,WAAoD;CACrF,MAAM,MAAM,UAAU,KAAK,KAAK;CAEhC,IAAI,QAAQ,UAAa,MAAM,GAAG,OAAO;CAEzC,IAAI;CAEJ,KAAK,MAAM,SAAS,KAAK,UAAU;EACjC,MAAM,OAAO,SAAS,OAAO,SAAS;EAEtC,IAAI,SAAS,QAAW,OAAO,OAAO,KAAK;CAC7C;CAEA,OAAO;AACT;;AAGA,SAAgB,WACd,OACA,SACkB;CAClB,MAAM,yBAAS,IAAI,IAAY;CAC/B,IAAI,YAAY;CAChB,IAAI,UAAU;CACd,IAAI,aAAa;CACjB,MAAM,SAAS,SAA0B;EACvC,MAAM,QAAQ,QAAQ,IAAI;EAE1B,IAAI,UAAU,MAAM,OAAO,IAAI,KAAK;EAEpC,IAAI,KAAK,SAAS,QAAQ,aAAa;EAEvC,MAAM,cAAc,KAAK,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["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":";;;;;AAiBA,MAAM,gBAAgB;AACtB,MAAM,YAAY;AAClB,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,2BAAW,IAAI,IAAI;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,wBAAQ,IAAI,IAAI;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAgCD,SAAS,QAAQ,MAAgC;CAC/C,MAAM,EAAE,MAAM,aAAa,YAAY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M,UAAU,KAAK,OAAO;KAE5B,SAAS,KAAK;MACZ,SAAS,MAAM;MACf,OAAO,KAAK;MACZ,OAAO,YAAY,IAAI,CAAC,CAAC,SAAS,SAAY,GAAG,MAAM,SAAS,GAAG,MAAM,UAAU;MACnF,QAAQ,KAAK;MACb,UAAU,gBAAgB,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"}
@@ -33,9 +33,26 @@ function subtract(own, other) {
33
33
  own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);
34
34
  own.reasoning = Math.max(0, own.reasoning - other.reasoning);
35
35
  }
36
+ /**
37
+ * The model a span reports: `agent.model.*` first, then `<span type>.model.*`
38
+ * (image, speech and transcription spans).
39
+ */
40
+ function spanModelOf(span) {
41
+ const attributes = span.attributes;
42
+ const pick = (key) => {
43
+ for (const prefix of ["agent", span.type]) {
44
+ const value = attributes?.[`${prefix}.${key}`];
45
+ if (typeof value === "string" && value !== "") return value;
46
+ }
47
+ };
48
+ return {
49
+ name: pick("model.name"),
50
+ provider: pick("model.provider")
51
+ };
52
+ }
36
53
  /** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */
37
54
  function isAiModelSpan(span) {
38
- return typeof span.attributes?.["agent.model.name"] === "string" || MODEL_SPAN_TYPES.has(span.type);
55
+ return spanModelOf(span).name !== void 0 || MODEL_SPAN_TYPES.has(span.type);
39
56
  }
40
57
  /** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */
41
58
  function nearestModelSpans(span) {
@@ -156,8 +173,8 @@ function traceToRollupDeltas(trace, totalCost) {
156
173
  function aiRollupNamesOf(span) {
157
174
  return {
158
175
  agent: cut(span.name, 200),
159
- model: cut(span.attributes?.["agent.model.name"], 200),
160
- provider: cut(span.attributes?.["agent.model.provider"], 100)
176
+ model: cut(spanModelOf(span).name, 200),
177
+ provider: cut(spanModelOf(span).provider, 100)
161
178
  };
162
179
  }
163
180
  /** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */
@@ -221,5 +238,5 @@ function addRollupCounters(target, source) {
221
238
  }
222
239
 
223
240
  //#endregion
224
- export { addRollupCounters, aiRollupNamesOf, emptyRollupDelta, isAiModelSpan, rollupId, traceToRollupDeltas };
241
+ export { addRollupCounters, aiRollupNamesOf, emptyRollupDelta, isAiModelSpan, rollupId, spanModelOf, traceToRollupDeltas };
225
242
  //# sourceMappingURL=extract.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"extract.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/extract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Trace } from \"@warlock.js/ai-panoptic\";\nimport type { DevtoolsAiRollupDelta, DevtoolsAiTotalCost } from \"../types\";\nimport { classifyAiError, emptyErrorCounts } from \"./categories\";\nimport { addAiLatency, aiLatencyBucket, emptyAiLatency } from \"./histogram\";\n\ntype Span = Trace[\"root\"];\ntype RollupKey = { hour: number; agent: string; model: string; provider: string };\n\nconst HOUR_MS = 3_600_000;\nconst UNKNOWN = \"(unknown)\";\nconst MODEL_SPAN_TYPES: ReadonlySet<string> = new Set([\n \"agent\",\n \"image\",\n \"speech\",\n \"transcription\",\n]);\n\n/** Token counts with `input` normalised to the whole prompt. */\ntype Tokens = {\n input: number;\n output: number;\n cached: number;\n cacheWrite: number;\n reasoning: number;\n};\n\nfunction count(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction normalise(usage: Span[\"usage\"] | undefined): Tokens {\n const cached = count(usage?.cachedTokens);\n const cacheWrite = count(usage?.cacheWriteTokens);\n const input = count(usage?.input);\n\n return {\n input: usage?.inputIncludesCache === false ? input + cached + cacheWrite : input,\n output: count(usage?.output),\n cached,\n cacheWrite,\n reasoning: count(usage?.reasoningTokens),\n };\n}\n\nfunction subtract(own: Tokens, other: Tokens): void {\n own.input = Math.max(0, own.input - other.input);\n own.output = Math.max(0, own.output - other.output);\n own.cached = Math.max(0, own.cached - other.cached);\n own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);\n own.reasoning = Math.max(0, own.reasoning - other.reasoning);\n}\n\n/** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */\nexport function isAiModelSpan(span: Span): boolean {\n return (\n typeof span.attributes?.[\"agent.model.name\"] === \"string\" || MODEL_SPAN_TYPES.has(span.type)\n );\n}\n\n/** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */\nfunction nearestModelSpans(span: Span): Span[] {\n const found: Span[] = [];\n\n for (const child of span.children ?? []) {\n if (isAiModelSpan(child)) found.push(child);\n else found.push(...nearestModelSpans(child));\n }\n\n return found;\n}\n\nfunction cut(value: unknown, max: number): string {\n if (typeof value !== \"string\" || value === \"\") return UNKNOWN;\n\n return value.length > max ? value.slice(0, max) : value;\n}\n\nfunction spanCost(span: Span, totalCost: DevtoolsAiTotalCost): number {\n return count(totalCost(span.usage));\n}\n\n/** Whether a span's usage carries pricing at all (a free model is priced at 0; no pricing is `undefined`). */\nfunction hasPricing(span: Span, totalCost: DevtoolsAiTotalCost): boolean {\n return typeof totalCost(span.usage) === \"number\";\n}\n\nfunction buildDelta(\n key: RollupKey,\n status: string,\n errorType: string | undefined,\n tokens: Tokens,\n cost: number,\n /** The own usage is priced even when `cost` is 0 (a model priced as free). */\n pricedAtZero = false,\n): DevtoolsAiRollupDelta {\n const delta = emptyRollupDelta(key);\n\n delta.runs = 1;\n delta.inputTokens = tokens.input;\n delta.outputTokens = tokens.output;\n delta.cachedTokens = tokens.cached;\n delta.cacheWriteTokens = tokens.cacheWrite;\n delta.reasoningTokens = tokens.reasoning;\n\n if (status === \"completed\") delta.completed = 1;\n else if (status === \"failed\") delta.failed = 1;\n else if (status === \"incomplete\" || status === \"max-iterations\") delta.incomplete = 1;\n else if (status === \"cancelled\") delta.cancelled = 1;\n\n if (status === \"failed\" || status === \"incomplete\" || status === \"max-iterations\") {\n delta.errors[classifyAiError(status, errorType)] = 1;\n }\n\n if (cost > 0 || (pricedAtZero && tokens.input + tokens.output > 0)) {\n delta.costUsd = cost;\n delta.pricedRuns = 1;\n } else if (tokens.input + tokens.output > 0) {\n delta.unpricedRuns = 1;\n delta.unpricedTokens = tokens.input + tokens.output;\n }\n\n return delta;\n}\n\n/**\n * Turns one finished Panoptic trace into rollup deltas, one per\n * model-bearing span (a span with an `agent.model.name` attribute, or of type\n * `agent`, `image`, `speech` or `transcription`), keyed by the hour of the\n * span's `endedAt`.\n *\n * Each span counts its OWN usage and cost: its rolled-up `usage` minus the\n * usage of its nearest model-bearing descendants (an agent used as a tool is\n * counted once, as itself). Root usage left after subtracting every\n * model-bearing span (a custom flow with no agent span) becomes one more delta\n * for the root name with model `(unknown)`, counted as one run.\n *\n * Per span: status maps to completed / failed / incomplete (`incomplete`,\n * `max-iterations`) / cancelled; failed and incomplete runs add one error to\n * `classifyAiError(status, error.type)`; tokens are normalised so `input`\n * includes cache reads and writes; `costUsd` is `totalCost` of the own usage\n * when it is above 0 (or the span's model is priced as free), otherwise a run\n * with tokens counts in `unpricedRuns` and `unpricedTokens`; `agent.fallbackTrips > 0` adds a fallback run;\n * `agent.refusals > 0` or a CONTENT_FILTER error adds a refusal; the span's\n * `duration` goes into the latency histogram.\n *\n * Pure: no clock, no I/O. Names are cut to 200 (provider 100) characters.\n */\nexport function traceToRollupDeltas(\n trace: Trace,\n totalCost: DevtoolsAiTotalCost,\n): DevtoolsAiRollupDelta[] {\n const root = trace.root;\n\n if (!root) return [];\n\n // A span without a readable end falls back to the root's end, then the trace's; no end at all skips the trace.\n const rootEnd = Date.parse(root.endedAt);\n const fallbackEnd = Number.isNaN(rootEnd) ? Date.parse(trace.endedAt) : rootEnd;\n\n if (Number.isNaN(fallbackEnd)) return [];\n\n const hourOf = (span: Span): number => {\n const ended = Date.parse(span.endedAt);\n const at = Number.isNaN(ended) ? fallbackEnd : ended;\n\n return Math.floor(at / HOUR_MS) * HOUR_MS;\n };\n\n const deltas: DevtoolsAiRollupDelta[] = [];\n const topLevel: Span[] = isAiModelSpan(root) ? [root] : nearestModelSpans(root);\n\n const visit = (span: Span): void => {\n const tokens = normalise(span.usage);\n let cost = spanCost(span, totalCost);\n const inner = nearestModelSpans(span);\n\n for (const child of inner) {\n subtract(tokens, normalise(child.usage));\n cost -= spanCost(child, totalCost);\n }\n\n cost = Math.max(0, cost);\n\n // Priced at zero only when the span's own pricing is known: none of the nested model spans carry a cost.\n const pricedAtZero =\n hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));\n\n const attributes = span.attributes ?? {};\n const key: RollupKey = { hour: hourOf(span), ...aiRollupNamesOf(span) };\n const delta = buildDelta(key, span.status, span.error?.type, tokens, cost, pricedAtZero);\n\n if (count(attributes[\"agent.fallbackTrips\"]) > 0) delta.fallbackRuns = 1;\n\n if (count(attributes[\"agent.refusals\"]) > 0 || span.error?.type === \"CONTENT_FILTER\") {\n delta.refusals = 1;\n }\n\n const duration = count(span.duration);\n\n const bucket = aiLatencyBucket(duration);\n\n delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;\n delta.latencyCount = 1;\n delta.latencySumMs = Math.max(0, duration);\n\n deltas.push(delta);\n\n for (const child of inner) visit(child);\n };\n\n // Only the real model-bearing roots start the walk; `visit` handles nesting.\n for (const span of topLevel) visit(span);\n\n const leftover = normalise(root.usage);\n let leftoverCost = spanCost(root, totalCost);\n\n for (const span of topLevel) {\n subtract(leftover, normalise(span.usage));\n leftoverCost -= spanCost(span, totalCost);\n }\n\n if (leftover.input + leftover.output > 0) {\n deltas.push(\n buildDelta(\n { hour: hourOf(root), agent: cut(root.name, 200), model: UNKNOWN, provider: UNKNOWN },\n root.status,\n root.error?.type,\n leftover,\n Math.max(0, leftoverCost),\n ),\n );\n }\n\n return deltas;\n}\n\n/** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */\nexport function aiRollupNamesOf(span: Span): { agent: string; model: string; provider: string } {\n return {\n agent: cut(span.name, 200),\n model: cut(span.attributes?.[\"agent.model.name\"], 200),\n provider: cut(span.attributes?.[\"agent.model.provider\"], 100),\n };\n}\n\n/** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */\nexport function rollupId(key: RollupKey): string {\n return createHash(\"sha256\")\n .update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`)\n .digest(\"hex\")\n .slice(0, 40);\n}\n\n/** A delta with every counter at zero for `key`. */\nexport function emptyRollupDelta(key: RollupKey): DevtoolsAiRollupDelta {\n return {\n hour: key.hour,\n agent: key.agent,\n model: key.model,\n provider: key.provider,\n runs: 0,\n completed: 0,\n failed: 0,\n incomplete: 0,\n cancelled: 0,\n inputTokens: 0,\n outputTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n reasoningTokens: 0,\n costUsd: 0,\n pricedRuns: 0,\n unpricedRuns: 0,\n unpricedTokens: 0,\n fallbackRuns: 0,\n refusals: 0,\n errors: emptyErrorCounts(),\n latency: emptyAiLatency(),\n latencyCount: 0,\n latencySumMs: 0,\n };\n}\n\nconst NUMERIC_COUNTERS = [\n \"runs\",\n \"completed\",\n \"failed\",\n \"incomplete\",\n \"cancelled\",\n \"inputTokens\",\n \"outputTokens\",\n \"cachedTokens\",\n \"cacheWriteTokens\",\n \"reasoningTokens\",\n \"costUsd\",\n \"pricedRuns\",\n \"unpricedRuns\",\n \"unpricedTokens\",\n \"fallbackRuns\",\n \"refusals\",\n \"latencyCount\",\n \"latencySumMs\",\n] as const;\n\n/** Adds the counters of `source` into `target` in place (keys must match). */\nexport function addRollupCounters(\n target: DevtoolsAiRollupDelta,\n source: DevtoolsAiRollupDelta,\n): void {\n for (const field of NUMERIC_COUNTERS) target[field] += source[field];\n\n for (const category of Object.keys(target.errors) as (keyof typeof target.errors)[]) {\n target.errors[category] += source.errors[category] ?? 0;\n }\n\n addAiLatency(target.latency, source.latency);\n}\n"],"mappings":";;;;;AASA,MAAM,UAAU;AAChB,MAAM,UAAU;AAChB,MAAM,mCAAwC,IAAI,IAAI;CACpD;CACA;CACA;CACA;AACF,CAAC;AAWD,SAAS,MAAM,OAAwB;CACrC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,UAAU,OAA0C;CAC3D,MAAM,SAAS,MAAM,OAAO,YAAY;CACxC,MAAM,aAAa,MAAM,OAAO,gBAAgB;CAChD,MAAM,QAAQ,MAAM,OAAO,KAAK;CAEhC,OAAO;EACL,OAAO,OAAO,uBAAuB,QAAQ,QAAQ,SAAS,aAAa;EAC3E,QAAQ,MAAM,OAAO,MAAM;EAC3B;EACA;EACA,WAAW,MAAM,OAAO,eAAe;CACzC;AACF;AAEA,SAAS,SAAS,KAAa,OAAqB;CAClD,IAAI,QAAQ,KAAK,IAAI,GAAG,IAAI,QAAQ,MAAM,KAAK;CAC/C,IAAI,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,MAAM,MAAM;CAClD,IAAI,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,MAAM,MAAM;CAClD,IAAI,aAAa,KAAK,IAAI,GAAG,IAAI,aAAa,MAAM,UAAU;CAC9D,IAAI,YAAY,KAAK,IAAI,GAAG,IAAI,YAAY,MAAM,SAAS;AAC7D;;AAGA,SAAgB,cAAc,MAAqB;CACjD,OACE,OAAO,KAAK,aAAa,wBAAwB,YAAY,iBAAiB,IAAI,KAAK,IAAI;AAE/F;;AAGA,SAAS,kBAAkB,MAAoB;CAC7C,MAAM,QAAgB,CAAC;CAEvB,KA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AAc;EACd,cAAc;EACd,kBAAkB;EAClB,iBAAiB;EACjB,SAAS;EACT,YAAY;EACZ,cAAc;EACd,gBAAgB;EAChB,cAAc;EACd,UAAU;EACV,QAAQ,iBAAiB;EACzB,SAAS,eAAe;EACxB,cAAc;EACd,cAAc;CAChB;AACF;AAEA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,kBACd,QACA,QACM;CACN,KAAK,MAAM,SAAS,kBAAkB,OAAO,UAAU,OAAO;CAE9D,KAAK,MAAM,YAAY,OAAO,KAAK,OAAO,MAAM,GAC9C,OAAO,OAAO,aAAa,OAAO,OAAO,aAAa;CAGxD,aAAa,OAAO,SAAS,OAAO,OAAO;AAC7C"}
1
+ {"version":3,"file":"extract.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/extract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Trace } from \"@warlock.js/ai-panoptic\";\nimport type { DevtoolsAiRollupDelta, DevtoolsAiTotalCost } from \"../types\";\nimport { classifyAiError, emptyErrorCounts } from \"./categories\";\nimport { addAiLatency, aiLatencyBucket, emptyAiLatency } from \"./histogram\";\n\ntype Span = Trace[\"root\"];\ntype RollupKey = { hour: number; agent: string; model: string; provider: string };\n\nconst HOUR_MS = 3_600_000;\nconst UNKNOWN = \"(unknown)\";\nconst MODEL_SPAN_TYPES: ReadonlySet<string> = new Set([\n \"agent\",\n \"image\",\n \"speech\",\n \"transcription\",\n]);\n\n/** Token counts with `input` normalised to the whole prompt. */\ntype Tokens = {\n input: number;\n output: number;\n cached: number;\n cacheWrite: number;\n reasoning: number;\n};\n\nfunction count(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction normalise(usage: Span[\"usage\"] | undefined): Tokens {\n const cached = count(usage?.cachedTokens);\n const cacheWrite = count(usage?.cacheWriteTokens);\n const input = count(usage?.input);\n\n return {\n input: usage?.inputIncludesCache === false ? input + cached + cacheWrite : input,\n output: count(usage?.output),\n cached,\n cacheWrite,\n reasoning: count(usage?.reasoningTokens),\n };\n}\n\nfunction subtract(own: Tokens, other: Tokens): void {\n own.input = Math.max(0, own.input - other.input);\n own.output = Math.max(0, own.output - other.output);\n own.cached = Math.max(0, own.cached - other.cached);\n own.cacheWrite = Math.max(0, own.cacheWrite - other.cacheWrite);\n own.reasoning = Math.max(0, own.reasoning - other.reasoning);\n}\n\n/**\n * The model a span reports: `agent.model.*` first, then `<span type>.model.*`\n * (image, speech and transcription spans).\n */\nexport function spanModelOf(span: Span): { name?: string; provider?: string } {\n const attributes = span.attributes;\n const pick = (key: string): string | undefined => {\n for (const prefix of [\"agent\", span.type]) {\n const value = attributes?.[`${prefix}.${key}`];\n\n if (typeof value === \"string\" && value !== \"\") return value;\n }\n\n return undefined;\n };\n\n return { name: pick(\"model.name\"), provider: pick(\"model.provider\") };\n}\n\n/** Whether a span is one run in the rollups: it reports a model, or is an agent/image/speech/transcription span. */\nexport function isAiModelSpan(span: Span): boolean {\n return spanModelOf(span).name !== undefined || MODEL_SPAN_TYPES.has(span.type);\n}\n\n/** The nearest model-bearing descendants of `span` (their own subtrees are not entered). */\nfunction nearestModelSpans(span: Span): Span[] {\n const found: Span[] = [];\n\n for (const child of span.children ?? []) {\n if (isAiModelSpan(child)) found.push(child);\n else found.push(...nearestModelSpans(child));\n }\n\n return found;\n}\n\nfunction cut(value: unknown, max: number): string {\n if (typeof value !== \"string\" || value === \"\") return UNKNOWN;\n\n return value.length > max ? value.slice(0, max) : value;\n}\n\nfunction spanCost(span: Span, totalCost: DevtoolsAiTotalCost): number {\n return count(totalCost(span.usage));\n}\n\n/** Whether a span's usage carries pricing at all (a free model is priced at 0; no pricing is `undefined`). */\nfunction hasPricing(span: Span, totalCost: DevtoolsAiTotalCost): boolean {\n return typeof totalCost(span.usage) === \"number\";\n}\n\nfunction buildDelta(\n key: RollupKey,\n status: string,\n errorType: string | undefined,\n tokens: Tokens,\n cost: number,\n /** The own usage is priced even when `cost` is 0 (a model priced as free). */\n pricedAtZero = false,\n): DevtoolsAiRollupDelta {\n const delta = emptyRollupDelta(key);\n\n delta.runs = 1;\n delta.inputTokens = tokens.input;\n delta.outputTokens = tokens.output;\n delta.cachedTokens = tokens.cached;\n delta.cacheWriteTokens = tokens.cacheWrite;\n delta.reasoningTokens = tokens.reasoning;\n\n if (status === \"completed\") delta.completed = 1;\n else if (status === \"failed\") delta.failed = 1;\n else if (status === \"incomplete\" || status === \"max-iterations\") delta.incomplete = 1;\n else if (status === \"cancelled\") delta.cancelled = 1;\n\n if (status === \"failed\" || status === \"incomplete\" || status === \"max-iterations\") {\n delta.errors[classifyAiError(status, errorType)] = 1;\n }\n\n if (cost > 0 || (pricedAtZero && tokens.input + tokens.output > 0)) {\n delta.costUsd = cost;\n delta.pricedRuns = 1;\n } else if (tokens.input + tokens.output > 0) {\n delta.unpricedRuns = 1;\n delta.unpricedTokens = tokens.input + tokens.output;\n }\n\n return delta;\n}\n\n/**\n * Turns one finished Panoptic trace into rollup deltas, one per\n * model-bearing span (a span with an `agent.model.name` attribute, or of type\n * `agent`, `image`, `speech` or `transcription`), keyed by the hour of the\n * span's `endedAt`.\n *\n * Each span counts its OWN usage and cost: its rolled-up `usage` minus the\n * usage of its nearest model-bearing descendants (an agent used as a tool is\n * counted once, as itself). Root usage left after subtracting every\n * model-bearing span (a custom flow with no agent span) becomes one more delta\n * for the root name with model `(unknown)`, counted as one run.\n *\n * Per span: status maps to completed / failed / incomplete (`incomplete`,\n * `max-iterations`) / cancelled; failed and incomplete runs add one error to\n * `classifyAiError(status, error.type)`; tokens are normalised so `input`\n * includes cache reads and writes; `costUsd` is `totalCost` of the own usage\n * when it is above 0 (or the span's model is priced as free), otherwise a run\n * with tokens counts in `unpricedRuns` and `unpricedTokens`; `agent.fallbackTrips > 0` adds a fallback run;\n * `agent.refusals > 0` or a CONTENT_FILTER error adds a refusal; the span's\n * `duration` goes into the latency histogram.\n *\n * Pure: no clock, no I/O. Names are cut to 200 (provider 100) characters.\n */\nexport function traceToRollupDeltas(\n trace: Trace,\n totalCost: DevtoolsAiTotalCost,\n): DevtoolsAiRollupDelta[] {\n const root = trace.root;\n\n if (!root) return [];\n\n // A span without a readable end falls back to the root's end, then the trace's; no end at all skips the trace.\n const rootEnd = Date.parse(root.endedAt);\n const fallbackEnd = Number.isNaN(rootEnd) ? Date.parse(trace.endedAt) : rootEnd;\n\n if (Number.isNaN(fallbackEnd)) return [];\n\n const hourOf = (span: Span): number => {\n const ended = Date.parse(span.endedAt);\n const at = Number.isNaN(ended) ? fallbackEnd : ended;\n\n return Math.floor(at / HOUR_MS) * HOUR_MS;\n };\n\n const deltas: DevtoolsAiRollupDelta[] = [];\n const topLevel: Span[] = isAiModelSpan(root) ? [root] : nearestModelSpans(root);\n\n const visit = (span: Span): void => {\n const tokens = normalise(span.usage);\n let cost = spanCost(span, totalCost);\n const inner = nearestModelSpans(span);\n\n for (const child of inner) {\n subtract(tokens, normalise(child.usage));\n cost -= spanCost(child, totalCost);\n }\n\n cost = Math.max(0, cost);\n\n // Priced at zero only when the span's own pricing is known: none of the nested model spans carry a cost.\n const pricedAtZero =\n hasPricing(span, totalCost) && inner.every((child) => !hasPricing(child, totalCost));\n\n const attributes = span.attributes ?? {};\n const key: RollupKey = { hour: hourOf(span), ...aiRollupNamesOf(span) };\n const delta = buildDelta(key, span.status, span.error?.type, tokens, cost, pricedAtZero);\n\n if (count(attributes[\"agent.fallbackTrips\"]) > 0) delta.fallbackRuns = 1;\n\n if (count(attributes[\"agent.refusals\"]) > 0 || span.error?.type === \"CONTENT_FILTER\") {\n delta.refusals = 1;\n }\n\n const duration = count(span.duration);\n\n const bucket = aiLatencyBucket(duration);\n\n delta.latency[bucket] = (delta.latency[bucket] ?? 0) + 1;\n delta.latencyCount = 1;\n delta.latencySumMs = Math.max(0, duration);\n\n deltas.push(delta);\n\n for (const child of inner) visit(child);\n };\n\n // Only the real model-bearing roots start the walk; `visit` handles nesting.\n for (const span of topLevel) visit(span);\n\n const leftover = normalise(root.usage);\n let leftoverCost = spanCost(root, totalCost);\n\n for (const span of topLevel) {\n subtract(leftover, normalise(span.usage));\n leftoverCost -= spanCost(span, totalCost);\n }\n\n if (leftover.input + leftover.output > 0) {\n deltas.push(\n buildDelta(\n { hour: hourOf(root), agent: cut(root.name, 200), model: UNKNOWN, provider: UNKNOWN },\n root.status,\n root.error?.type,\n leftover,\n Math.max(0, leftoverCost),\n ),\n );\n }\n\n return deltas;\n}\n\n/** The agent, model and provider a span is counted under (names cut, `(unknown)` when missing). */\nexport function aiRollupNamesOf(span: Span): { agent: string; model: string; provider: string } {\n return {\n agent: cut(span.name, 200),\n model: cut(spanModelOf(span).name, 200),\n provider: cut(spanModelOf(span).provider, 100),\n };\n}\n\n/** `rollupId(key)`: first 40 hex characters of SHA-256 over `hour|agent|model|provider`. */\nexport function rollupId(key: RollupKey): string {\n return createHash(\"sha256\")\n .update(`${key.hour}|${key.agent}|${key.model}|${key.provider}`)\n .digest(\"hex\")\n .slice(0, 40);\n}\n\n/** A delta with every counter at zero for `key`. */\nexport function emptyRollupDelta(key: RollupKey): DevtoolsAiRollupDelta {\n return {\n hour: key.hour,\n agent: key.agent,\n model: key.model,\n provider: key.provider,\n runs: 0,\n completed: 0,\n failed: 0,\n incomplete: 0,\n cancelled: 0,\n inputTokens: 0,\n outputTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n reasoningTokens: 0,\n costUsd: 0,\n pricedRuns: 0,\n unpricedRuns: 0,\n unpricedTokens: 0,\n fallbackRuns: 0,\n refusals: 0,\n errors: emptyErrorCounts(),\n latency: emptyAiLatency(),\n latencyCount: 0,\n latencySumMs: 0,\n };\n}\n\nconst NUMERIC_COUNTERS = [\n \"runs\",\n \"completed\",\n \"failed\",\n \"incomplete\",\n \"cancelled\",\n \"inputTokens\",\n \"outputTokens\",\n \"cachedTokens\",\n \"cacheWriteTokens\",\n \"reasoningTokens\",\n \"costUsd\",\n \"pricedRuns\",\n \"unpricedRuns\",\n \"unpricedTokens\",\n \"fallbackRuns\",\n \"refusals\",\n \"latencyCount\",\n \"latencySumMs\",\n] as const;\n\n/** Adds the counters of `source` into `target` in place (keys must match). */\nexport function addRollupCounters(\n target: DevtoolsAiRollupDelta,\n source: DevtoolsAiRollupDelta,\n): void {\n for (const field of NUMERIC_COUNTERS) target[field] += source[field];\n\n for (const category of Object.keys(target.errors) as (keyof typeof target.errors)[]) {\n target.errors[category] += source.errors[category] ?? 0;\n }\n\n addAiLatency(target.latency, source.latency);\n}\n"],"mappings":";;;;;AASA,MAAM,UAAU;AAChB,MAAM,UAAU;AAChB,MAAM,mCAAwC,IAAI,IAAI;CACpD;CACA;CACA;CACA;AACF,CAAC;AAWD,SAAS,MAAM,OAAwB;CACrC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,UAAU,OAA0C;CAC3D,MAAM,SAAS,MAAM,OAAO,YAAY;CACxC,MAAM,aAAa,MAAM,OAAO,gBAAgB;CAChD,MAAM,QAAQ,MAAM,OAAO,KAAK;CAEhC,OAAO;EACL,OAAO,OAAO,uBAAuB,QAAQ,QAAQ,SAAS,aAAa;EAC3E,QAAQ,MAAM,OAAO,MAAM;EAC3B;EACA;EACA,WAAW,MAAM,OAAO,eAAe;CACzC;AACF;AAEA,SAAS,SAAS,KAAa,OAAqB;CAClD,IAAI,QAAQ,KAAK,IAAI,GAAG,IAAI,QAAQ,MAAM,KAAK;CAC/C,IAAI,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,MAAM,MAAM;CAClD,IAAI,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,MAAM,MAAM;CAClD,IAAI,aAAa,KAAK,IAAI,GAAG,IAAI,aAAa,MAAM,UAAU;CAC9D,IAAI,YAAY,KAAK,IAAI,GAAG,IAAI,YAAY,MAAM,SAAS;AAC7D;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;EACzB,OAAO,IAAI,YAAY,IAAI,CAAC,CAAC,MAAM,GAAG;EACtC,UAAU,IAAI,YAAY,IAAI,CAAC,CAAC,UAAU,GAAG;CAC/C;AACF;;AAGA,SAAgB,SAAS,KAAwB;CAC/C,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,GAAG,IAAI,KAAK,GAAG,IAAI,MAAM,GAAG,IAAI,MAAM,GAAG,IAAI,UAAU,CAAC,CAC/D,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;AAChB;;AAGA,SAAgB,iBAAiB,KAAuC;CACtE,OAAO;EACL,MAAM,IAAI;EACV,OAAO,IAAI;EACX,OAAO,IAAI;EACX,UAAU,IAAI;EACd,MAAM;EACN,WAAW;EACX,QAAQ;EACR,YAAY;EACZ,WAAW;EACX,aAAa;EACb,cAAc;EACd,cAAc;EACd,kBAAkB;EAClB,iBAAiB;EACjB,SAAS;EACT,YAAY;EACZ,cAAc;EACd,gBAAgB;EAChB,cAAc;EACd,UAAU;EACV,QAAQ,iBAAiB;EACzB,SAAS,eAAe;EACxB,cAAc;EACd,cAAc;CAChB;AACF;AAEA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,kBACd,QACA,QACM;CACN,KAAK,MAAM,SAAS,kBAAkB,OAAO,UAAU,OAAO;CAE9D,KAAK,MAAM,YAAY,OAAO,KAAK,OAAO,MAAM,GAC9C,OAAO,OAAO,aAAa,OAAO,OAAO,aAAa;CAGxD,aAAa,OAAO,SAAS,OAAO,OAAO;AAC7C"}
package/esm/panels.mjs CHANGED
@@ -328,6 +328,19 @@ function productionPanels(packagePanels, overrides = {}) {
328
328
  panels: packagePanels.filter((panel) => overrides[panel.id] ?? panel.production)
329
329
  };
330
330
  }
331
+ /** The tabs that read per-process run details; production keeps hourly totals instead. */
332
+ const DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS = ["ai", "agents"];
333
+ /**
334
+ * Drops the Runs (`ai`) and Agents (`agents`) tabs from a production tab list.
335
+ * `ignored` lists the ones the project asked for (`production.panels[id] === true`),
336
+ * so boot can warn once.
337
+ */
338
+ function withoutDevelopmentAiTabs(builtIn, overrides = {}) {
339
+ return {
340
+ builtIn: builtIn.filter((tab) => !DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.includes(tab)),
341
+ ignored: DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.filter((tab) => overrides[tab] === true)
342
+ };
343
+ }
331
344
  /**
332
345
  * The tab list `GET api/panels` answers with: the built-in tabs in
333
346
  * `builtIn` (default: every one), in display order, then the package panels
@@ -350,5 +363,5 @@ function listPanelInfos(panels, builtIn) {
350
363
  }
351
364
 
352
365
  //#endregion
353
- export { DEFAULT_PANEL_FILE_EXTENSIONS, checkDevtoolsPanel, checkDevtoolsPanels, listPanelInfos, loadDevtoolsPanels, panelContentType, productionPanels };
366
+ export { DEFAULT_PANEL_FILE_EXTENSIONS, DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS, checkDevtoolsPanel, checkDevtoolsPanels, listPanelInfos, loadDevtoolsPanels, panelContentType, productionPanels, withoutDevelopmentAiTabs };
354
367
  //# sourceMappingURL=panels.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"panels.mjs","names":[],"sources":["../../../../../../../packages/devtools/src/panels.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { DEVTOOLS_BUILT_IN_PANELS } from \"./production/contracts\";\nimport type { DevtoolsMode, DevtoolsPanelInfo } from \"./production/contracts\";\nimport type {\n DevtoolsPanel,\n DevtoolsPanelEntry,\n DevtoolsPanelErrorSummary,\n DevtoolsPanelExport,\n DevtoolsPanelMethod,\n DevtoolsPanelRoute,\n} from \"./types\";\n\n/**\n * A validated panel: file paths are absolute strings and every list is\n * present, so the server never re-checks them per request.\n */\nexport type MountedDevtoolsPanel = {\n id: string;\n title: string;\n view: string;\n routes: readonly (DevtoolsPanelRoute & { method: DevtoolsPanelMethod })[];\n assets: Readonly<Record<string, string>>;\n /** The folder of images the panel serves; `null` when it declared none. */\n files: MountedPanelFiles | null;\n /** What a read-only share link of the panel opens; `null` when the panel cannot be shared. */\n share: MountedPanelShare | null;\n /** Whether the panel declared itself safe for the production monitor. */\n production: boolean;\n};\n\n/** A panel's folder of images, validated: an absolute directory and lower-case extensions. */\nexport type MountedPanelFiles = {\n dir: string;\n extensions: readonly string[];\n};\n\n/** A panel's shared view, validated. */\nexport type MountedPanelShare = {\n /** Absolute path of the shared view module. */\n view: string;\n /** Paths of the GET routes the shared page may call. */\n routes: readonly string[];\n /** Served names from `assets` the shared page may load. */\n assets: readonly string[];\n /** Whether the shared page may load images from `files`. */\n files: boolean;\n};\n\n/** The extensions a panel serves from `files` when it lists none. */\nexport const DEFAULT_PANEL_FILE_EXTENSIONS: readonly string[] = [\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".webp\",\n \".gif\",\n];\n\n/** Extensions a panel may never serve from `files`: a browser runs or renders them as a page. */\nconst BLOCKED_FILE_EXTENSIONS = new Set([\".svg\", \".html\", \".htm\", \".js\", \".mjs\"]);\n\n/**\n * Ids the dashboard already uses for its own tabs, API segments and URLs. A\n * panel's routes live under `<path>/api/<id>`, so these would collide.\n */\nconst RESERVED_PANEL_IDS = new Set([\n \"account\",\n \"admin\",\n \"agents\",\n \"ai\",\n \"api\",\n \"assets\",\n \"auth\",\n \"background\",\n \"docs\",\n \"errors\",\n \"health\",\n \"instances\",\n \"jobs\",\n \"logs\",\n \"mail\",\n \"mails\",\n \"panels\",\n \"queries\",\n \"requests\",\n \"resources\",\n \"routes\",\n \"share\",\n \"stream\",\n]);\n\nconst PANEL_ID = /^[a-z][a-z0-9-]*$/;\nconst ASSET_NAME = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;\nconst METHODS = new Set<DevtoolsPanelMethod>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/** Content types for the files a panel may serve; anything else is sent as bytes. */\nconst CONTENT_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".gif\": \"image/gif\",\n \".woff2\": \"font/woff2\",\n};\n\n/** The content type a panel file is served with, from its served name. */\nexport function panelContentType(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** An absolute file path from a path or `file:` URL, or `undefined` for anything else. */\nfunction toFilePath(value: unknown): string | undefined {\n if (value instanceof URL) return value.protocol === \"file:\" ? fileURLToPath(value) : undefined;\n if (typeof value !== \"string\" || value === \"\") return undefined;\n if (value.startsWith(\"file:\")) return fileURLToPath(value);\n\n return path.isAbsolute(value) ? value : undefined;\n}\n\nfunction isFile(file: string): boolean {\n return existsSync(file) && statSync(file).isFile();\n}\n\n/**\n * Validates `value` as a panel and returns it ready to mount. Throws an\n * error that names the panel and what to change; `taken` maps the ids\n * already registered to their titles and receives this panel's id.\n */\nexport function checkDevtoolsPanel(\n value: unknown,\n taken: Map<string, string>,\n): MountedDevtoolsPanel {\n const panel = (value ?? {}) as Partial<DevtoolsPanel>;\n const id = panel.id;\n\n if (typeof id !== \"string\" || !PANEL_ID.test(id)) {\n throw new Error(\n `A devtools panel needs an \"id\" of lower-case letters, digits and dashes that starts with a letter; got ${JSON.stringify(id)}.`,\n );\n }\n\n if (RESERVED_PANEL_IDS.has(id)) {\n throw new Error(\n `Devtools panel id \"${id}\" is used by the dashboard itself; give the panel another id.`,\n );\n }\n\n const existing = taken.get(id);\n\n if (existing !== undefined) {\n throw new Error(\n `Devtools panel id \"${id}\" is already registered by the \"${existing}\" panel; each panel needs its own id.`,\n );\n }\n\n if (typeof panel.title !== \"string\" || panel.title.trim() === \"\") {\n throw new Error(`Devtools panel \"${id}\" needs a \"title\" for its tab.`);\n }\n\n const view = toFilePath(panel.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs a \"view\": an absolute path or file: URL of its browser module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n // Two routes on one method and path would make the server refuse to start.\n const seen = new Set<string>();\n const routes = (panel.routes ?? []).map((route) => {\n const method = route.method ?? \"GET\";\n\n if (!METHODS.has(method)) {\n throw new Error(\n `Devtools panel \"${id}\" has a route with method \"${String(method)}\"; use GET, POST, PUT, PATCH or DELETE.`,\n );\n }\n\n if (typeof route.path !== \"string\" || (route.path !== \"\" && !route.path.startsWith(\"/\"))) {\n throw new Error(\n `Devtools panel \"${id}\" has a route path ${JSON.stringify(route.path)}; use \"\" or a path starting with \"/\".`,\n );\n }\n\n if (typeof route.handler !== \"function\") {\n throw new Error(`Devtools panel \"${id}\" route ${method} \"${route.path}\" has no handler.`);\n }\n\n if (seen.has(`${method} ${route.path}`)) {\n throw new Error(\n `Devtools panel \"${id}\" lists route ${method} \"${route.path}\" twice; keep one.`,\n );\n }\n\n seen.add(`${method} ${route.path}`);\n\n return { ...route, method };\n });\n\n const assets: Record<string, string> = {};\n\n for (const [name, source] of Object.entries(panel.assets ?? {})) {\n if (!ASSET_NAME.test(name) || name === \"view.js\") {\n throw new Error(\n `Devtools panel \"${id}\" has an asset named ${JSON.stringify(name)}; use a plain file name other than \"view.js\".`,\n );\n }\n\n const file = toFilePath(source);\n\n if (file === undefined || !isFile(file)) {\n throw new Error(\n `The asset \"${name}\" of devtools panel \"${id}\" was not found at ${String(source)}; give an absolute path or file: URL.`,\n );\n }\n\n assets[name] = file;\n }\n\n const files = checkPanelFiles(id, panel.files);\n const share = checkPanelShare(id, panel.share, routes, assets, files !== null);\n\n taken.set(id, panel.title);\n\n return {\n id,\n title: panel.title,\n view,\n routes,\n assets,\n files,\n share,\n production: panel.production === true,\n };\n}\n\nconst FILE_EXTENSION = /^\\.[a-z0-9]{1,16}$/;\n\n/** Validates `files`; `null` when the panel declares none. */\nfunction checkPanelFiles(\n id: string,\n value: DevtoolsPanel[\"files\"] | null,\n): MountedPanelFiles | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has files that is not an object; use { dir: \"/absolute/folder\" }.`,\n );\n }\n\n const dir = toFilePath(value.dir);\n\n if (dir === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs files.dir to be an absolute path or a file: URL; got ${String(value.dir)}.`,\n );\n }\n\n const given = value.extensions;\n\n if (given !== undefined && (!Array.isArray(given) || given.length === 0)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions that is not a list; use [\".png\", \".jpg\"] or leave it out.`,\n );\n }\n\n for (const extension of given ?? []) {\n if (typeof extension !== \"string\" || !FILE_EXTENSION.test(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions entry ${JSON.stringify(extension)}; use lower-case extensions that start with a dot, such as \".png\".`,\n );\n }\n\n if (BLOCKED_FILE_EXTENSIONS.has(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" lists files.extensions entry \"${extension}\", which can run as a page or script in the browser; remove it (images such as .png, .jpg, .webp and .gif are fine).`,\n );\n }\n }\n\n return { dir, extensions: [...(given ?? DEFAULT_PANEL_FILE_EXTENSIONS)] };\n}\n\n/** Validates `share` against the panel's own routes, assets and files. */\nfunction checkPanelShare(\n id: string,\n value: DevtoolsPanel[\"share\"] | null,\n routes: readonly { method: DevtoolsPanelMethod; path: string }[],\n assets: Readonly<Record<string, string>>,\n hasFiles: boolean,\n): MountedPanelShare | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has share that is not an object; use { view, routes }.`,\n );\n }\n\n const view = toFilePath(value.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.view: an absolute path or file: URL of the shared view module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The share.view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n if (!Array.isArray(value.routes)) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.routes: a list of the paths of its GET routes the shared page may call.`,\n );\n }\n\n const getPaths = routes.filter((route) => route.method === \"GET\").map((route) => route.path);\n\n for (const route of value.routes) {\n if (typeof route !== \"string\" || !getPaths.includes(route)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.routes entry ${JSON.stringify(route)}, which is not the path of one of its GET routes${getPaths.length > 0 ? `; use one of ${getPaths.map((path) => JSON.stringify(path)).join(\", \")}` : \" (the panel has no GET routes)\"}.`,\n );\n }\n }\n\n for (const name of value.assets ?? []) {\n if (typeof name !== \"string\" || !Object.hasOwn(assets, name)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.assets entry ${JSON.stringify(name)}, which is not a name in its assets; use one of ${Object.keys(assets).join(\", \") || \"(the panel has no assets)\"}.`,\n );\n }\n }\n\n const files = value.files === true;\n\n if (value.files !== undefined && typeof value.files !== \"boolean\") {\n throw new Error(`Devtools panel \"${id}\" needs share.files to be true or false.`);\n }\n\n if (files && !hasFiles) {\n throw new Error(\n `Devtools panel \"${id}\" sets share.files, but the panel has no files folder; add files: { dir } or remove share.files.`,\n );\n }\n\n return { view, routes: [...value.routes], assets: [...(value.assets ?? [])], files };\n}\n\n/** Validates a list of panels; the first invalid or duplicate one throws. */\nexport function checkDevtoolsPanels(panels: readonly unknown[]): MountedDevtoolsPanel[] {\n const taken = new Map<string, string>();\n\n return panels.map((panel) => checkDevtoolsPanel(panel, taken));\n}\n\n/** Hooks `loadDevtoolsPanels` uses; replaced in specs. */\nexport type LoadDevtoolsPanelsOptions = {\n /** The app's root directory: bare specifiers resolve from here, `./` paths are relative to it. */\n root: string;\n /** Receives one line per entry that could not be loaded or was rejected. */\n warn: (message: string) => void;\n /** Ids already taken (the built-in panels), mapped to their titles. */\n taken?: ReadonlyMap<string, string>;\n /** Imports a module URL or specifier; defaults to a dynamic `import()`. */\n importModule?: (specifier: string) => Promise<unknown>;\n /** Where the dashboard runs; panel factories receive it as `context.mode`. @default \"development\" */\n mode?: DevtoolsMode;\n /** The captured error groups of the last hour; panel factories receive it as `context.errors`. */\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\n/** What is wrong with a `[specifier, options]` entry, or `undefined` when it is valid. */\nfunction tupleProblem(entry: readonly unknown[]): string | undefined {\n if (entry.length !== 2) {\n return `it has ${entry.length} item(s); use exactly [specifier, options]`;\n }\n\n if (typeof entry[0] !== \"string\" || entry[0] === \"\") {\n return `its first item is ${JSON.stringify(entry[0])}; use the module specifier as a string`;\n }\n\n if (!isPlainObject(entry[1])) {\n return `its second item is not a plain object; pass the options as { name: value }`;\n }\n\n return undefined;\n}\n\n/** The URL or specifier to import for a `panels` entry. */\nfunction resolvePanelSpecifier(entry: string, root: string): string {\n if (entry.startsWith(\"./\") || entry.startsWith(\"../\") || path.isAbsolute(entry)) {\n return pathToFileURL(path.resolve(root, entry)).href;\n }\n\n return resolveFromNodeModules(entry, root) ?? resolveWithRequire(entry, root) ?? entry;\n}\n\n/** Picks the file an `exports` target names: `import`, then `default`, then `node`. */\nfunction exportTarget(target: unknown): string | undefined {\n if (typeof target === \"string\") return target;\n\n if (Array.isArray(target)) {\n for (const item of target) {\n const found = exportTarget(item);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n }\n\n if (target !== null && typeof target === \"object\") {\n const conditions = target as Record<string, unknown>;\n\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const found = exportTarget(conditions[condition]);\n\n if (found !== undefined) return found;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a package specifier by looking it up in the `node_modules` folders\n * above the app root and reading its `exports` map. `createRequire().resolve`\n * cannot do this for a package that only has an `import` condition.\n */\nfunction resolveFromNodeModules(entry: string, root: string): string | undefined {\n const parts = entry.split(\"/\");\n const nameLength = entry.startsWith(\"@\") ? 2 : 1;\n const name = parts.slice(0, nameLength).join(\"/\");\n const subpath = parts.length > nameLength ? `./${parts.slice(nameLength).join(\"/\")}` : \".\";\n\n if (!name) return undefined;\n\n let directory = path.resolve(root);\n\n for (;;) {\n const packageDirectory = path.join(directory, \"node_modules\", name);\n const manifestFile = path.join(packageDirectory, \"package.json\");\n\n if (existsSync(manifestFile)) {\n try {\n const manifest = JSON.parse(readFileSync(manifestFile, \"utf8\")) as {\n exports?: unknown;\n main?: string;\n };\n const exported = manifest.exports;\n const map =\n exported !== null && typeof exported === \"object\" && !Array.isArray(exported)\n ? (exported as Record<string, unknown>)\n : undefined;\n const hasSubpaths =\n map !== undefined && Object.keys(map).some((key) => key.startsWith(\".\"));\n const target =\n exported === undefined\n ? subpath === \".\"\n ? (manifest.main ?? \"index.js\")\n : subpath\n : hasSubpaths\n ? exportTarget(map?.[subpath])\n : subpath === \".\"\n ? exportTarget(exported)\n : undefined;\n\n if (target === undefined) return undefined;\n\n const file = path.resolve(packageDirectory, target);\n\n return isFile(file) ? pathToFileURL(file).href : undefined;\n } catch {\n return undefined;\n }\n }\n\n const parent = path.dirname(directory);\n\n if (parent === directory) return undefined;\n\n directory = parent;\n }\n}\n\n/** The `require` resolution, for packages the `node_modules` lookup does not understand. */\nfunction resolveWithRequire(entry: string, root: string): string | undefined {\n try {\n return pathToFileURL(createRequire(path.join(root, \"package.json\")).resolve(entry)).href;\n } catch {\n return undefined;\n }\n}\n\n/** The panels a module's default export describes. */\nasync function panelsOf(\n exported: DevtoolsPanelExport,\n root: string,\n mode: DevtoolsMode,\n panelOptions: Readonly<Record<string, unknown>> = {},\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>,\n): Promise<readonly unknown[]> {\n const value =\n typeof exported === \"function\"\n ? await exported({ ...panelOptions, root, mode, ...(errors ? { errors } : {}) })\n : exported;\n\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Loads the devtools `panels` option: imports each module entry, reads its\n * default export, and validates every panel. An entry that fails to load and\n * a panel that is invalid or reuses an id are reported through `warn` and\n * skipped, so one broken panel never stops the dashboard.\n */\nexport async function loadDevtoolsPanels(\n entries: readonly DevtoolsPanelEntry[],\n options: LoadDevtoolsPanelsOptions,\n): Promise<MountedDevtoolsPanel[]> {\n // `src/config/devtools.ts` is a plain object with no types: a single string would be read letter by letter.\n if (!Array.isArray(entries as unknown)) {\n options.warn(\n `The devtools \"panels\" option must be a list, such as panels: [\"@warlock.js/grimoire/devtools\"]; got ${JSON.stringify(entries)}. No panel was added.`,\n );\n\n return [];\n }\n\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const mode = options.mode ?? \"development\";\n const taken = new Map<string, string>(options.taken ?? []);\n const panels: MountedDevtoolsPanel[] = [];\n\n for (const entry of entries) {\n let candidates: readonly unknown[];\n\n try {\n if (Array.isArray(entry as unknown)) {\n const problem = tupleProblem(entry as readonly unknown[]);\n\n if (problem !== undefined) {\n options.warn(\n `Devtools panels entry ${JSON.stringify(entry)} is invalid: ${problem}. Example: [\"@warlock.js/grimoire/devtools\", { ttlMs: 60000 }]. The entry was not added.`,\n );\n continue;\n }\n }\n\n if (typeof entry === \"string\" || Array.isArray(entry as unknown)) {\n const [specifier, panelOptions] =\n typeof entry === \"string\"\n ? [entry, undefined]\n : (entry as readonly [string, Record<string, unknown>]);\n const module = (await importModule(resolvePanelSpecifier(specifier, options.root))) as {\n default?: DevtoolsPanelExport;\n };\n\n if (module.default === undefined) {\n throw new Error(\"the module has no default export\");\n }\n\n candidates = await panelsOf(\n module.default,\n options.root,\n mode,\n panelOptions,\n options.errors,\n );\n } else {\n candidates = [entry];\n }\n } catch (error) {\n options.warn(\n `Devtools panel module \"${String(Array.isArray(entry as unknown) ? (entry as readonly unknown[])[0] : entry)}\" could not be loaded: ${describe(error)}. Check that it is installed and listed correctly in the devtools \"panels\" option.`,\n );\n continue;\n }\n\n for (const candidate of candidates) {\n try {\n panels.push(checkDevtoolsPanel(candidate, taken));\n } catch (error) {\n options.warn(`${describe(error)} The panel was not added.`);\n }\n }\n }\n\n return panels;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** What `productionPanels` decides. */\nexport type DevtoolsProductionPanels = {\n /** Built-in tab ids shown, in display order. */\n builtIn: string[];\n /** Package panels shown. */\n panels: MountedDevtoolsPanel[];\n};\n\n/**\n * Which tabs the production monitor shows. A built-in tab follows\n * `DEVTOOLS_BUILT_IN_PANELS` unless `overrides[id]` says otherwise. A package\n * panel (the Processes panel included) shows when it declares\n * `production: true` or `overrides[id]` is `true`; `overrides[id]: false` turns\n * any tab off.\n */\nexport function productionPanels(\n packagePanels: readonly MountedDevtoolsPanel[],\n overrides: Readonly<Record<string, boolean>> = {},\n): DevtoolsProductionPanels {\n const builtIn = DEVTOOLS_BUILT_IN_PANELS.filter((tab) => overrides[tab.id] ?? tab.production).map(\n (tab) => tab.id,\n );\n const panels = packagePanels.filter((panel) => overrides[panel.id] ?? panel.production);\n\n return { builtIn, panels };\n}\n\n/**\n * The tab list `GET api/panels` answers with: the built-in tabs in\n * `builtIn` (default: every one), in display order, then the package panels\n * in registration order.\n */\nexport function listPanelInfos(\n panels: readonly (Pick<MountedDevtoolsPanel, \"id\" | \"title\"> &\n Partial<Pick<MountedDevtoolsPanel, \"share\">>)[],\n builtIn?: readonly string[],\n): DevtoolsPanelInfo[] {\n const tabs: DevtoolsPanelInfo[] = DEVTOOLS_BUILT_IN_PANELS.filter(\n (tab) => builtIn === undefined || builtIn.includes(tab.id),\n ).map((tab) => ({\n id: tab.id,\n title: tab.title,\n type: \"built-in\" as const,\n shareable: false,\n }));\n\n for (const panel of panels) {\n tabs.push({\n id: panel.id,\n title: panel.title,\n type: \"package\" as const,\n shareable: panel.share !== undefined && panel.share !== null,\n });\n }\n\n return tabs;\n}\n"],"mappings":";;;;;;;;AAoDA,MAAa,gCAAmD;CAC9D;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAQ;CAAO;AAAM,CAAC;;;;;AAMhF,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,WAAW;AACjB,MAAM,aAAa;AACnB,MAAM,0BAAU,IAAI,IAAyB;CAAC;CAAO;CAAQ;CAAO;CAAS;AAAQ,CAAC;;AAGtF,MAAM,gBAAwC;CAC5C,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,UAAU;AACZ;;AAGA,SAAgB,iBAAiB,MAAsB;CACrD,OAAO,cAAc,KAAK,QAAQ,IAAI,CAAC,CAAC,YAAY,MAAM;AAC5D;;AAGA,SAAS,WAAW,OAAoC;CACtD,IAAI,iBAAiB,KAAK,OAAO,MAAM,aAAa,UAAU,cAAc,KAAK,IAAI;CACrF,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO;CACtD,IAAI,MAAM,WAAW,OAAO,GAAG,OAAO,cAAc,KAAK;CAEzD,OAAO,KAAK,WAAW,KAAK,IAAI,QAAQ;AAC1C;AAEA,SAAS,OAAO,MAAuB;CACrC,OAAO,WAAW,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,OAAO;AACnD;;;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ACrB,MAAM,OAA4B,yBAAyB,QACxD,QAAQ,YAAY,UAAa,QAAQ,SAAS,IAAI,EAAE,CAC3D,CAAC,CAAC,KAAK,SAAS;EACd,IAAI,IAAI;EACR,OAAO,IAAI;EACX,MAAM;EACN,WAAW;CACb,EAAE;CAEF,KAAK,MAAM,SAAS,QAClB,KAAK,KAAK;EACR,IAAI,MAAM;EACV,OAAO,MAAM;EACb,MAAM;EACN,WAAW,MAAM,UAAU,UAAa,MAAM,UAAU;CAC1D,CAAC;CAGH,OAAO;AACT"}
1
+ {"version":3,"file":"panels.mjs","names":[],"sources":["../../../../../../../packages/devtools/src/panels.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { DEVTOOLS_BUILT_IN_PANELS } from \"./production/contracts\";\nimport type { DevtoolsMode, DevtoolsPanelInfo } from \"./production/contracts\";\nimport type {\n DevtoolsPanel,\n DevtoolsPanelEntry,\n DevtoolsPanelErrorSummary,\n DevtoolsPanelExport,\n DevtoolsPanelMethod,\n DevtoolsPanelRoute,\n} from \"./types\";\n\n/**\n * A validated panel: file paths are absolute strings and every list is\n * present, so the server never re-checks them per request.\n */\nexport type MountedDevtoolsPanel = {\n id: string;\n title: string;\n view: string;\n routes: readonly (DevtoolsPanelRoute & { method: DevtoolsPanelMethod })[];\n assets: Readonly<Record<string, string>>;\n /** The folder of images the panel serves; `null` when it declared none. */\n files: MountedPanelFiles | null;\n /** What a read-only share link of the panel opens; `null` when the panel cannot be shared. */\n share: MountedPanelShare | null;\n /** Whether the panel declared itself safe for the production monitor. */\n production: boolean;\n};\n\n/** A panel's folder of images, validated: an absolute directory and lower-case extensions. */\nexport type MountedPanelFiles = {\n dir: string;\n extensions: readonly string[];\n};\n\n/** A panel's shared view, validated. */\nexport type MountedPanelShare = {\n /** Absolute path of the shared view module. */\n view: string;\n /** Paths of the GET routes the shared page may call. */\n routes: readonly string[];\n /** Served names from `assets` the shared page may load. */\n assets: readonly string[];\n /** Whether the shared page may load images from `files`. */\n files: boolean;\n};\n\n/** The extensions a panel serves from `files` when it lists none. */\nexport const DEFAULT_PANEL_FILE_EXTENSIONS: readonly string[] = [\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".webp\",\n \".gif\",\n];\n\n/** Extensions a panel may never serve from `files`: a browser runs or renders them as a page. */\nconst BLOCKED_FILE_EXTENSIONS = new Set([\".svg\", \".html\", \".htm\", \".js\", \".mjs\"]);\n\n/**\n * Ids the dashboard already uses for its own tabs, API segments and URLs. A\n * panel's routes live under `<path>/api/<id>`, so these would collide.\n */\nconst RESERVED_PANEL_IDS = new Set([\n \"account\",\n \"admin\",\n \"agents\",\n \"ai\",\n \"api\",\n \"assets\",\n \"auth\",\n \"background\",\n \"docs\",\n \"errors\",\n \"health\",\n \"instances\",\n \"jobs\",\n \"logs\",\n \"mail\",\n \"mails\",\n \"panels\",\n \"queries\",\n \"requests\",\n \"resources\",\n \"routes\",\n \"share\",\n \"stream\",\n]);\n\nconst PANEL_ID = /^[a-z][a-z0-9-]*$/;\nconst ASSET_NAME = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;\nconst METHODS = new Set<DevtoolsPanelMethod>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/** Content types for the files a panel may serve; anything else is sent as bytes. */\nconst CONTENT_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".gif\": \"image/gif\",\n \".woff2\": \"font/woff2\",\n};\n\n/** The content type a panel file is served with, from its served name. */\nexport function panelContentType(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** An absolute file path from a path or `file:` URL, or `undefined` for anything else. */\nfunction toFilePath(value: unknown): string | undefined {\n if (value instanceof URL) return value.protocol === \"file:\" ? fileURLToPath(value) : undefined;\n if (typeof value !== \"string\" || value === \"\") return undefined;\n if (value.startsWith(\"file:\")) return fileURLToPath(value);\n\n return path.isAbsolute(value) ? value : undefined;\n}\n\nfunction isFile(file: string): boolean {\n return existsSync(file) && statSync(file).isFile();\n}\n\n/**\n * Validates `value` as a panel and returns it ready to mount. Throws an\n * error that names the panel and what to change; `taken` maps the ids\n * already registered to their titles and receives this panel's id.\n */\nexport function checkDevtoolsPanel(\n value: unknown,\n taken: Map<string, string>,\n): MountedDevtoolsPanel {\n const panel = (value ?? {}) as Partial<DevtoolsPanel>;\n const id = panel.id;\n\n if (typeof id !== \"string\" || !PANEL_ID.test(id)) {\n throw new Error(\n `A devtools panel needs an \"id\" of lower-case letters, digits and dashes that starts with a letter; got ${JSON.stringify(id)}.`,\n );\n }\n\n if (RESERVED_PANEL_IDS.has(id)) {\n throw new Error(\n `Devtools panel id \"${id}\" is used by the dashboard itself; give the panel another id.`,\n );\n }\n\n const existing = taken.get(id);\n\n if (existing !== undefined) {\n throw new Error(\n `Devtools panel id \"${id}\" is already registered by the \"${existing}\" panel; each panel needs its own id.`,\n );\n }\n\n if (typeof panel.title !== \"string\" || panel.title.trim() === \"\") {\n throw new Error(`Devtools panel \"${id}\" needs a \"title\" for its tab.`);\n }\n\n const view = toFilePath(panel.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs a \"view\": an absolute path or file: URL of its browser module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n // Two routes on one method and path would make the server refuse to start.\n const seen = new Set<string>();\n const routes = (panel.routes ?? []).map((route) => {\n const method = route.method ?? \"GET\";\n\n if (!METHODS.has(method)) {\n throw new Error(\n `Devtools panel \"${id}\" has a route with method \"${String(method)}\"; use GET, POST, PUT, PATCH or DELETE.`,\n );\n }\n\n if (typeof route.path !== \"string\" || (route.path !== \"\" && !route.path.startsWith(\"/\"))) {\n throw new Error(\n `Devtools panel \"${id}\" has a route path ${JSON.stringify(route.path)}; use \"\" or a path starting with \"/\".`,\n );\n }\n\n if (typeof route.handler !== \"function\") {\n throw new Error(`Devtools panel \"${id}\" route ${method} \"${route.path}\" has no handler.`);\n }\n\n if (seen.has(`${method} ${route.path}`)) {\n throw new Error(\n `Devtools panel \"${id}\" lists route ${method} \"${route.path}\" twice; keep one.`,\n );\n }\n\n seen.add(`${method} ${route.path}`);\n\n return { ...route, method };\n });\n\n const assets: Record<string, string> = {};\n\n for (const [name, source] of Object.entries(panel.assets ?? {})) {\n if (!ASSET_NAME.test(name) || name === \"view.js\") {\n throw new Error(\n `Devtools panel \"${id}\" has an asset named ${JSON.stringify(name)}; use a plain file name other than \"view.js\".`,\n );\n }\n\n const file = toFilePath(source);\n\n if (file === undefined || !isFile(file)) {\n throw new Error(\n `The asset \"${name}\" of devtools panel \"${id}\" was not found at ${String(source)}; give an absolute path or file: URL.`,\n );\n }\n\n assets[name] = file;\n }\n\n const files = checkPanelFiles(id, panel.files);\n const share = checkPanelShare(id, panel.share, routes, assets, files !== null);\n\n taken.set(id, panel.title);\n\n return {\n id,\n title: panel.title,\n view,\n routes,\n assets,\n files,\n share,\n production: panel.production === true,\n };\n}\n\nconst FILE_EXTENSION = /^\\.[a-z0-9]{1,16}$/;\n\n/** Validates `files`; `null` when the panel declares none. */\nfunction checkPanelFiles(\n id: string,\n value: DevtoolsPanel[\"files\"] | null,\n): MountedPanelFiles | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has files that is not an object; use { dir: \"/absolute/folder\" }.`,\n );\n }\n\n const dir = toFilePath(value.dir);\n\n if (dir === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs files.dir to be an absolute path or a file: URL; got ${String(value.dir)}.`,\n );\n }\n\n const given = value.extensions;\n\n if (given !== undefined && (!Array.isArray(given) || given.length === 0)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions that is not a list; use [\".png\", \".jpg\"] or leave it out.`,\n );\n }\n\n for (const extension of given ?? []) {\n if (typeof extension !== \"string\" || !FILE_EXTENSION.test(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" has files.extensions entry ${JSON.stringify(extension)}; use lower-case extensions that start with a dot, such as \".png\".`,\n );\n }\n\n if (BLOCKED_FILE_EXTENSIONS.has(extension)) {\n throw new Error(\n `Devtools panel \"${id}\" lists files.extensions entry \"${extension}\", which can run as a page or script in the browser; remove it (images such as .png, .jpg, .webp and .gif are fine).`,\n );\n }\n }\n\n return { dir, extensions: [...(given ?? DEFAULT_PANEL_FILE_EXTENSIONS)] };\n}\n\n/** Validates `share` against the panel's own routes, assets and files. */\nfunction checkPanelShare(\n id: string,\n value: DevtoolsPanel[\"share\"] | null,\n routes: readonly { method: DevtoolsPanelMethod; path: string }[],\n assets: Readonly<Record<string, string>>,\n hasFiles: boolean,\n): MountedPanelShare | null {\n // A panel that was mounted before carries `null` for \"none\".\n if (value === undefined || value === null) return null;\n\n if (typeof value !== \"object\") {\n throw new Error(\n `Devtools panel \"${id}\" has share that is not an object; use { view, routes }.`,\n );\n }\n\n const view = toFilePath(value.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.view: an absolute path or file: URL of the shared view module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The share.view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n if (!Array.isArray(value.routes)) {\n throw new Error(\n `Devtools panel \"${id}\" needs share.routes: a list of the paths of its GET routes the shared page may call.`,\n );\n }\n\n const getPaths = routes.filter((route) => route.method === \"GET\").map((route) => route.path);\n\n for (const route of value.routes) {\n if (typeof route !== \"string\" || !getPaths.includes(route)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.routes entry ${JSON.stringify(route)}, which is not the path of one of its GET routes${getPaths.length > 0 ? `; use one of ${getPaths.map((path) => JSON.stringify(path)).join(\", \")}` : \" (the panel has no GET routes)\"}.`,\n );\n }\n }\n\n for (const name of value.assets ?? []) {\n if (typeof name !== \"string\" || !Object.hasOwn(assets, name)) {\n throw new Error(\n `Devtools panel \"${id}\" lists share.assets entry ${JSON.stringify(name)}, which is not a name in its assets; use one of ${Object.keys(assets).join(\", \") || \"(the panel has no assets)\"}.`,\n );\n }\n }\n\n const files = value.files === true;\n\n if (value.files !== undefined && typeof value.files !== \"boolean\") {\n throw new Error(`Devtools panel \"${id}\" needs share.files to be true or false.`);\n }\n\n if (files && !hasFiles) {\n throw new Error(\n `Devtools panel \"${id}\" sets share.files, but the panel has no files folder; add files: { dir } or remove share.files.`,\n );\n }\n\n return { view, routes: [...value.routes], assets: [...(value.assets ?? [])], files };\n}\n\n/** Validates a list of panels; the first invalid or duplicate one throws. */\nexport function checkDevtoolsPanels(panels: readonly unknown[]): MountedDevtoolsPanel[] {\n const taken = new Map<string, string>();\n\n return panels.map((panel) => checkDevtoolsPanel(panel, taken));\n}\n\n/** Hooks `loadDevtoolsPanels` uses; replaced in specs. */\nexport type LoadDevtoolsPanelsOptions = {\n /** The app's root directory: bare specifiers resolve from here, `./` paths are relative to it. */\n root: string;\n /** Receives one line per entry that could not be loaded or was rejected. */\n warn: (message: string) => void;\n /** Ids already taken (the built-in panels), mapped to their titles. */\n taken?: ReadonlyMap<string, string>;\n /** Imports a module URL or specifier; defaults to a dynamic `import()`. */\n importModule?: (specifier: string) => Promise<unknown>;\n /** Where the dashboard runs; panel factories receive it as `context.mode`. @default \"development\" */\n mode?: DevtoolsMode;\n /** The captured error groups of the last hour; panel factories receive it as `context.errors`. */\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\n/** What is wrong with a `[specifier, options]` entry, or `undefined` when it is valid. */\nfunction tupleProblem(entry: readonly unknown[]): string | undefined {\n if (entry.length !== 2) {\n return `it has ${entry.length} item(s); use exactly [specifier, options]`;\n }\n\n if (typeof entry[0] !== \"string\" || entry[0] === \"\") {\n return `its first item is ${JSON.stringify(entry[0])}; use the module specifier as a string`;\n }\n\n if (!isPlainObject(entry[1])) {\n return `its second item is not a plain object; pass the options as { name: value }`;\n }\n\n return undefined;\n}\n\n/** The URL or specifier to import for a `panels` entry. */\nfunction resolvePanelSpecifier(entry: string, root: string): string {\n if (entry.startsWith(\"./\") || entry.startsWith(\"../\") || path.isAbsolute(entry)) {\n return pathToFileURL(path.resolve(root, entry)).href;\n }\n\n return resolveFromNodeModules(entry, root) ?? resolveWithRequire(entry, root) ?? entry;\n}\n\n/** Picks the file an `exports` target names: `import`, then `default`, then `node`. */\nfunction exportTarget(target: unknown): string | undefined {\n if (typeof target === \"string\") return target;\n\n if (Array.isArray(target)) {\n for (const item of target) {\n const found = exportTarget(item);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n }\n\n if (target !== null && typeof target === \"object\") {\n const conditions = target as Record<string, unknown>;\n\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const found = exportTarget(conditions[condition]);\n\n if (found !== undefined) return found;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a package specifier by looking it up in the `node_modules` folders\n * above the app root and reading its `exports` map. `createRequire().resolve`\n * cannot do this for a package that only has an `import` condition.\n */\nfunction resolveFromNodeModules(entry: string, root: string): string | undefined {\n const parts = entry.split(\"/\");\n const nameLength = entry.startsWith(\"@\") ? 2 : 1;\n const name = parts.slice(0, nameLength).join(\"/\");\n const subpath = parts.length > nameLength ? `./${parts.slice(nameLength).join(\"/\")}` : \".\";\n\n if (!name) return undefined;\n\n let directory = path.resolve(root);\n\n for (;;) {\n const packageDirectory = path.join(directory, \"node_modules\", name);\n const manifestFile = path.join(packageDirectory, \"package.json\");\n\n if (existsSync(manifestFile)) {\n try {\n const manifest = JSON.parse(readFileSync(manifestFile, \"utf8\")) as {\n exports?: unknown;\n main?: string;\n };\n const exported = manifest.exports;\n const map =\n exported !== null && typeof exported === \"object\" && !Array.isArray(exported)\n ? (exported as Record<string, unknown>)\n : undefined;\n const hasSubpaths =\n map !== undefined && Object.keys(map).some((key) => key.startsWith(\".\"));\n const target =\n exported === undefined\n ? subpath === \".\"\n ? (manifest.main ?? \"index.js\")\n : subpath\n : hasSubpaths\n ? exportTarget(map?.[subpath])\n : subpath === \".\"\n ? exportTarget(exported)\n : undefined;\n\n if (target === undefined) return undefined;\n\n const file = path.resolve(packageDirectory, target);\n\n return isFile(file) ? pathToFileURL(file).href : undefined;\n } catch {\n return undefined;\n }\n }\n\n const parent = path.dirname(directory);\n\n if (parent === directory) return undefined;\n\n directory = parent;\n }\n}\n\n/** The `require` resolution, for packages the `node_modules` lookup does not understand. */\nfunction resolveWithRequire(entry: string, root: string): string | undefined {\n try {\n return pathToFileURL(createRequire(path.join(root, \"package.json\")).resolve(entry)).href;\n } catch {\n return undefined;\n }\n}\n\n/** The panels a module's default export describes. */\nasync function panelsOf(\n exported: DevtoolsPanelExport,\n root: string,\n mode: DevtoolsMode,\n panelOptions: Readonly<Record<string, unknown>> = {},\n errors?: () => Promise<readonly DevtoolsPanelErrorSummary[]>,\n): Promise<readonly unknown[]> {\n const value =\n typeof exported === \"function\"\n ? await exported({ ...panelOptions, root, mode, ...(errors ? { errors } : {}) })\n : exported;\n\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Loads the devtools `panels` option: imports each module entry, reads its\n * default export, and validates every panel. An entry that fails to load and\n * a panel that is invalid or reuses an id are reported through `warn` and\n * skipped, so one broken panel never stops the dashboard.\n */\nexport async function loadDevtoolsPanels(\n entries: readonly DevtoolsPanelEntry[],\n options: LoadDevtoolsPanelsOptions,\n): Promise<MountedDevtoolsPanel[]> {\n // `src/config/devtools.ts` is a plain object with no types: a single string would be read letter by letter.\n if (!Array.isArray(entries as unknown)) {\n options.warn(\n `The devtools \"panels\" option must be a list, such as panels: [\"@warlock.js/grimoire/devtools\"]; got ${JSON.stringify(entries)}. No panel was added.`,\n );\n\n return [];\n }\n\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const mode = options.mode ?? \"development\";\n const taken = new Map<string, string>(options.taken ?? []);\n const panels: MountedDevtoolsPanel[] = [];\n\n for (const entry of entries) {\n let candidates: readonly unknown[];\n\n try {\n if (Array.isArray(entry as unknown)) {\n const problem = tupleProblem(entry as readonly unknown[]);\n\n if (problem !== undefined) {\n options.warn(\n `Devtools panels entry ${JSON.stringify(entry)} is invalid: ${problem}. Example: [\"@warlock.js/grimoire/devtools\", { ttlMs: 60000 }]. The entry was not added.`,\n );\n continue;\n }\n }\n\n if (typeof entry === \"string\" || Array.isArray(entry as unknown)) {\n const [specifier, panelOptions] =\n typeof entry === \"string\"\n ? [entry, undefined]\n : (entry as readonly [string, Record<string, unknown>]);\n const module = (await importModule(resolvePanelSpecifier(specifier, options.root))) as {\n default?: DevtoolsPanelExport;\n };\n\n if (module.default === undefined) {\n throw new Error(\"the module has no default export\");\n }\n\n candidates = await panelsOf(\n module.default,\n options.root,\n mode,\n panelOptions,\n options.errors,\n );\n } else {\n candidates = [entry];\n }\n } catch (error) {\n options.warn(\n `Devtools panel module \"${String(Array.isArray(entry as unknown) ? (entry as readonly unknown[])[0] : entry)}\" could not be loaded: ${describe(error)}. Check that it is installed and listed correctly in the devtools \"panels\" option.`,\n );\n continue;\n }\n\n for (const candidate of candidates) {\n try {\n panels.push(checkDevtoolsPanel(candidate, taken));\n } catch (error) {\n options.warn(`${describe(error)} The panel was not added.`);\n }\n }\n }\n\n return panels;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** What `productionPanels` decides. */\nexport type DevtoolsProductionPanels = {\n /** Built-in tab ids shown, in display order. */\n builtIn: string[];\n /** Package panels shown. */\n panels: MountedDevtoolsPanel[];\n};\n\n/**\n * Which tabs the production monitor shows. A built-in tab follows\n * `DEVTOOLS_BUILT_IN_PANELS` unless `overrides[id]` says otherwise. A package\n * panel (the Processes panel included) shows when it declares\n * `production: true` or `overrides[id]` is `true`; `overrides[id]: false` turns\n * any tab off.\n */\nexport function productionPanels(\n packagePanels: readonly MountedDevtoolsPanel[],\n overrides: Readonly<Record<string, boolean>> = {},\n): DevtoolsProductionPanels {\n const builtIn = DEVTOOLS_BUILT_IN_PANELS.filter((tab) => overrides[tab.id] ?? tab.production).map(\n (tab) => tab.id,\n );\n const panels = packagePanels.filter((panel) => overrides[panel.id] ?? panel.production);\n\n return { builtIn, panels };\n}\n\n/** The tabs that read per-process run details; production keeps hourly totals instead. */\nexport const DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS: readonly string[] = [\"ai\", \"agents\"];\n\n/**\n * Drops the Runs (`ai`) and Agents (`agents`) tabs from a production tab list.\n * `ignored` lists the ones the project asked for (`production.panels[id] === true`),\n * so boot can warn once.\n */\nexport function withoutDevelopmentAiTabs(\n builtIn: readonly string[],\n overrides: Readonly<Record<string, boolean>> = {},\n): { builtIn: string[]; ignored: string[] } {\n return {\n builtIn: builtIn.filter((tab) => !DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.includes(tab)),\n ignored: DEVTOOLS_DEVELOPMENT_ONLY_AI_TABS.filter((tab) => overrides[tab] === true),\n };\n}\n\n/**\n * The tab list `GET api/panels` answers with: the built-in tabs in\n * `builtIn` (default: every one), in display order, then the package panels\n * in registration order.\n */\nexport function listPanelInfos(\n panels: readonly (Pick<MountedDevtoolsPanel, \"id\" | \"title\"> &\n Partial<Pick<MountedDevtoolsPanel, \"share\">>)[],\n builtIn?: readonly string[],\n): DevtoolsPanelInfo[] {\n const tabs: DevtoolsPanelInfo[] = DEVTOOLS_BUILT_IN_PANELS.filter(\n (tab) => builtIn === undefined || builtIn.includes(tab.id),\n ).map((tab) => ({\n id: tab.id,\n title: tab.title,\n type: \"built-in\" as const,\n shareable: false,\n }));\n\n for (const panel of panels) {\n tabs.push({\n id: panel.id,\n title: panel.title,\n type: \"package\" as const,\n shareable: panel.share !== undefined && panel.share !== null,\n });\n }\n\n return tabs;\n}\n"],"mappings":";;;;;;;;AAoDA,MAAa,gCAAmD;CAC9D;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAQ;CAAO;AAAM,CAAC;;;;;AAMhF,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,WAAW;AACjB,MAAM,aAAa;AACnB,MAAM,0BAAU,IAAI,IAAyB;CAAC;CAAO;CAAQ;CAAO;CAAS;AAAQ,CAAC;;AAGtF,MAAM,gBAAwC;CAC5C,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,UAAU;AACZ;;AAGA,SAAgB,iBAAiB,MAAsB;CACrD,OAAO,cAAc,KAAK,QAAQ,IAAI,CAAC,CAAC,YAAY,MAAM;AAC5D;;AAGA,SAAS,WAAW,OAAoC;CACtD,IAAI,iBAAiB,KAAK,OAAO,MAAM,aAAa,UAAU,cAAc,KAAK,IAAI;CACrF,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO;CACtD,IAAI,MAAM,WAAW,OAAO,GAAG,OAAO,cAAc,KAAK;CAEzD,OAAO,KAAK,WAAW,KAAK,IAAI,QAAQ;AAC1C;AAEA,SAAS,OAAO,MAAuB;CACrC,OAAO,WAAW,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,OAAO;AACnD;;;;;;AAOA,SAAgB,mBAC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gB,yBACd,SACA,YAA+C,CAAC,GACN;CAC1C,OAAO;EACL,SAAS,QAAQ,QAAQ,QAAQ,CAAC,kCAAkC,SAAS,GAAG,CAAC;EACjF,SAAS,kCAAkC,QAAQ,QAAQ,UAAU,SAAS,IAAI;CACpF;AACF;;;;;;AAOA,SAAgB,eACd,QAEA,SACqB;CACrB,MAAM,OAA4B,yBAAyB,QACxD,QAAQ,YAAY,UAAa,QAAQ,SAAS,IAAI,EAAE,CAC3D,CAAC,CAAC,KAAK,SAAS;EACd,IAAI,IAAI;EACR,OAAO,IAAI;EACX,MAAM;EACN,WAAW;CACb,EAAE;CAEF,KAAK,MAAM,SAAS,QAClB,KAAK,KAAK;EACR,IAAI,MAAM;EACV,OAAO,MAAM;EACb,MAAM;EACN,WAAW,MAAM,UAAU,UAAa,MAAM,UAAU;CAC1D,CAAC;CAGH,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { productionPanels } from "../panels.mjs";
1
+ import { productionPanels, withoutDevelopmentAiTabs } from "../panels.mjs";
2
2
  import { resolveDevtoolsAiOptions } from "../ai/options.mjs";
3
3
  import { DevtoolsProductionConfigError } from "./errors.mjs";
4
4
  import { resolveProductionOptions } from "./options.mjs";
@@ -147,7 +147,9 @@ async function bootProductionDevtools(input) {
147
147
  });
148
148
  input.onInsights?.(insights);
149
149
  const state = httpModule.createDashboardState(store, production.path);
150
- const { builtIn: shownTabs, panels } = productionPanels(input.panels, production.panels);
150
+ const { builtIn: requestedTabs, panels } = productionPanels(input.panels, production.panels);
151
+ const { builtIn: shownTabs, ignored: ignoredAiTabs } = withoutDevelopmentAiTabs(requestedTabs, production.panels);
152
+ if (ignoredAiTabs.length > 0) warn("The Runs and Agents tabs are development tabs, so production.panels.ai and production.panels.agents are ignored. Production shows AI totals in Reports, Models and Errors.");
151
153
  const aiWiring = shownTabs.some((tab) => AI_REPORT_TABS.includes(tab)) ? await attachProductionAi(options, warn) : {
152
154
  feedAvailable: false,
153
155
  reports: {
@@ -1 +1 @@
1
- {"version":3,"file":"boot.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/boot.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport {\n attachAiReports,\n DEVTOOLS_MOUNTED_KEY,\n type DevtoolsAiReports,\n loadAiFeed,\n} from \"../ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"../ai/options\";\nimport { type MountedDevtoolsPanel, productionPanels } from \"../panels\";\nimport type { MountDevtoolsRoutesDeps } from \"../server/types\";\nimport type { ResolvedDevtoolsOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport type { DevtoolsInsights } from \"./insights/types\";\nimport { resolveProductionOptions } from \"./options\";\nimport { describeAiUnavailable, toAiUnavailableView } from \"../sources/ai-source\";\n\n/** What the connector hands production boot. */\nexport type BootProductionDevtoolsInput = {\n options: ResolvedDevtoolsOptions;\n env: Readonly<Record<string, string | undefined>>;\n server: FastifyInstance;\n /** Package panels loaded with `mode: \"production\"` (not yet filtered). */\n panels: readonly MountedDevtoolsPanel[];\n /** The route deps the connector builds for development, reused (requestLog, listRoutes, ai, …). */\n routes: Omit<MountDevtoolsRoutesDeps, \"collector\" | \"options\" | \"isDevelopment\">;\n /** Reads one config value (`encryption.key`); defaults to core's `config.get`. */\n readConfig?: (key: string) => unknown;\n /** Called once the shared insights exist (panels read captured error counts through them). */\n onInsights?: (insights: DevtoolsInsights) => void;\n log: {\n info(module: string, action: string, message: string): unknown;\n warn(module: string, action: string, message: string): unknown;\n error(module: string, action: string, message: string): unknown;\n };\n};\n\nconst AI_REPORT_TABS: readonly string[] = [\"ai-reports\", \"ai-models\", \"ai-errors\"];\n\n/** Tells other packages (Panoptic) that devtools is mounted here and where. */\nfunction publishMounted(path: string): void {\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = { path, mode: \"production\" };\n}\n\nfunction clearMounted(): void {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n}\n\n/**\n * Loads the AI feed and starts this process's rollup writer (every process of\n * a deployment adds into the same table). Never throws: a failure leaves the\n * AI report tabs answering their unavailable view.\n */\nasync function attachProductionAi(\n options: ResolvedDevtoolsOptions,\n warn: (message: string) => void,\n): Promise<{ feedAvailable: boolean; reports: DevtoolsAiReports }> {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) {\n return { feedAvailable: false, reports: { ...loaded.unavailable, async dispose() {} } };\n }\n\n try {\n return {\n feedAvailable: true,\n reports: await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(options.ai, \"production\"),\n warn,\n }),\n };\n } catch (error) {\n warn(`AI reports could not start: ${error instanceof Error ? error.message : String(error)}`);\n\n return {\n feedAvailable: true,\n reports: { ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")), async dispose() {} },\n };\n }\n}\n\n/** `/ops-…`: the first part of the path, enough to recognise it and not enough to use it. */\nexport function maskDashboardPath(path: string): string {\n const match = /^\\/[A-Za-z]{1,8}-/.exec(path);\n\n return `${match ? match[0] : \"/\"}…`;\n}\n\n/** The key core encrypts with: 64 hex characters. */\nfunction hasEncryptionKey(value: unknown): boolean {\n return typeof value === \"string\" && /^[0-9a-fA-F]{64}$/.test(value);\n}\n\n/**\n * Starts the production monitor, in this order: resolve options (env) →\n * check `encryption.key` (DT006) → cascade store (DT005) → `store.verify()`\n * (DT008) → `ensureFirstAdmin()` (DT003/DT004) → instance info → capture\n * (attach hooks) → resource monitor, health history, jobs reader → local\n * reporter → report writer → shared insights → `excludeFromRequestLog(path)`\n * → mount. Logs one line with the path masked (`/ops-…`), never the full path.\n * Any `DevtoolsProductionConfigError` propagates: the app does not boot.\n *\n * Returns the disposer the connector calls at shutdown (flush samples, stop\n * timers, detach hooks).\n */\nexport async function bootProductionDevtools(\n input: BootProductionDevtoolsInput,\n): Promise<() => Promise<void>> {\n const { options, env, server, log } = input;\n const production = resolveProductionOptions(options.production, env);\n const core = await import(\"@warlock.js/core\");\n const readConfig = input.readConfig ?? ((key: string) => core.config.get(key));\n\n if (!hasEncryptionKey(readConfig(\"encryption.key\"))) {\n throw new DevtoolsProductionConfigError(\"DT006\");\n }\n\n const [{ createCascadeStore }, authModule, captureModule, insightsModule, httpModule] =\n await Promise.all([\n import(\"./store\"),\n import(\"./auth\"),\n import(\"./capture\"),\n import(\"./insights\"),\n import(\"./http\"),\n ]);\n\n const store = await createCascadeStore({ shares: production.share.enabled });\n\n await store.verify();\n\n const warn = (message: string): void => {\n log.warn(\"devtools\", \"production\", message);\n };\n if (production.twoFactor === \"off\") {\n warn(\n 'Two-factor sign-in is off for the dashboard (production.twoFactor is \"off\"): anyone with a password can sign in. Set it to \"admins\" or \"everyone\" to require an authenticator app or passkey.',\n );\n }\n\n const instance = insightsModule.createInstanceInfo();\n const [crypto, passkeys] = await Promise.all([\n authModule.defaultDevtoolsCrypto(),\n authModule.loadDevtoolsPasskeys(),\n ]);\n const auth = authModule.createDevtoolsAuth({\n store,\n options: production,\n instance,\n crypto,\n passkeys,\n warn,\n });\n\n await auth.ensureFirstAdmin();\n\n const isDashboardPath = (path: string): boolean =>\n path === production.path || path.startsWith(`${production.path}/`);\n const capture = captureModule.createProductionCapture({\n options,\n production,\n instance,\n store,\n isDashboardPath,\n warn,\n });\n const stops: (() => unknown)[] = [];\n\n try {\n stops.push(await capture.attach());\n\n const resources = insightsModule.createResourceMonitor();\n const health = insightsModule.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insightsModule.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insightsModule.createJobsReader(),\n queries: capture.queries,\n routes: capture.routes,\n errors: capture.errors,\n logs: capture.logs,\n counters: () => capture.counters(),\n });\n const writer = insightsModule.startReportWriter({ reporter, store, production, warn });\n\n stops.push(() => writer.stop());\n\n const insights = insightsModule.createSharedInsights({\n store,\n reporter,\n sampleRate: production.sampleRate,\n });\n input.onInsights?.(insights);\n\n const state = httpModule.createDashboardState(store, production.path);\n const { builtIn: shownTabs, panels } = productionPanels(input.panels, production.panels);\n\n // The AI report tabs are listed only when the app has the AI feed (Panoptic), unless the project turned one on.\n // With every report tab turned off, no totals are written (and no missing-table warning is logged).\n const aiWiring = shownTabs.some((tab) => AI_REPORT_TABS.includes(tab))\n ? await attachProductionAi(options, warn)\n : {\n feedAvailable: false,\n reports: {\n ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")),\n async dispose() {},\n },\n };\n const builtIn = aiWiring.feedAvailable\n ? shownTabs\n : shownTabs.filter((tab) => !AI_REPORT_TABS.includes(tab) || production.panels[tab] === true);\n\n stops.push(() => aiWiring.reports.dispose());\n\n // The dashboard's own requests are not worth a line in the request log, and its sign-in bodies must not reach it.\n if (typeof core.excludeFromRequestLog === \"function\") {\n stops.push(core.excludeFromRequestLog(production.path));\n }\n\n // Mail previews exist only when the project turned that tab on.\n if (builtIn.includes(\"mail\")) {\n const { attachMailSource } = await import(\"../sources/mail-source\");\n\n stops.push(await attachMailSource(capture.collector));\n }\n\n httpModule.mountProductionDevtools(server, {\n routes: {\n ...input.routes,\n aiReports: aiWiring.reports,\n collector: capture.collector,\n options,\n isDevelopment: () => false,\n },\n production,\n store,\n auth,\n capture,\n insights,\n instance,\n panels,\n builtInPanels: builtIn,\n state,\n warn,\n ...(typeof core.answerUnknownUrl === \"function\"\n ? { answerUnknownUrl: core.answerUnknownUrl }\n : {}),\n hmac: (value) => crypto.hmac(value),\n });\n\n publishMounted(production.path);\n stops.push(clearMounted);\n\n log.info(\n \"devtools\",\n \"ready\",\n `devtools production monitor mounted at ${maskDashboardPath(production.path)} (DEVTOOLS_PATH)`,\n );\n } catch (error) {\n for (const stop of stops.splice(0).reverse()) {\n try {\n void Promise.resolve(stop()).catch(() => undefined);\n } catch {\n // Cleanup after a failed boot must not hide the real error.\n }\n }\n\n void capture.dispose().catch(() => undefined);\n\n throw error;\n }\n\n // Returns the promise of the stops so the connector can wait for the final AI totals flush.\n return () => {\n const finished: Promise<unknown>[] = [];\n\n for (const stop of stops.splice(0).reverse()) {\n try {\n finished.push(Promise.resolve(stop()).catch(() => undefined));\n } catch {\n // Shutdown continues past a failing step.\n }\n }\n\n finished.push(capture.dispose().catch(() => undefined));\n\n return Promise.all(finished).then(() => undefined);\n };\n}\n"],"mappings":";;;;;;;;AAoCA,MAAM,iBAAoC;CAAC;CAAc;CAAa;AAAW;;AAGjF,SAAS,eAAe,MAAoB;CAC1C,AAAC,WAAuC,wBAAwB;EAAE;EAAM,MAAM;CAAa;AAC7F;AAEA,SAAS,eAAqB;CAC5B,OAAQ,WAAuC;AACjD;;;;;;AAOA,eAAe,mBACb,SACA,MACiE;CACjE,MAAM,SAAS,MAAM,WAAW;CAEhC,IAAI,iBAAiB,QACnB,OAAO;EAAE,eAAe;EAAO,SAAS;GAAE,GAAG,OAAO;GAAa,MAAM,UAAU,CAAC;EAAE;CAAE;CAGxF,IAAI;EACF,OAAO;GACL,eAAe;GACf,SAAS,MAAM,gBAAgB;IAC7B,MAAM,OAAO;IACb,SAAS,yBAAyB,QAAQ,IAAI,YAAY;IAC1D;GACF,CAAC;EACH;CACF,SAAS,OAAO;EACd,KAAK,+BAA+B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;EAE5F,OAAO;GACL,eAAe;GACf,SAAS;IAAE,GAAG,oBAAoB,sBAAsB,aAAa,CAAC;IAAG,MAAM,UAAU,CAAC;GAAE;EAC9F;CACF;AACF;;AAGA,SAAgB,kBAAkB,MAAsB;CACtD,MAAM,QAAQ,oBAAoB,KAAK,IAAI;CAE3C,OAAO,GAAG,QAAQ,MAAM,KAAK,IAAI;AACnC;;AAGA,SAAS,iBAAiB,OAAyB;CACjD,OAAO,OAAO,UAAU,YAAY,oBAAoB,KAAK,KAAK;AACpE;;;;;;;;;;;;;AAcA,eAAsB,uBACpB,OAC8B;CAC9B,MAAM,EAAE,SAAS,KAAK,QAAQ,QAAQ;CACtC,MAAM,aAAa,yBAAyB,QAAQ,YAAY,GA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,KAAK,iBAAiB,IAC1C,CAAC;GACL,OAAO,UAAU,OAAO,KAAK,KAAK;EACpC,CAAC;EAED,eAAe,WAAW,IAAI;EAC9B,MAAM,KAAK,YAAY;EAEvB,IAAI,KACF,YACA,SACA,0CAA0C,kBAAkB,WAAW,IAAI,EAAE,iBAC/E;CACF,SAAS,OAAO;EACd,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,AAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS;EACpD,QAAQ,CAER;EAGF,AAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS;EAE5C,MAAM;CACR;CAGA,aAAa;EACX,MAAM,WAA+B,CAAC;EAEtC,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,SAAS,KAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS,CAAC;EAC9D,QAAQ,CAER;EAGF,SAAS,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS,CAAC;EAEtD,OAAO,QAAQ,IAAI,QAAQ,CAAC,CAAC,WAAW,MAAS;CACnD;AACF"}
1
+ {"version":3,"file":"boot.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/boot.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport {\n attachAiReports,\n DEVTOOLS_MOUNTED_KEY,\n type DevtoolsAiReports,\n loadAiFeed,\n} from \"../ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"../ai/options\";\nimport { type MountedDevtoolsPanel, productionPanels, withoutDevelopmentAiTabs } from \"../panels\";\nimport type { MountDevtoolsRoutesDeps } from \"../server/types\";\nimport type { ResolvedDevtoolsOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport type { DevtoolsInsights } from \"./insights/types\";\nimport { resolveProductionOptions } from \"./options\";\nimport { describeAiUnavailable, toAiUnavailableView } from \"../sources/ai-source\";\n\n/** What the connector hands production boot. */\nexport type BootProductionDevtoolsInput = {\n options: ResolvedDevtoolsOptions;\n env: Readonly<Record<string, string | undefined>>;\n server: FastifyInstance;\n /** Package panels loaded with `mode: \"production\"` (not yet filtered). */\n panels: readonly MountedDevtoolsPanel[];\n /** The route deps the connector builds for development, reused (requestLog, listRoutes, ai, …). */\n routes: Omit<MountDevtoolsRoutesDeps, \"collector\" | \"options\" | \"isDevelopment\">;\n /** Reads one config value (`encryption.key`); defaults to core's `config.get`. */\n readConfig?: (key: string) => unknown;\n /** Called once the shared insights exist (panels read captured error counts through them). */\n onInsights?: (insights: DevtoolsInsights) => void;\n log: {\n info(module: string, action: string, message: string): unknown;\n warn(module: string, action: string, message: string): unknown;\n error(module: string, action: string, message: string): unknown;\n };\n};\n\nconst AI_REPORT_TABS: readonly string[] = [\"ai-reports\", \"ai-models\", \"ai-errors\"];\n\n/** Tells other packages (Panoptic) that devtools is mounted here and where. */\nfunction publishMounted(path: string): void {\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = { path, mode: \"production\" };\n}\n\nfunction clearMounted(): void {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n}\n\n/**\n * Loads the AI feed and starts this process's rollup writer (every process of\n * a deployment adds into the same table). Never throws: a failure leaves the\n * AI report tabs answering their unavailable view.\n */\nasync function attachProductionAi(\n options: ResolvedDevtoolsOptions,\n warn: (message: string) => void,\n): Promise<{ feedAvailable: boolean; reports: DevtoolsAiReports }> {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) {\n return { feedAvailable: false, reports: { ...loaded.unavailable, async dispose() {} } };\n }\n\n try {\n return {\n feedAvailable: true,\n reports: await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(options.ai, \"production\"),\n warn,\n }),\n };\n } catch (error) {\n warn(`AI reports could not start: ${error instanceof Error ? error.message : String(error)}`);\n\n return {\n feedAvailable: true,\n reports: { ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")), async dispose() {} },\n };\n }\n}\n\n/** `/ops-…`: the first part of the path, enough to recognise it and not enough to use it. */\nexport function maskDashboardPath(path: string): string {\n const match = /^\\/[A-Za-z]{1,8}-/.exec(path);\n\n return `${match ? match[0] : \"/\"}…`;\n}\n\n/** The key core encrypts with: 64 hex characters. */\nfunction hasEncryptionKey(value: unknown): boolean {\n return typeof value === \"string\" && /^[0-9a-fA-F]{64}$/.test(value);\n}\n\n/**\n * Starts the production monitor, in this order: resolve options (env) →\n * check `encryption.key` (DT006) → cascade store (DT005) → `store.verify()`\n * (DT008) → `ensureFirstAdmin()` (DT003/DT004) → instance info → capture\n * (attach hooks) → resource monitor, health history, jobs reader → local\n * reporter → report writer → shared insights → `excludeFromRequestLog(path)`\n * → mount. Logs one line with the path masked (`/ops-…`), never the full path.\n * Any `DevtoolsProductionConfigError` propagates: the app does not boot.\n *\n * Returns the disposer the connector calls at shutdown (flush samples, stop\n * timers, detach hooks).\n */\nexport async function bootProductionDevtools(\n input: BootProductionDevtoolsInput,\n): Promise<() => Promise<void>> {\n const { options, env, server, log } = input;\n const production = resolveProductionOptions(options.production, env);\n const core = await import(\"@warlock.js/core\");\n const readConfig = input.readConfig ?? ((key: string) => core.config.get(key));\n\n if (!hasEncryptionKey(readConfig(\"encryption.key\"))) {\n throw new DevtoolsProductionConfigError(\"DT006\");\n }\n\n const [{ createCascadeStore }, authModule, captureModule, insightsModule, httpModule] =\n await Promise.all([\n import(\"./store\"),\n import(\"./auth\"),\n import(\"./capture\"),\n import(\"./insights\"),\n import(\"./http\"),\n ]);\n\n const store = await createCascadeStore({ shares: production.share.enabled });\n\n await store.verify();\n\n const warn = (message: string): void => {\n log.warn(\"devtools\", \"production\", message);\n };\n if (production.twoFactor === \"off\") {\n warn(\n 'Two-factor sign-in is off for the dashboard (production.twoFactor is \"off\"): anyone with a password can sign in. Set it to \"admins\" or \"everyone\" to require an authenticator app or passkey.',\n );\n }\n\n const instance = insightsModule.createInstanceInfo();\n const [crypto, passkeys] = await Promise.all([\n authModule.defaultDevtoolsCrypto(),\n authModule.loadDevtoolsPasskeys(),\n ]);\n const auth = authModule.createDevtoolsAuth({\n store,\n options: production,\n instance,\n crypto,\n passkeys,\n warn,\n });\n\n await auth.ensureFirstAdmin();\n\n const isDashboardPath = (path: string): boolean =>\n path === production.path || path.startsWith(`${production.path}/`);\n const capture = captureModule.createProductionCapture({\n options,\n production,\n instance,\n store,\n isDashboardPath,\n warn,\n });\n const stops: (() => unknown)[] = [];\n\n try {\n stops.push(await capture.attach());\n\n const resources = insightsModule.createResourceMonitor();\n const health = insightsModule.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insightsModule.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insightsModule.createJobsReader(),\n queries: capture.queries,\n routes: capture.routes,\n errors: capture.errors,\n logs: capture.logs,\n counters: () => capture.counters(),\n });\n const writer = insightsModule.startReportWriter({ reporter, store, production, warn });\n\n stops.push(() => writer.stop());\n\n const insights = insightsModule.createSharedInsights({\n store,\n reporter,\n sampleRate: production.sampleRate,\n });\n input.onInsights?.(insights);\n\n const state = httpModule.createDashboardState(store, production.path);\n const { builtIn: requestedTabs, panels } = productionPanels(input.panels, production.panels);\n\n // Runs and Agents read per-process run details, which production does not keep (it keeps hourly totals).\n const { builtIn: shownTabs, ignored: ignoredAiTabs } = withoutDevelopmentAiTabs(\n requestedTabs,\n production.panels,\n );\n\n if (ignoredAiTabs.length > 0) {\n warn(\n \"The Runs and Agents tabs are development tabs, so production.panels.ai and production.panels.agents are ignored. Production shows AI totals in Reports, Models and Errors.\",\n );\n }\n\n // The AI report tabs are listed only when the app has the AI feed (Panoptic), unless the project turned one on.\n // With every report tab turned off, no totals are written (and no missing-table warning is logged).\n const aiWiring = shownTabs.some((tab) => AI_REPORT_TABS.includes(tab))\n ? await attachProductionAi(options, warn)\n : {\n feedAvailable: false,\n reports: {\n ...toAiUnavailableView(describeAiUnavailable(\"reports-off\")),\n async dispose() {},\n },\n };\n const builtIn = aiWiring.feedAvailable\n ? shownTabs\n : shownTabs.filter((tab) => !AI_REPORT_TABS.includes(tab) || production.panels[tab] === true);\n\n stops.push(() => aiWiring.reports.dispose());\n\n // The dashboard's own requests are not worth a line in the request log, and its sign-in bodies must not reach it.\n if (typeof core.excludeFromRequestLog === \"function\") {\n stops.push(core.excludeFromRequestLog(production.path));\n }\n\n // Mail previews exist only when the project turned that tab on.\n if (builtIn.includes(\"mail\")) {\n const { attachMailSource } = await import(\"../sources/mail-source\");\n\n stops.push(await attachMailSource(capture.collector));\n }\n\n httpModule.mountProductionDevtools(server, {\n routes: {\n ...input.routes,\n aiReports: aiWiring.reports,\n collector: capture.collector,\n options,\n isDevelopment: () => false,\n },\n production,\n store,\n auth,\n capture,\n insights,\n instance,\n panels,\n builtInPanels: builtIn,\n state,\n warn,\n ...(typeof core.answerUnknownUrl === \"function\"\n ? { answerUnknownUrl: core.answerUnknownUrl }\n : {}),\n hmac: (value) => crypto.hmac(value),\n });\n\n publishMounted(production.path);\n stops.push(clearMounted);\n\n log.info(\n \"devtools\",\n \"ready\",\n `devtools production monitor mounted at ${maskDashboardPath(production.path)} (DEVTOOLS_PATH)`,\n );\n } catch (error) {\n for (const stop of stops.splice(0).reverse()) {\n try {\n void Promise.resolve(stop()).catch(() => undefined);\n } catch {\n // Cleanup after a failed boot must not hide the real error.\n }\n }\n\n void capture.dispose().catch(() => undefined);\n\n throw error;\n }\n\n // Returns the promise of the stops so the connector can wait for the final AI totals flush.\n return () => {\n const finished: Promise<unknown>[] = [];\n\n for (const stop of stops.splice(0).reverse()) {\n try {\n finished.push(Promise.resolve(stop()).catch(() => undefined));\n } catch {\n // Shutdown continues past a failing step.\n }\n }\n\n finished.push(capture.dispose().catch(() => undefined));\n\n return Promise.all(finished).then(() => undefined);\n };\n}\n"],"mappings":";;;;;;;;AAoCA,MAAM,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EAC9B,MAAM,KAAK,YAAY;EAEvB,IAAI,KACF,YACA,SACA,0CAA0C,kBAAkB,WAAW,IAAI,EAAE,iBAC/E;CACF,SAAS,OAAO;EACd,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,AAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS;EACpD,QAAQ,CAER;EAGF,AAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS;EAE5C,MAAM;CACR;CAGA,aAAa;EACX,MAAM,WAA+B,CAAC;EAEtC,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,GACzC,IAAI;GACF,SAAS,KAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,YAAY,MAAS,CAAC;EAC9D,QAAQ,CAER;EAGF,SAAS,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAS,CAAC;EAEtD,OAAO,QAAQ,IAAI,QAAQ,CAAC,CAAC,WAAW,MAAS;CACnD;AACF"}
@@ -52,6 +52,11 @@ export type ResolvedDevtoolsProductionOptions = {
52
52
  explain: {
53
53
  executing: boolean;
54
54
  };
55
+ /**
56
+ * Turn a dashboard tab on or off by id. `ai` (Runs) and `agents` are development
57
+ * tabs: they are ignored in production, with one warning at boot. Production
58
+ * shows AI totals in the Reports, Models and Errors tabs.
59
+ */
55
60
  panels: Readonly<Record<string, boolean>>;
56
61
  logLevels: readonly DevtoolsLogEntry["level"][];
57
62
  auditRetentionDays: number;
@@ -1 +1 @@
1
- {"version":3,"file":"options.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/production/options.ts"],"mappings":";;;;;;YAQY;;EAEV;;EAEA;IAAS;IAAsB;IAAyB;;EACxD;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IAAW;IAAqB;IAAkB;;EAClD;EACA;IAAa;IAAmB;;EAChC;IACE;IACA;IACA;IACA;IACA;;EAEF;IAAW;;EACX,QAAQ,SAAS;EACjB,oBAAoB;EACpB;EACA;IAAY;IAAgB;;;EAE5B;IAAS;IAAkB"}
1
+ {"version":3,"file":"options.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/production/options.ts"],"mappings":";;;;;;YAQY;;EAEV;;EAEA;IAAS;IAAsB;IAAyB;;EACxD;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IAAW;IAAqB;IAAkB;;EAClD;EACA;IAAa;IAAmB;;EAChC;IACE;IACA;IACA;IACA;IACA;;EAEF;IAAW;;;;;;;EAMX,QAAQ,SAAS;EACjB,oBAAoB;EACpB;EACA;IAAY;IAAgB;;;EAE5B;IAAS;IAAkB"}