@warlock.js/devtools 5.59.0 → 5.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/cjs/{app-versions-DfpPZOI2.cjs → app-versions-C_ZyzuvD.cjs} +1 -116
- package/cjs/app-versions-C_ZyzuvD.cjs.map +1 -0
- package/cjs/attach-D5aMqUnA.cjs +1342 -0
- package/cjs/attach-D5aMqUnA.cjs.map +1 -0
- package/cjs/{auth-B3wyjJnQ.cjs → auth-ChHh5E7j.cjs} +6 -6
- package/cjs/{auth-B3wyjJnQ.cjs.map → auth-ChHh5E7j.cjs.map} +1 -1
- package/cjs/{boot-nczSvJ_F.cjs → boot-D0nF-7w3.cjs} +78 -14
- package/cjs/boot-D0nF-7w3.cjs.map +1 -0
- package/cjs/{capture-CuyT8Vab.cjs → capture-D2k0GnBN.cjs} +23 -422
- package/cjs/capture-D2k0GnBN.cjs.map +1 -0
- package/cjs/{cascade-store-CuRRYzt_.cjs → cascade-store-DUT2Laha.cjs} +3 -3
- package/cjs/{cascade-store-CuRRYzt_.cjs.map → cascade-store-DUT2Laha.cjs.map} +1 -1
- package/cjs/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
- package/cjs/collector-BfC4v87v.cjs.map +1 -0
- package/cjs/{current-request-id-CeQhRz9Q.cjs → current-request-id-Badec-TH.cjs} +2 -2
- package/cjs/{current-request-id-CeQhRz9Q.cjs.map → current-request-id-Badec-TH.cjs.map} +1 -1
- package/cjs/{errors-BadbSDX8.cjs → errors-DNQ-g49I.cjs} +198 -1
- package/cjs/errors-DNQ-g49I.cjs.map +1 -0
- package/cjs/extract-8kaX_cUV.cjs +1103 -0
- package/cjs/extract-8kaX_cUV.cjs.map +1 -0
- package/cjs/{http-Biauhqi0.cjs → http-1nnpAoI7.cjs} +33 -10
- package/cjs/http-1nnpAoI7.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-BjJA6Ret.cjs → insights-COA3u37q.cjs} +54 -22
- package/cjs/insights-COA3u37q.cjs.map +1 -0
- package/cjs/migrations-BQdNOL5_.cjs +30 -0
- package/cjs/migrations-BQdNOL5_.cjs.map +1 -0
- package/cjs/{migrations-BP4cYTGo.cjs → models-DF1agAm4.cjs} +106 -24
- package/cjs/models-DF1agAm4.cjs.map +1 -0
- package/cjs/{process-panel-DskSA7Cm.cjs → process-panel-D3D9Y_dc.cjs} +4 -4
- package/cjs/{process-panel-DskSA7Cm.cjs.map → process-panel-D3D9Y_dc.cjs.map} +1 -1
- package/cjs/production/index.cjs +4 -4
- package/cjs/query-shape-DShKQa0x.cjs +45 -0
- package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
- package/cjs/redact-DQ28mDzr.cjs +533 -0
- package/cjs/redact-DQ28mDzr.cjs.map +1 -0
- package/cjs/runs-DECWPGnq.cjs +390 -0
- package/cjs/runs-DECWPGnq.cjs.map +1 -0
- package/cjs/{server-D3XRbSSb.cjs → server-DLT3uPef.cjs} +8 -7
- package/cjs/{server-D3XRbSSb.cjs.map → server-DLT3uPef.cjs.map} +1 -1
- package/cjs/{src-QcNghoYN.cjs → src-BZiSv8A1.cjs} +182 -24
- package/cjs/src-BZiSv8A1.cjs.map +1 -0
- package/cjs/{store-CNFv3wVp.cjs → store-EFn4wp0T.cjs} +2 -2
- package/cjs/{stream-route-BqyAlfxQ.cjs → stream-route-B6WAjbPG.cjs} +111 -22
- package/cjs/stream-route-B6WAjbPG.cjs.map +1 -0
- package/esm/ai/attach.mjs +92 -0
- package/esm/ai/attach.mjs.map +1 -0
- package/esm/ai/options.mjs +31 -0
- package/esm/ai/options.mjs.map +1 -0
- package/esm/ai/reports/aggregate.mjs +330 -0
- package/esm/ai/reports/aggregate.mjs.map +1 -0
- package/esm/ai/reports/evaluate.mjs +108 -0
- package/esm/ai/reports/evaluate.mjs.map +1 -0
- package/esm/ai/reports/range.mjs +121 -0
- package/esm/ai/reports/range.mjs.map +1 -0
- package/esm/ai/reports/runs.d.mts +2 -0
- package/esm/ai/reports/runs.mjs +212 -0
- package/esm/ai/reports/runs.mjs.map +1 -0
- package/esm/ai/reports/service.mjs +132 -0
- package/esm/ai/reports/service.mjs.map +1 -0
- package/esm/ai/rollup/cascade-store.mjs +84 -0
- package/esm/ai/rollup/cascade-store.mjs.map +1 -0
- package/esm/ai/rollup/categories.mjs +67 -0
- package/esm/ai/rollup/categories.mjs.map +1 -0
- package/esm/ai/rollup/extract.mjs +225 -0
- package/esm/ai/rollup/extract.mjs.map +1 -0
- package/esm/ai/rollup/file-store.mjs +147 -0
- package/esm/ai/rollup/file-store.mjs.map +1 -0
- package/esm/ai/rollup/histogram.mjs +42 -0
- package/esm/ai/rollup/histogram.mjs.map +1 -0
- package/esm/ai/rollup/increment-error.mjs +19 -0
- package/esm/ai/rollup/increment-error.mjs.map +1 -0
- package/esm/ai/rollup/index.mjs +9 -0
- package/esm/ai/rollup/mapping.mjs +69 -0
- package/esm/ai/rollup/mapping.mjs.map +1 -0
- package/esm/ai/rollup/memory-store.mjs +26 -0
- package/esm/ai/rollup/memory-store.mjs.map +1 -0
- package/esm/ai/rollup/writer.mjs +113 -0
- package/esm/ai/rollup/writer.mjs.map +1 -0
- package/esm/ai/types.d.mts +29 -0
- package/esm/ai/types.d.mts.map +1 -0
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +58 -3
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/options.mjs +4 -0
- package/esm/options.mjs.map +1 -1
- package/esm/production/boot.mjs +70 -3
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +388 -6
- package/esm/production/contracts.d.mts.map +1 -1
- package/esm/production/contracts.mjs +64 -2
- package/esm/production/contracts.mjs.map +1 -1
- package/esm/production/errors.mjs +8 -0
- package/esm/production/errors.mjs.map +1 -1
- package/esm/production/http/access.mjs +6 -0
- package/esm/production/http/access.mjs.map +1 -1
- package/esm/production/http/mount.mjs +21 -2
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/http/share.mjs.map +1 -1
- package/esm/production/index.d.mts +2 -2
- package/esm/production/insights/jobs.mjs +45 -11
- package/esm/production/insights/jobs.mjs.map +1 -1
- package/esm/production/store/migrations.d.mts +1 -1
- package/esm/production/store/migrations.d.mts.map +1 -1
- package/esm/production/store/migrations.mjs +4 -2
- package/esm/production/store/migrations.mjs.map +1 -1
- package/esm/production/store/models/ai-rollup.migration.mjs +48 -0
- package/esm/production/store/models/ai-rollup.migration.mjs.map +1 -0
- package/esm/production/store/models/ai-rollup.model.mjs +13 -0
- package/esm/production/store/models/ai-rollup.model.mjs.map +1 -0
- package/esm/production/store/models/index.mjs +3 -1
- package/esm/server/ai-report-routes.mjs +72 -0
- package/esm/server/ai-report-routes.mjs.map +1 -0
- package/esm/server/ai-routes.mjs +22 -1
- package/esm/server/ai-routes.mjs.map +1 -1
- package/esm/server/index.mjs +2 -0
- package/esm/server/index.mjs.map +1 -1
- package/esm/server/panel-routes.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +4 -7
- package/esm/server/ui-assets.mjs.map +1 -1
- package/esm/sources/agent-trace-source.d.mts.map +1 -1
- package/esm/sources/agent-trace-source.mjs.map +1 -1
- package/esm/sources/ai-source.d.mts +2 -0
- package/esm/sources/ai-source.d.mts.map +1 -1
- package/esm/sources/ai-source.mjs +58 -17
- package/esm/sources/ai-source.mjs.map +1 -1
- package/esm/types.d.mts +13 -3
- package/esm/types.d.mts.map +1 -1
- package/llms-full.txt +61 -22
- package/package.json +8 -8
- package/skills/SKILL.md +61 -22
- package/ui/dashboard/assets/app.css +1 -1
- package/ui/dashboard/assets/app.js +12 -5
- package/ui/dashboard/build-info.json +7 -7
- package/cjs/ai-source-BdvMfyKw.cjs +0 -448
- package/cjs/ai-source-BdvMfyKw.cjs.map +0 -1
- package/cjs/app-versions-DfpPZOI2.cjs.map +0 -1
- package/cjs/boot-nczSvJ_F.cjs.map +0 -1
- package/cjs/capture-CuyT8Vab.cjs.map +0 -1
- package/cjs/collector-CJbQbzzK.cjs.map +0 -1
- package/cjs/errors-BadbSDX8.cjs.map +0 -1
- package/cjs/histogram-DTOGnNBW.cjs +0 -102
- package/cjs/histogram-DTOGnNBW.cjs.map +0 -1
- package/cjs/http-Biauhqi0.cjs.map +0 -1
- package/cjs/insights-BjJA6Ret.cjs.map +0 -1
- package/cjs/migrations-BP4cYTGo.cjs.map +0 -1
- package/cjs/options-B9FHbRAJ.cjs +0 -205
- package/cjs/options-B9FHbRAJ.cjs.map +0 -1
- package/cjs/panels-D1ITm-jc.cjs +0 -384
- package/cjs/panels-D1ITm-jc.cjs.map +0 -1
- package/cjs/src-QcNghoYN.cjs.map +0 -1
- package/cjs/stream-route-BqyAlfxQ.cjs.map +0 -1
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { addRollupCounters, rollupId, traceToRollupDeltas } from "./extract.mjs";
|
|
2
|
+
import { DevtoolsAiRollupIncrementError } from "./increment-error.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/devtools/src/ai/rollup/writer.ts
|
|
5
|
+
const HOUR_MS = 36e5;
|
|
6
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
7
|
+
const PRUNE_EVERY_MS = 6e5;
|
|
8
|
+
const WARN_EVERY_MS = 6e4;
|
|
9
|
+
const STOP_GRACE_MS = 5e3;
|
|
10
|
+
const DEFAULT_MAX_KEYS = 2e3;
|
|
11
|
+
/**
|
|
12
|
+
* Starts the rollup writer: `record(trace)` adds the trace's deltas to an
|
|
13
|
+
* in-memory map keyed by `rollupId`; every `options.flushIntervalMs` the map
|
|
14
|
+
* is swapped out and written with `store.increment` (a failed write merges
|
|
15
|
+
* the unsaved deltas back for the next try, only those when the store says
|
|
16
|
+
* which, and warns at most once a minute); every
|
|
17
|
+
* 10 minutes it prunes hours older than `options.retentionDays`. Timers are
|
|
18
|
+
* `unref`ed and writes are serialised (never two at once). `stop()` clears
|
|
19
|
+
* the timers and flushes, giving up after 5 seconds.
|
|
20
|
+
*/
|
|
21
|
+
function startAiRollupWriter(input) {
|
|
22
|
+
const { store, totalCost, options } = input;
|
|
23
|
+
const now = input.now ?? Date.now;
|
|
24
|
+
const warn = input.warn ?? ((message) => console.warn(message));
|
|
25
|
+
const maxKeys = input.maxKeys ?? DEFAULT_MAX_KEYS;
|
|
26
|
+
let pending = /* @__PURE__ */ new Map();
|
|
27
|
+
let writing = [];
|
|
28
|
+
let inflight = Promise.resolve();
|
|
29
|
+
let lastWarnAt;
|
|
30
|
+
const warnOnce = (task, error) => {
|
|
31
|
+
const at = now();
|
|
32
|
+
if (lastWarnAt !== void 0 && at - lastWarnAt < WARN_EVERY_MS) return;
|
|
33
|
+
lastWarnAt = at;
|
|
34
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
35
|
+
warn(`Devtools could not ${task}: ${reason}. It will try again.`);
|
|
36
|
+
};
|
|
37
|
+
/** Adds a delta, folding a new key into agent `(other)` once `maxKeys` is reached. */
|
|
38
|
+
const add = (delta) => {
|
|
39
|
+
let id = rollupId(delta);
|
|
40
|
+
let target = pending.get(id);
|
|
41
|
+
let source = delta;
|
|
42
|
+
if (!target && pending.size >= maxKeys) {
|
|
43
|
+
source = {
|
|
44
|
+
...structuredClone(delta),
|
|
45
|
+
agent: "(other)"
|
|
46
|
+
};
|
|
47
|
+
id = rollupId(source);
|
|
48
|
+
target = pending.get(id);
|
|
49
|
+
}
|
|
50
|
+
if (target) addRollupCounters(target, source);
|
|
51
|
+
else pending.set(id, structuredClone(source));
|
|
52
|
+
};
|
|
53
|
+
const writeNow = async () => {
|
|
54
|
+
if (pending.size === 0) return;
|
|
55
|
+
const batch = [...pending.values()];
|
|
56
|
+
pending = /* @__PURE__ */ new Map();
|
|
57
|
+
writing = batch;
|
|
58
|
+
try {
|
|
59
|
+
await store.increment(batch);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const unsaved = error instanceof DevtoolsAiRollupIncrementError ? error.unwritten : batch;
|
|
62
|
+
for (const delta of unsaved) add(delta);
|
|
63
|
+
warnOnce("save AI totals", error);
|
|
64
|
+
} finally {
|
|
65
|
+
writing = [];
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const flush = () => {
|
|
69
|
+
inflight = inflight.then(writeNow);
|
|
70
|
+
return inflight;
|
|
71
|
+
};
|
|
72
|
+
const prune = async () => {
|
|
73
|
+
try {
|
|
74
|
+
const cutoff = Math.floor(now() / HOUR_MS) * HOUR_MS - options.retentionDays * DAY_MS;
|
|
75
|
+
await store.prune(cutoff);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
warnOnce("remove old AI totals", error);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
const flushTimer = setInterval(() => void flush(), options.flushIntervalMs);
|
|
81
|
+
const pruneTimer = setInterval(() => void prune(), PRUNE_EVERY_MS);
|
|
82
|
+
flushTimer.unref();
|
|
83
|
+
pruneTimer.unref();
|
|
84
|
+
return {
|
|
85
|
+
record(trace) {
|
|
86
|
+
try {
|
|
87
|
+
for (const delta of traceToRollupDeltas(trace, totalCost)) add(delta);
|
|
88
|
+
} catch {}
|
|
89
|
+
},
|
|
90
|
+
pending() {
|
|
91
|
+
return [...writing, ...pending.values()].map((delta) => structuredClone(delta));
|
|
92
|
+
},
|
|
93
|
+
flush,
|
|
94
|
+
async stop() {
|
|
95
|
+
clearInterval(flushTimer);
|
|
96
|
+
clearInterval(pruneTimer);
|
|
97
|
+
let timer;
|
|
98
|
+
const giveUp = new Promise((resolve) => {
|
|
99
|
+
timer = setTimeout(resolve, STOP_GRACE_MS);
|
|
100
|
+
timer.unref();
|
|
101
|
+
});
|
|
102
|
+
try {
|
|
103
|
+
await Promise.race([flush(), giveUp]);
|
|
104
|
+
} finally {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
//#endregion
|
|
112
|
+
export { startAiRollupWriter };
|
|
113
|
+
//# sourceMappingURL=writer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"writer.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/ai/rollup/writer.ts"],"sourcesContent":["import type {\n DevtoolsAiRollupDelta,\n DevtoolsAiRollupWriter,\n DevtoolsAiRollupWriterInput,\n} from \"../types\";\nimport { addRollupCounters, rollupId, traceToRollupDeltas } from \"./extract\";\nimport { DevtoolsAiRollupIncrementError } from \"./increment-error\";\n\nconst HOUR_MS = 3_600_000;\nconst DAY_MS = 24 * HOUR_MS;\nconst PRUNE_EVERY_MS = 10 * 60_000;\nconst WARN_EVERY_MS = 60_000;\nconst STOP_GRACE_MS = 5000;\nconst DEFAULT_MAX_KEYS = 2000;\n\n/**\n * Starts the rollup writer: `record(trace)` adds the trace's deltas to an\n * in-memory map keyed by `rollupId`; every `options.flushIntervalMs` the map\n * is swapped out and written with `store.increment` (a failed write merges\n * the unsaved deltas back for the next try, only those when the store says\n * which, and warns at most once a minute); every\n * 10 minutes it prunes hours older than `options.retentionDays`. Timers are\n * `unref`ed and writes are serialised (never two at once). `stop()` clears\n * the timers and flushes, giving up after 5 seconds.\n */\nexport function startAiRollupWriter(input: DevtoolsAiRollupWriterInput): DevtoolsAiRollupWriter {\n const { store, totalCost, options } = input;\n const now = input.now ?? Date.now;\n const warn = input.warn ?? ((message: string) => console.warn(message));\n const maxKeys = input.maxKeys ?? DEFAULT_MAX_KEYS;\n\n let pending = new Map<string, DevtoolsAiRollupDelta>();\n // The batch being written: still shown by `pending()` until the write settles, so reports never dip.\n let writing: readonly DevtoolsAiRollupDelta[] = [];\n let inflight: Promise<void> = Promise.resolve();\n let lastWarnAt: number | undefined;\n\n const warnOnce = (task: string, error: unknown): void => {\n const at = now();\n\n if (lastWarnAt !== undefined && at - lastWarnAt < WARN_EVERY_MS) return;\n\n lastWarnAt = at;\n\n const reason = error instanceof Error ? error.message : String(error);\n\n warn(`Devtools could not ${task}: ${reason}. It will try again.`);\n };\n\n /** Adds a delta, folding a new key into agent `(other)` once `maxKeys` is reached. */\n const add = (delta: DevtoolsAiRollupDelta): void => {\n let id = rollupId(delta);\n let target = pending.get(id);\n let source = delta;\n\n if (!target && pending.size >= maxKeys) {\n source = { ...structuredClone(delta), agent: \"(other)\" };\n id = rollupId(source);\n target = pending.get(id);\n }\n\n if (target) {\n addRollupCounters(target, source);\n } else {\n pending.set(id, structuredClone(source));\n }\n };\n\n const writeNow = async (): Promise<void> => {\n if (pending.size === 0) return;\n\n const batch = [...pending.values()];\n\n pending = new Map();\n writing = batch;\n\n try {\n await store.increment(batch);\n } catch (error) {\n // Only what was not saved goes back: a partly saved batch must never be added twice.\n const unsaved = error instanceof DevtoolsAiRollupIncrementError ? error.unwritten : batch;\n\n for (const delta of unsaved) add(delta);\n\n warnOnce(\"save AI totals\", error);\n } finally {\n writing = [];\n }\n };\n\n const flush = (): Promise<void> => {\n inflight = inflight.then(writeNow);\n\n return inflight;\n };\n\n const prune = async (): Promise<void> => {\n try {\n const cutoff = Math.floor(now() / HOUR_MS) * HOUR_MS - options.retentionDays * DAY_MS;\n\n await store.prune(cutoff);\n } catch (error) {\n warnOnce(\"remove old AI totals\", error);\n }\n };\n\n const flushTimer = setInterval(() => void flush(), options.flushIntervalMs);\n const pruneTimer = setInterval(() => void prune(), PRUNE_EVERY_MS);\n\n flushTimer.unref();\n pruneTimer.unref();\n\n return {\n record(trace) {\n try {\n for (const delta of traceToRollupDeltas(trace, totalCost)) add(delta);\n } catch {\n // A trace that cannot be summarised must never reach the trace publisher.\n }\n },\n pending() {\n return [...writing, ...pending.values()].map((delta) => structuredClone(delta));\n },\n flush,\n async stop() {\n clearInterval(flushTimer);\n clearInterval(pruneTimer);\n\n let timer: NodeJS.Timeout | undefined;\n const giveUp = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, STOP_GRACE_MS);\n timer.unref();\n });\n\n try {\n await Promise.race([flush(), giveUp]);\n } finally {\n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src/ai/types.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Server-side types of the AI section: the hourly rollups, their stores and
|
|
5
|
+
* writer, and the options. The JSON the routes answer with lives in
|
|
6
|
+
* `production/contracts.ts` (the dashboard imports it).
|
|
7
|
+
*/
|
|
8
|
+
/** `devtools.ai` in `src/config/devtools.ts`. */
|
|
9
|
+
export type DevtoolsAiOptions = {
|
|
10
|
+
/**
|
|
11
|
+
* Keep hourly AI totals (runs, tokens, estimated cost, errors, latency) for
|
|
12
|
+
* the Reports, Models and Errors pages.
|
|
13
|
+
* @default true
|
|
14
|
+
*/
|
|
15
|
+
reports?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Days of hourly totals kept; older hours are removed every 10 minutes.
|
|
18
|
+
* A whole number from 1 to 400.
|
|
19
|
+
* @default 30 in development, 90 in production
|
|
20
|
+
*/
|
|
21
|
+
retentionDays?: number;
|
|
22
|
+
/**
|
|
23
|
+
* How often totals not yet saved are written, in ms. At least 5000.
|
|
24
|
+
* @default 60000
|
|
25
|
+
*/
|
|
26
|
+
flushIntervalMs?: number;
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
//# sourceMappingURL=types.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/ai/types.ts"],"mappings":";;;;;;;;YAUY;;;;;;EAMV;;;;;;EAMA;;;;;EAKA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devtools-connector.d.mts","names":[],"sources":["../../../../../../../packages/devtools/src/devtools-connector.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"devtools-connector.d.mts","names":[],"sources":["../../../../../../../packages/devtools/src/devtools-connector.ts"],"mappings":";;;;YAuDY,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;wBAwBvB,kBAAkB,UAAS,2BAAgC"}
|
|
@@ -2,10 +2,14 @@ import { createPanelErrorSource } from "./panel-errors.mjs";
|
|
|
2
2
|
import { checkDevtoolsPanels, loadDevtoolsPanels } from "./panels.mjs";
|
|
3
3
|
import { loadProcessPanel, processesDevtoolsPanel } from "./process-panel.mjs";
|
|
4
4
|
import { createCollector } from "./collector.mjs";
|
|
5
|
+
import { resolveDevtoolsAiOptions } from "./ai/options.mjs";
|
|
5
6
|
import { resolveDevtoolsOptions } from "./options.mjs";
|
|
6
7
|
import { DEVTOOLS_PRODUCTION_DEFAULTS } from "./production/options.mjs";
|
|
7
8
|
import { attachAgentTraceSource } from "./sources/agent-trace-source.mjs";
|
|
8
|
-
import { attachAiSource } from "./sources/ai-source.mjs";
|
|
9
|
+
import { attachAiSource, describeAiUnavailable, toAiUnavailableView } from "./sources/ai-source.mjs";
|
|
10
|
+
import { DEVTOOLS_MOUNTED_KEY, attachAiReports, loadAiFeed } from "./ai/attach.mjs";
|
|
11
|
+
import { createAiEvaluator } from "./ai/reports/evaluate.mjs";
|
|
12
|
+
import { recentAiFailures } from "./ai/reports/runs.mjs";
|
|
9
13
|
import { attachCacheSource } from "./sources/cache-source.mjs";
|
|
10
14
|
import { attachLogSource } from "./sources/log-source.mjs";
|
|
11
15
|
import { attachMailSource } from "./sources/mail-source.mjs";
|
|
@@ -19,6 +23,8 @@ import { attachTracingSource } from "./sources/tracing-source.mjs";
|
|
|
19
23
|
* that depends on it, so it simply goes last.
|
|
20
24
|
*/
|
|
21
25
|
const DEVTOOLS_CONNECTOR_PRIORITY = 12;
|
|
26
|
+
/** The slot core reads to turn query events on; see `resolveDatabaseConnectionConfig`. */
|
|
27
|
+
const DEVTOOLS_PRODUCTION_REQUESTED = Symbol.for("@warlock.js/devtools.productionRequested");
|
|
22
28
|
/**
|
|
23
29
|
* The app's `src/config/devtools.ts`, or `{}` when there is none (or the
|
|
24
30
|
* config store cannot be read, which must never stop the dev server).
|
|
@@ -54,6 +60,7 @@ function readConfiguredOptions(readConfig) {
|
|
|
54
60
|
* import of this package); options passed here win over it.
|
|
55
61
|
*/
|
|
56
62
|
function devtoolsConnector(options = {}) {
|
|
63
|
+
if (options.production?.enabled === true) globalThis[DEVTOOLS_PRODUCTION_REQUESTED] = true;
|
|
57
64
|
let active = false;
|
|
58
65
|
const disposers = [];
|
|
59
66
|
const connector = {
|
|
@@ -88,6 +95,11 @@ function devtoolsConnector(options = {}) {
|
|
|
88
95
|
disposers.push(ai.dispose);
|
|
89
96
|
const agentTraces = await attachAgentTraceSource();
|
|
90
97
|
disposers.push(agentTraces.dispose);
|
|
98
|
+
const aiWiring = await wireDevelopmentAiReports(ai, resolved, core, log, disposers);
|
|
99
|
+
const aiEvaluator = createAiEvaluator({
|
|
100
|
+
agentTraces,
|
|
101
|
+
warn: (message) => log.warn("devtools", "evaluate", message)
|
|
102
|
+
});
|
|
91
103
|
const { mountDevtoolsRoutes } = await import("./server/index.mjs");
|
|
92
104
|
const postmanBuilder = await findPostmanBuilder();
|
|
93
105
|
const requestLog = await findRequestLogSource();
|
|
@@ -106,6 +118,8 @@ function devtoolsConnector(options = {}) {
|
|
|
106
118
|
collector,
|
|
107
119
|
ai,
|
|
108
120
|
agentTraces,
|
|
121
|
+
aiReports: aiWiring,
|
|
122
|
+
aiEvaluator,
|
|
109
123
|
...processPanel ? { processPanel } : {},
|
|
110
124
|
panels,
|
|
111
125
|
options: resolved,
|
|
@@ -125,6 +139,13 @@ function devtoolsConnector(options = {}) {
|
|
|
125
139
|
log.warn("devtools", "n+1", `${warning.message}${where} (${event.data.method} ${event.data.path})`);
|
|
126
140
|
}
|
|
127
141
|
}));
|
|
142
|
+
globalThis[DEVTOOLS_MOUNTED_KEY] = {
|
|
143
|
+
path: resolved.path,
|
|
144
|
+
mode: "development"
|
|
145
|
+
};
|
|
146
|
+
disposers.push(() => {
|
|
147
|
+
delete globalThis[DEVTOOLS_MOUNTED_KEY];
|
|
148
|
+
});
|
|
128
149
|
active = true;
|
|
129
150
|
log.info("devtools", "ready", `devtools ready at ${resolved.path}`);
|
|
130
151
|
},
|
|
@@ -134,7 +155,11 @@ function devtoolsConnector(options = {}) {
|
|
|
134
155
|
await connector.start();
|
|
135
156
|
},
|
|
136
157
|
async shutdown() {
|
|
137
|
-
|
|
158
|
+
const finished = [];
|
|
159
|
+
for (const dispose of disposers.splice(0)) try {
|
|
160
|
+
finished.push(Promise.resolve(dispose()).catch(() => void 0));
|
|
161
|
+
} catch {}
|
|
162
|
+
await Promise.all(finished);
|
|
138
163
|
active = false;
|
|
139
164
|
},
|
|
140
165
|
shouldRestart: () => false
|
|
@@ -215,6 +240,36 @@ async function wireDevelopmentInsights(collector, resolved, log, disposers) {
|
|
|
215
240
|
}
|
|
216
241
|
}
|
|
217
242
|
/**
|
|
243
|
+
* Starts this process's AI totals in development: loads the Panoptic feed and
|
|
244
|
+
* writes hourly rollups to `storage/devtools/ai-rollups`. Never throws; a
|
|
245
|
+
* failure leaves the Reports, Models and Errors pages answering why.
|
|
246
|
+
*/
|
|
247
|
+
async function wireDevelopmentAiReports(ai, resolved, core, log, disposers) {
|
|
248
|
+
const none = (reason) => ({
|
|
249
|
+
...toAiUnavailableView(describeAiUnavailable(reason)),
|
|
250
|
+
async dispose() {}
|
|
251
|
+
});
|
|
252
|
+
try {
|
|
253
|
+
const loaded = await loadAiFeed();
|
|
254
|
+
if ("unavailable" in loaded) return {
|
|
255
|
+
...loaded.unavailable,
|
|
256
|
+
async dispose() {}
|
|
257
|
+
};
|
|
258
|
+
const reports = await attachAiReports({
|
|
259
|
+
feed: loaded.feed,
|
|
260
|
+
options: resolveDevtoolsAiOptions(resolved.ai, "development"),
|
|
261
|
+
...typeof core.storagePath === "function" ? { directory: core.storagePath("devtools/ai-rollups") } : {},
|
|
262
|
+
recentFailures: (filter) => ai.available ? recentAiFailures(ai.store.query(), 50, filter) : [],
|
|
263
|
+
warn: (message) => log.warn("devtools", "ai-reports", message)
|
|
264
|
+
});
|
|
265
|
+
disposers.push(() => reports.dispose());
|
|
266
|
+
return reports;
|
|
267
|
+
} catch (error) {
|
|
268
|
+
log.warn("devtools", "ai-reports", `AI reports could not start: ${error instanceof Error ? error.message : String(error)}`);
|
|
269
|
+
return none("reports-off");
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
218
273
|
* Starts the production monitor: loads the panels in production mode and
|
|
219
274
|
* hands everything to `bootProductionDevtools`, which refuses to boot (throws
|
|
220
275
|
* `DevtoolsProductionConfigError`) when the configuration is incomplete.
|
|
@@ -319,5 +374,5 @@ function unwrapCollection(result) {
|
|
|
319
374
|
}
|
|
320
375
|
|
|
321
376
|
//#endregion
|
|
322
|
-
export { devtoolsConnector };
|
|
377
|
+
export { DEVTOOLS_PRODUCTION_REQUESTED, devtoolsConnector };
|
|
323
378
|
//# sourceMappingURL=devtools-connector.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devtools-connector.mjs","names":[],"sources":["../../../../../../../packages/devtools/src/devtools-connector.ts"],"sourcesContent":["/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createPanelErrorSource } from \"./panel-errors\";\nimport { checkDevtoolsPanels, loadDevtoolsPanels } from \"./panels\";\nimport { loadProcessPanel, processesDevtoolsPanel } from \"./process-panel\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport { DEVTOOLS_PRODUCTION_DEFAULTS } from \"./production/options\";\nimport type { DevtoolsRequestLogSource, DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./server\";\nimport { attachAgentTraceSource } from \"./sources/agent-trace-source\";\nimport { attachAiSource } from \"./sources/ai-source\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/**\n * The app's `src/config/devtools.ts`, or `{}` when there is none (or the\n * config store cannot be read, which must never stop the dev server).\n */\nfunction readConfiguredOptions(readConfig: () => { get(name: string): unknown }): DevtoolsOptions {\n try {\n const value = readConfig().get(\"devtools\");\n\n return value !== null && typeof value === \"object\" ? (value as DevtoolsOptions) : {};\n } catch {\n return {};\n }\n}\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Outside development, `boot()` checks `Application.runtimeStrategy` and\n * `devtools.production.enabled`: unless both say production, it logs one\n * warning and returns without mounting a route or subscribing to anything.\n * With `enabled: true` in production it starts the signed-in production\n * monitor (`bootProductionDevtools`), which refuses to boot when its\n * configuration is incomplete. In development it attaches every source\n * (tracing, queries, cache, mail, logs), loads the panels listed in the\n * `panels` option, then mounts the dashboard's routes on the HTTP server —\n * before it starts listening, the only point in the boot sequence where\n * mounting is possible (see `queue/src/dashboard-boot.ts` for the same\n * constraint).\n *\n * In development apps don't call this: `warlock dev` registers it\n * automatically when the package is installed (`warlock add devtools`). To\n * run the production monitor, list `devtoolsConnector()` in\n * `warlock.config.ts > connectors` (and keep the package in `dependencies`).\n * Options come from the app's `src/config/devtools.ts` (a plain object, no\n * import of this package); options passed here win over it.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const core = await import(\"@warlock.js/core\");\n const { Application, getHttpServer } = core;\n const { log } = await import(\"@warlock.js/logger\");\n\n const resolved = resolveDevtoolsOptions({\n ...readConfiguredOptions(() => core.config),\n ...options,\n });\n\n if (Application.runtimeStrategy === \"production\" && resolved.production?.enabled === true) {\n disposers.push(await bootProduction(core, log, resolved));\n active = true;\n\n return;\n }\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development unless devtools.production.enabled is true; it is not mounted\",\n );\n return;\n }\n\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const ai = await attachAiSource(resolved.maxRequests);\n disposers.push(ai.dispose);\n\n const agentTraces = await attachAgentTraceSource();\n disposers.push(agentTraces.dispose);\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n const requestLog = await findRequestLogSource();\n const processPanel = await loadProcessPanel();\n const builtIn = processesDevtoolsPanel(processPanel);\n // A panel that fails to load or reuses an id is reported and left out;\n // it never stops the dashboard or the app.\n const panelErrors = createPanelErrorSource();\n const panels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n errors: panelErrors.read,\n });\n\n const insightsWiring = await wireDevelopmentInsights(collector, resolved, log, disposers);\n\n panelErrors.bind(insightsWiring.insights ?? null);\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n ai,\n agentTraces,\n ...(processPanel ? { processPanel } : {}),\n panels,\n options: resolved,\n ...insightsWiring,\n requestLog,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n warn: (message) => log.warn(\"devtools\", \"refused\", message),\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n getPostmanCollection: postmanBuilder\n ? async () => unwrapCollection(await postmanBuilder())\n : undefined,\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n for (const dispose of disposers.splice(0)) dispose();\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\ntype ConnectorLogger = {\n info: (module: string, action: string, message: string) => unknown;\n warn: (module: string, action: string, message: string) => unknown;\n error: (module: string, action: string, message: string) => unknown;\n};\n\n/**\n * Development: the statistics, resources, health and jobs behind the\n * Resources, Queries (statistics), Routes (statistics), Errors, Health and\n * Jobs tabs. Wrapped as a whole: when anything fails to start, one line is\n * logged and the dashboard mounts without insights (those tabs then say they\n * are not available). It never stops the dashboard.\n */\nasync function wireDevelopmentInsights(\n collector: ReturnType<typeof createCollector>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<Pick<MountDevtoolsRoutesDeps, \"instance\" | \"insights\" | \"explainShape\">> {\n const stops: DevtoolsDisposer[] = [];\n\n try {\n const capture = await import(\"./production/capture\");\n const insights = await import(\"./production/insights\");\n const instance = insights.createInstanceInfo();\n const queries = capture.createQueryStats({\n maxShapes: DEVTOOLS_PRODUCTION_DEFAULTS.maxShapes,\n instance: instance.id,\n });\n const routes = capture.createRouteStats({\n maxRoutes: DEVTOOLS_PRODUCTION_DEFAULTS.maxRoutes,\n instance: instance.id,\n });\n const errors = capture.createErrorGroups({\n maxGroups: DEVTOOLS_PRODUCTION_DEFAULTS.maxErrorGroups,\n });\n const logs = capture.createRecentLogs({ maxEntries: 200 });\n\n stops.push(\n capture.attachDevelopmentStats(collector, {\n queries,\n routes,\n errors,\n logs,\n nPlusOneThreshold: resolved.nPlusOneThreshold,\n }),\n );\n\n const resources = insights.createResourceMonitor();\n const health = insights.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insights.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insights.createJobsReader(),\n queries,\n routes,\n errors,\n logs,\n counters: null,\n });\n const explainShape = capture.createShapeExplainer({\n queries,\n executing: false,\n instance: instance.id,\n });\n\n disposers.push(...stops);\n\n return { instance, insights: insights.createLocalInsights(reporter), explainShape };\n } catch (error) {\n for (const stop of stops) {\n try {\n stop();\n } catch {\n // Cleanup after a failed start must not hide the reason.\n }\n }\n\n log.warn(\n \"devtools\",\n \"insights-failed\",\n `devtools' statistics could not start, so the Resources, Queries, Routes, Errors, Health and Jobs tabs are not available: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return {};\n }\n}\n\n/**\n * Starts the production monitor: loads the panels in production mode and\n * hands everything to `bootProductionDevtools`, which refuses to boot (throws\n * `DevtoolsProductionConfigError`) when the configuration is incomplete.\n */\nasync function bootProduction(\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n): Promise<DevtoolsDisposer> {\n const { bootProductionDevtools } = await import(\"./production/boot\");\n const requestLog = await findRequestLogSource();\n // The Processes panel reads an app file; load it only when the project turned that tab on.\n const processPanel =\n resolved.production?.panels?.processes === true ? await loadProcessPanel() : undefined;\n const builtIn = processesDevtoolsPanel(processPanel);\n const panelErrors = createPanelErrorSource();\n const packagePanels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n mode: \"production\",\n errors: panelErrors.read,\n });\n // `warlock start` registers no development OpenAPI provider: the API tab, when turned on, builds its own.\n const { createProductionOpenApi } = await import(\"./production/openapi\");\n const openApi = createProductionOpenApi(core);\n\n return bootProductionDevtools({\n options: resolved,\n env: process.env,\n server: core.getHttpServer(),\n panels: [...checkDevtoolsPanels([builtIn]), ...packagePanels],\n routes: {\n ...(processPanel ? { processPanel } : {}),\n ...(requestLog ? { requestLog } : {}),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: openApi.getOpenApiDocument,\n getPostmanCollection: openApi.getPostmanCollection,\n },\n log,\n onInsights: (insights) => panelErrors.bind(insights),\n });\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n\ntype PostmanBuilder = () => Promise<unknown>;\n\n/**\n * Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.\n * Older cores do not export it; the route then answers 503. The lookup is\n * guarded because a namespace without the export may throw on access. Core is\n * imported lazily, like the OpenAPI document above.\n */\nasync function findPostmanBuilder(): Promise<PostmanBuilder | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const build = core.getDevelopmentPostmanCollection;\n\n return typeof build === \"function\" ? (build as PostmanBuilder) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Looks up core's persistent request log reader. Older cores do not export\n * it; the dashboard then shows the in-memory requests only. Core is imported\n * lazily, like the builders above.\n */\nasync function findRequestLogSource(): Promise<DevtoolsRequestLogSource | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const { listRequestLogs, getRequestLog, requestLogToCurl, compileRequestLogFilter } = core;\n\n if (\n typeof listRequestLogs !== \"function\" ||\n typeof getRequestLog !== \"function\" ||\n typeof requestLogToCurl !== \"function\" ||\n typeof compileRequestLogFilter !== \"function\"\n ) {\n return undefined;\n }\n\n return {\n list: (filter) => listRequestLogs(filter),\n get: (id) => getRequestLog(id),\n curl: (record, baseUrl) => requestLogToCurl(record, baseUrl),\n compile: (filter) => compileRequestLogFilter(filter),\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Core may return the collection itself or wrap it in `{ collection, warnings }`,\n * like the OpenAPI generator's `{ document, warnings }`.\n */\nfunction unwrapCollection(result: unknown): object {\n if (result && typeof result === \"object\" && \"collection\" in result) {\n return (result as { collection: object }).collection;\n }\n\n return result as object;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,8BAA8B;;;;;AAM3C,SAAS,sBAAsB,YAAmE;CAChG,IAAI;EACF,MAAM,QAAQ,WAAW,CAAC,CAAC,IAAI,UAAU;EAEzC,OAAO,UAAU,QAAQ,OAAO,UAAU,WAAY,QAA4B,CAAC;CACrF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,kBAAkB,UAAoC,CAAC,GAAc;CACnF,IAAI,SAAS;CACb,MAAM,YAAgC,CAAC;CAEvC,MAAM,YAAuB;EAC3B,MAAM;EACN;EAGA,gBAAgB;EAChB,gBAAgB;EAChB,MAAM,OAAO;GACX,MAAM,OAAO,MAAM,OAAO;GAC1B,MAAM,EAAE,aAAa,kBAAkB;GACvC,MAAM,EAAE,QAAQ,MAAM,OAAO;GAE7B,MAAM,WAAW,uBAAuB;IACtC,GAAG,4BAA4B,KAAK,MAAM;IAC1C,GAAG;GACL,CAAC;GAED,IAAI,YAAY,oBAAoB,gBAAgB,SAAS,YAAY,YAAY,MAAM;IACzF,UAAU,KAAK,MAAM,eAAe,MAAM,KAAK,QAAQ,CAAC;IACxD,SAAS;IAET;GACF;GAEA,IAAI,YAAY,oBAAoB,eAAe;IACjD,IAAI,KACF,YACA,YACA,6GACF;IACA;GACF;GAEA,MAAM,YAAY,gBAAgB,QAAQ;GAE1C,MAAM,aAAa,KAAK,iBAAiB,oBAAoB,WAAW,QAAQ,CAAC;GACjF,MAAM,aAAa,KAAK,eAAe,kBAAkB,SAAS,CAAC;GACnE,MAAM,aAAa,KAAK,eAAe,kBAAkB,SAAS,CAAC;GACnE,MAAM,aAAa,KAAK,cAAc,iBAAiB,SAAS,CAAC;GACjE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4BAA4B,MAD1C,OAAO;EAGnD,IACE,OAAO,oBAAoB,cAC3B,OAAO,kBAAkB,cACzB,OAAO,qBAAqB,cAC5B,OAAO,4BAA4B,YAEnC;EAGF,OAAO;GACL,OAAO,WAAW,gBAAgB,MAAM;GACxC,MAAM,OAAO,cAAc,EAAE;GAC7B,OAAO,QAAQ,YAAY,iBAAiB,QAAQ,OAAO;GAC3D,UAAU,WAAW,wBAAwB,MAAM;EACrD;CACF,QAAQ;EACN;CACF;AACF;;;;;AAMA,SAAS,iBAAiB,QAAyB;CACjD,IAAI,UAAU,OAAO,WAAW,YAAY,gBAAgB,QAC1D,OAAQ,OAAkC;CAG5C,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"devtools-connector.mjs","names":[],"sources":["../../../../../../../packages/devtools/src/devtools-connector.ts"],"sourcesContent":["/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createPanelErrorSource } from \"./panel-errors\";\nimport { checkDevtoolsPanels, loadDevtoolsPanels } from \"./panels\";\nimport { loadProcessPanel, processesDevtoolsPanel } from \"./process-panel\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport { DEVTOOLS_PRODUCTION_DEFAULTS } from \"./production/options\";\nimport type { DevtoolsRequestLogSource, DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./server\";\nimport { attachAgentTraceSource } from \"./sources/agent-trace-source\";\nimport { attachAiReports, DEVTOOLS_MOUNTED_KEY, loadAiFeed } from \"./ai/attach\";\nimport { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport { createAiEvaluator } from \"./ai/reports/evaluate\";\nimport { recentAiFailures } from \"./ai/reports/runs\";\nimport { attachAiSource, describeAiUnavailable, toAiUnavailableView } from \"./sources/ai-source\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/** The slot core reads to turn query events on; see `resolveDatabaseConnectionConfig`. */\nexport const DEVTOOLS_PRODUCTION_REQUESTED = Symbol.for(\"@warlock.js/devtools.productionRequested\");\n\n/**\n * The app's `src/config/devtools.ts`, or `{}` when there is none (or the\n * config store cannot be read, which must never stop the dev server).\n */\nfunction readConfiguredOptions(readConfig: () => { get(name: string): unknown }): DevtoolsOptions {\n try {\n const value = readConfig().get(\"devtools\");\n\n return value !== null && typeof value === \"object\" ? (value as DevtoolsOptions) : {};\n } catch {\n return {};\n }\n}\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Outside development, `boot()` checks `Application.runtimeStrategy` and\n * `devtools.production.enabled`: unless both say production, it logs one\n * warning and returns without mounting a route or subscribing to anything.\n * With `enabled: true` in production it starts the signed-in production\n * monitor (`bootProductionDevtools`), which refuses to boot when its\n * configuration is incomplete. In development it attaches every source\n * (tracing, queries, cache, mail, logs), loads the panels listed in the\n * `panels` option, then mounts the dashboard's routes on the HTTP server —\n * before it starts listening, the only point in the boot sequence where\n * mounting is possible (see `queue/src/dashboard-boot.ts` for the same\n * constraint).\n *\n * In development apps don't call this: `warlock dev` registers it\n * automatically when the package is installed (`warlock add devtools`). To\n * run the production monitor, list `devtoolsConnector()` in\n * `warlock.config.ts > connectors` (and keep the package in `dependencies`).\n * Options come from the app's `src/config/devtools.ts` (a plain object, no\n * import of this package); options passed here win over it.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n // Core reads this slot when it connects the database, so the monitor's\n // Queries tab gets query events without `devtools.production.enabled` in config.\n if (options.production?.enabled === true) {\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_PRODUCTION_REQUESTED] = true;\n }\n\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const core = await import(\"@warlock.js/core\");\n const { Application, getHttpServer } = core;\n const { log } = await import(\"@warlock.js/logger\");\n\n const resolved = resolveDevtoolsOptions({\n ...readConfiguredOptions(() => core.config),\n ...options,\n });\n\n if (Application.runtimeStrategy === \"production\" && resolved.production?.enabled === true) {\n disposers.push(await bootProduction(core, log, resolved));\n active = true;\n\n return;\n }\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development unless devtools.production.enabled is true; it is not mounted\",\n );\n return;\n }\n\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const ai = await attachAiSource(resolved.maxRequests);\n disposers.push(ai.dispose);\n\n const agentTraces = await attachAgentTraceSource();\n disposers.push(agentTraces.dispose);\n\n const aiWiring = await wireDevelopmentAiReports(ai, resolved, core, log, disposers);\n const aiEvaluator = createAiEvaluator({\n agentTraces,\n warn: (message) => log.warn(\"devtools\", \"evaluate\", message),\n });\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n const requestLog = await findRequestLogSource();\n const processPanel = await loadProcessPanel();\n const builtIn = processesDevtoolsPanel(processPanel);\n // A panel that fails to load or reuses an id is reported and left out;\n // it never stops the dashboard or the app.\n const panelErrors = createPanelErrorSource();\n const panels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n errors: panelErrors.read,\n });\n\n const insightsWiring = await wireDevelopmentInsights(collector, resolved, log, disposers);\n\n panelErrors.bind(insightsWiring.insights ?? null);\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n ai,\n agentTraces,\n aiReports: aiWiring,\n aiEvaluator,\n ...(processPanel ? { processPanel } : {}),\n panels,\n options: resolved,\n ...insightsWiring,\n requestLog,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n warn: (message) => log.warn(\"devtools\", \"refused\", message),\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n getPostmanCollection: postmanBuilder\n ? async () => unwrapCollection(await postmanBuilder())\n : undefined,\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY] = {\n path: resolved.path,\n mode: \"development\",\n };\n disposers.push(() => {\n delete (globalThis as Record<symbol, unknown>)[DEVTOOLS_MOUNTED_KEY];\n });\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n // A disposer may return a promise (the AI totals' final flush): wait for it, never let one fail the rest.\n const finished: Promise<unknown>[] = [];\n\n for (const dispose of disposers.splice(0)) {\n try {\n finished.push(Promise.resolve(dispose()).catch(() => undefined));\n } catch {\n // The remaining disposers still run.\n }\n }\n\n await Promise.all(finished);\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\ntype ConnectorLogger = {\n info: (module: string, action: string, message: string) => unknown;\n warn: (module: string, action: string, message: string) => unknown;\n error: (module: string, action: string, message: string) => unknown;\n};\n\n/**\n * Development: the statistics, resources, health and jobs behind the\n * Resources, Queries (statistics), Routes (statistics), Errors, Health and\n * Jobs tabs. Wrapped as a whole: when anything fails to start, one line is\n * logged and the dashboard mounts without insights (those tabs then say they\n * are not available). It never stops the dashboard.\n */\nasync function wireDevelopmentInsights(\n collector: ReturnType<typeof createCollector>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<Pick<MountDevtoolsRoutesDeps, \"instance\" | \"insights\" | \"explainShape\">> {\n const stops: DevtoolsDisposer[] = [];\n\n try {\n const capture = await import(\"./production/capture\");\n const insights = await import(\"./production/insights\");\n const instance = insights.createInstanceInfo();\n const queries = capture.createQueryStats({\n maxShapes: DEVTOOLS_PRODUCTION_DEFAULTS.maxShapes,\n instance: instance.id,\n });\n const routes = capture.createRouteStats({\n maxRoutes: DEVTOOLS_PRODUCTION_DEFAULTS.maxRoutes,\n instance: instance.id,\n });\n const errors = capture.createErrorGroups({\n maxGroups: DEVTOOLS_PRODUCTION_DEFAULTS.maxErrorGroups,\n });\n const logs = capture.createRecentLogs({ maxEntries: 200 });\n\n stops.push(\n capture.attachDevelopmentStats(collector, {\n queries,\n routes,\n errors,\n logs,\n nPlusOneThreshold: resolved.nPlusOneThreshold,\n }),\n );\n\n const resources = insights.createResourceMonitor();\n const health = insights.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insights.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insights.createJobsReader(),\n queries,\n routes,\n errors,\n logs,\n counters: null,\n });\n const explainShape = capture.createShapeExplainer({\n queries,\n executing: false,\n instance: instance.id,\n });\n\n disposers.push(...stops);\n\n return { instance, insights: insights.createLocalInsights(reporter), explainShape };\n } catch (error) {\n for (const stop of stops) {\n try {\n stop();\n } catch {\n // Cleanup after a failed start must not hide the reason.\n }\n }\n\n log.warn(\n \"devtools\",\n \"insights-failed\",\n `devtools' statistics could not start, so the Resources, Queries, Routes, Errors, Health and Jobs tabs are not available: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return {};\n }\n}\n\n/**\n * Starts this process's AI totals in development: loads the Panoptic feed and\n * writes hourly rollups to `storage/devtools/ai-rollups`. Never throws; a\n * failure leaves the Reports, Models and Errors pages answering why.\n */\nasync function wireDevelopmentAiReports(\n ai: Awaited<ReturnType<typeof attachAiSource>>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<NonNullable<MountDevtoolsRoutesDeps[\"aiReports\"]>> {\n const none = (reason: \"ai-missing\" | \"reports-off\") => ({\n ...toAiUnavailableView(describeAiUnavailable(reason)),\n async dispose() {},\n });\n\n try {\n const loaded = await loadAiFeed();\n\n if (\"unavailable\" in loaded) return { ...loaded.unavailable, async dispose() {} };\n\n const reports = await attachAiReports({\n feed: loaded.feed,\n options: resolveDevtoolsAiOptions(resolved.ai, \"development\"),\n ...(typeof core.storagePath === \"function\"\n ? { directory: core.storagePath(\"devtools/ai-rollups\") }\n : {}),\n recentFailures: (filter) =>\n ai.available ? recentAiFailures(ai.store.query(), 50, filter) : [],\n warn: (message) => log.warn(\"devtools\", \"ai-reports\", message),\n });\n\n disposers.push(() => reports.dispose());\n\n return reports;\n } catch (error) {\n log.warn(\n \"devtools\",\n \"ai-reports\",\n `AI reports could not start: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return none(\"reports-off\");\n }\n}\n\n/**\n * Starts the production monitor: loads the panels in production mode and\n * hands everything to `bootProductionDevtools`, which refuses to boot (throws\n * `DevtoolsProductionConfigError`) when the configuration is incomplete.\n */\nasync function bootProduction(\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n): Promise<DevtoolsDisposer> {\n const { bootProductionDevtools } = await import(\"./production/boot\");\n const requestLog = await findRequestLogSource();\n // The Processes panel reads an app file; load it only when the project turned that tab on.\n const processPanel =\n resolved.production?.panels?.processes === true ? await loadProcessPanel() : undefined;\n const builtIn = processesDevtoolsPanel(processPanel);\n const panelErrors = createPanelErrorSource();\n const packagePanels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n mode: \"production\",\n errors: panelErrors.read,\n });\n // `warlock start` registers no development OpenAPI provider: the API tab, when turned on, builds its own.\n const { createProductionOpenApi } = await import(\"./production/openapi\");\n const openApi = createProductionOpenApi(core);\n\n return bootProductionDevtools({\n options: resolved,\n env: process.env,\n server: core.getHttpServer(),\n panels: [...checkDevtoolsPanels([builtIn]), ...packagePanels],\n routes: {\n ...(processPanel ? { processPanel } : {}),\n ...(requestLog ? { requestLog } : {}),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: openApi.getOpenApiDocument,\n getPostmanCollection: openApi.getPostmanCollection,\n },\n log,\n onInsights: (insights) => panelErrors.bind(insights),\n });\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n\ntype PostmanBuilder = () => Promise<unknown>;\n\n/**\n * Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.\n * Older cores do not export it; the route then answers 503. The lookup is\n * guarded because a namespace without the export may throw on access. Core is\n * imported lazily, like the OpenAPI document above.\n */\nasync function findPostmanBuilder(): Promise<PostmanBuilder | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const build = core.getDevelopmentPostmanCollection;\n\n return typeof build === \"function\" ? (build as PostmanBuilder) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Looks up core's persistent request log reader. Older cores do not export\n * it; the dashboard then shows the in-memory requests only. Core is imported\n * lazily, like the builders above.\n */\nasync function findRequestLogSource(): Promise<DevtoolsRequestLogSource | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const { listRequestLogs, getRequestLog, requestLogToCurl, compileRequestLogFilter } = core;\n\n if (\n typeof listRequestLogs !== \"function\" ||\n typeof getRequestLog !== \"function\" ||\n typeof requestLogToCurl !== \"function\" ||\n typeof compileRequestLogFilter !== \"function\"\n ) {\n return undefined;\n }\n\n return {\n list: (filter) => listRequestLogs(filter),\n get: (id) => getRequestLog(id),\n curl: (record, baseUrl) => requestLogToCurl(record, baseUrl),\n compile: (filter) => compileRequestLogFilter(filter),\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Core may return the collection itself or wrap it in `{ collection, warnings }`,\n * like the OpenAPI generator's `{ document, warnings }`.\n */\nfunction unwrapCollection(result: unknown): object {\n if (result && typeof result === \"object\" && \"collection\" in result) {\n return (result as { collection: object }).collection;\n }\n\n return result as object;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,8BAA8B;;AAG3C,MAAa,gCAAgC,OAAO,IAAI,0CAA0C;;;;;AAMlG,SAAS,sBAAsB,YAAmE;CAChG,IAAI;EACF,MAAM,QAAQ,WAAW,CAAC,CAAC,IAAI,UAAU;EAEzC,OAAO,UAAU,QAAQ,OAAO,UAAU,WAAY,QAA4B,CAAC;CACrF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,kBAAkB,UAAoC,CAAC,GAAc;CAGnF,IAAI,QAAQ,YAAY,YAAY,MAClC,AAAC,WAAuC,iCAAiC;CAG3E,IAAI,SAAS;CACb,MAAM,YAAgC,CAAC;CAEvC,MAAM,YAAuB;EAC3B,MAAM;EACN;EAGA,gBAAgB;EAChB,gBAAgB;EAChB,MAAM,OAAO;GACX,MAAM,OAAO,MAAM,OAAO;GAC1B,MAAM,EAAE,aAAa,kBAAkB;G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E_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_SHARE_LABEL_MAX, DevtoolsAccountView, DevtoolsAiBreakdownRow, DevtoolsAiCostTotals, DevtoolsAiErrorCategory, DevtoolsAiErrorGroup, DevtoolsAiErrorsView, DevtoolsAiEvaluatePrompt, DevtoolsAiEvaluateRequest, DevtoolsAiEvaluateResult, DevtoolsAiEvaluateView, DevtoolsAiFailedRun, DevtoolsAiFilterOptions, DevtoolsAiLatencyTotals, DevtoolsAiModelRow, DevtoolsAiModelsView, DevtoolsAiPricingState, DevtoolsAiRangePreset, DevtoolsAiRatePoint, DevtoolsAiReportView, DevtoolsAiResolvedRange, DevtoolsAiRunGroup, DevtoolsAiRunRow, DevtoolsAiRunsView, DevtoolsAiSeriesSet, DevtoolsAiTokenTotals, DevtoolsAiTotals, DevtoolsAiUnavailableReasonView, DevtoolsAiUnavailableView, DevtoolsAiUsageView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsCreatedShare, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsQueueInfo, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsScheduleRun, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsShareCreateInput, DevtoolsShareList, DevtoolsShareOpenAnswer, DevtoolsShareStatus, DevtoolsShareView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./production/contracts.mjs";
|
|
3
|
+
import { DevtoolsAiOptions } from "./ai/types.mjs";
|
|
2
4
|
import { DevtoolsAiEvent, DevtoolsAiRun } from "./sources/ai-source.mjs";
|
|
3
|
-
import { DEVTOOLS_BUILT_IN_PANELS, DEVTOOLS_FAILURE_AUDIT_TYPES, DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_SHARE_LABEL_MAX, DevtoolsAccountView, DevtoolsApiErrorBody, DevtoolsAuditEntry, DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsBuiltInPanelId, DevtoolsCaptureCounters, DevtoolsCreatedInvite, DevtoolsCreatedShare, DevtoolsErrorCode, DevtoolsErrorGroup, DevtoolsErrorsView, DevtoolsExplainResult, DevtoolsHealthReport, DevtoolsHealthView, DevtoolsHistogram, DevtoolsInstanceInfo, DevtoolsInstanceReport, DevtoolsInstancesView, DevtoolsInviteView, DevtoolsJobsReport, DevtoolsJobsView, DevtoolsLogRow, DevtoolsLoginInput, DevtoolsLogsView, DevtoolsMode, DevtoolsPanelInfo, DevtoolsPasswordSource, DevtoolsQueryShapeRow, DevtoolsQueryShapeStats, DevtoolsQueryStatsView, DevtoolsRecoveryCodes, DevtoolsReportLogEntry, DevtoolsResourcePoint, DevtoolsResourceSnapshot, DevtoolsResourcesView, DevtoolsRole, DevtoolsRoutePhaseStats, DevtoolsRouteStats, DevtoolsRouteStatsRow, DevtoolsRouteStatsView, DevtoolsSampleDetail, DevtoolsSampleQuery, DevtoolsSampleSummary, DevtoolsScheduleInfo, DevtoolsSessionInfo, DevtoolsSessionStage, DevtoolsSessionView, DevtoolsShareCreateInput, DevtoolsShareList, DevtoolsShareOpenAnswer, DevtoolsShareStatus, DevtoolsShareView, DevtoolsTotpEnrolment, DevtoolsUserListView } from "./production/contracts.mjs";
|
|
4
5
|
import { DevtoolsBackground, DevtoolsCacheOperation, DevtoolsCallerLocation, DevtoolsCollector, DevtoolsDisposer, DevtoolsLogEntry, DevtoolsMail, DevtoolsMailAttachment, DevtoolsMailSummary, DevtoolsOptions, DevtoolsPanel, DevtoolsPanelEntry, DevtoolsPanelErrorSummary, DevtoolsPanelExport, DevtoolsPanelFactoryContext, DevtoolsPanelFiles, DevtoolsPanelMethod, DevtoolsPanelRequest, DevtoolsPanelRoute, DevtoolsPanelShare, DevtoolsPanels, DevtoolsPhase, DevtoolsProductionOptions, DevtoolsQuery, DevtoolsRequest, DevtoolsRequestDetail, DevtoolsRequestSummary, DevtoolsStreamEvent, DevtoolsWarning, ResolvedDevtoolsOptions } from "./types.mjs";
|
|
5
6
|
import { devtoolsConnector } from "./devtools-connector.mjs";
|
|
6
7
|
import { DEVTOOLS_PANEL_TOKENS } from "./panel-tokens.mjs";
|
|
7
|
-
export { type DEVTOOLS_BUILT_IN_PANELS, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_PANEL_TOKENS, type DEVTOOLS_SHARE_LABEL_MAX, type DevtoolsAccountView, type DevtoolsAgentRun, type DevtoolsAgentTraceEvent, type DevtoolsAiEvent, type DevtoolsAiRun, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBackground, type DevtoolsBuiltInPanelId, type DevtoolsCacheOperation, type DevtoolsCallerLocation, type DevtoolsCaptureCounters, type DevtoolsCollector, type DevtoolsCreatedInvite, type DevtoolsCreatedShare, type DevtoolsDisposer, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogEntry, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMail, type DevtoolsMailAttachment, type DevtoolsMailSummary, type DevtoolsMode, type DevtoolsOptions, type DevtoolsPanel, type DevtoolsPanelEntry, type DevtoolsPanelErrorSummary, type DevtoolsPanelExport, type DevtoolsPanelFactoryContext, type DevtoolsPanelFiles, type DevtoolsPanelInfo, type DevtoolsPanelMethod, type DevtoolsPanelRequest, type DevtoolsPanelRoute, type DevtoolsPanelShare, type DevtoolsPanels, type DevtoolsPasswordSource, type DevtoolsPhase, type DevtoolsProductionOptions, type DevtoolsQuery, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsRequest, type DevtoolsRequestDetail, type DevtoolsRequestSummary, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsShareCreateInput, type DevtoolsShareList, type DevtoolsShareOpenAnswer, type DevtoolsShareStatus, type DevtoolsShareView, type DevtoolsStreamEvent, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type DevtoolsWarning, type ResolvedDevtoolsOptions, devtoolsConnector };
|
|
8
|
+
export { type DEVTOOLS_AI_ERROR_CATEGORIES, type DEVTOOLS_AI_LATENCY_BUCKETS_MS, type DEVTOOLS_BUILT_IN_PANELS, type DEVTOOLS_FAILURE_AUDIT_TYPES, type DEVTOOLS_LATENCY_BUCKETS_MS, DEVTOOLS_PANEL_TOKENS, type DEVTOOLS_SHARE_LABEL_MAX, type DevtoolsAccountView, type DevtoolsAgentRun, type DevtoolsAgentTraceEvent, type DevtoolsAiBreakdownRow, type DevtoolsAiCostTotals, type DevtoolsAiErrorCategory, type DevtoolsAiErrorGroup, type DevtoolsAiErrorsView, type DevtoolsAiEvaluatePrompt, type DevtoolsAiEvaluateRequest, type DevtoolsAiEvaluateResult, type DevtoolsAiEvaluateView, type DevtoolsAiEvent, type DevtoolsAiFailedRun, type DevtoolsAiFilterOptions, type DevtoolsAiLatencyTotals, type DevtoolsAiModelRow, type DevtoolsAiModelsView, type DevtoolsAiOptions, type DevtoolsAiPricingState, type DevtoolsAiRangePreset, type DevtoolsAiRatePoint, type DevtoolsAiReportView, type DevtoolsAiResolvedRange, type DevtoolsAiRun, type DevtoolsAiRunGroup, type DevtoolsAiRunRow, type DevtoolsAiRunsView, type DevtoolsAiSeriesSet, type DevtoolsAiTokenTotals, type DevtoolsAiTotals, type DevtoolsAiUnavailableReasonView, type DevtoolsAiUnavailableView, type DevtoolsAiUsageView, type DevtoolsApiErrorBody, type DevtoolsAuditEntry, type DevtoolsAuditType, type DevtoolsAuthStepResult, type DevtoolsBackground, type DevtoolsBuiltInPanelId, type DevtoolsCacheOperation, type DevtoolsCallerLocation, type DevtoolsCaptureCounters, type DevtoolsCollector, type DevtoolsCreatedInvite, type DevtoolsCreatedShare, type DevtoolsDisposer, type DevtoolsErrorCode, type DevtoolsErrorGroup, type DevtoolsErrorsView, type DevtoolsExplainResult, type DevtoolsHealthReport, type DevtoolsHealthView, type DevtoolsHistogram, type DevtoolsInstanceInfo, type DevtoolsInstanceReport, type DevtoolsInstancesView, type DevtoolsInviteView, type DevtoolsJobsReport, type DevtoolsJobsView, type DevtoolsLogEntry, type DevtoolsLogRow, type DevtoolsLoginInput, type DevtoolsLogsView, type DevtoolsMail, type DevtoolsMailAttachment, type DevtoolsMailSummary, type DevtoolsMode, type DevtoolsOptions, type DevtoolsPanel, type DevtoolsPanelEntry, type DevtoolsPanelErrorSummary, type DevtoolsPanelExport, type DevtoolsPanelFactoryContext, type DevtoolsPanelFiles, type DevtoolsPanelInfo, type DevtoolsPanelMethod, type DevtoolsPanelRequest, type DevtoolsPanelRoute, type DevtoolsPanelShare, type DevtoolsPanels, type DevtoolsPasswordSource, type DevtoolsPhase, type DevtoolsProductionOptions, type DevtoolsQuery, type DevtoolsQueryShapeRow, type DevtoolsQueryShapeStats, type DevtoolsQueryStatsView, type DevtoolsQueueInfo, type DevtoolsRecoveryCodes, type DevtoolsReportLogEntry, type DevtoolsRequest, type DevtoolsRequestDetail, type DevtoolsRequestSummary, type DevtoolsResourcePoint, type DevtoolsResourceSnapshot, type DevtoolsResourcesView, type DevtoolsRole, type DevtoolsRoutePhaseStats, type DevtoolsRouteStats, type DevtoolsRouteStatsRow, type DevtoolsRouteStatsView, type DevtoolsSampleDetail, type DevtoolsSampleQuery, type DevtoolsSampleSummary, type DevtoolsScheduleInfo, type DevtoolsScheduleRun, type DevtoolsSessionInfo, type DevtoolsSessionStage, type DevtoolsSessionView, type DevtoolsShareCreateInput, type DevtoolsShareList, type DevtoolsShareOpenAnswer, type DevtoolsShareStatus, type DevtoolsShareView, type DevtoolsStreamEvent, type DevtoolsTotpEnrolment, type DevtoolsUserListView, type DevtoolsWarning, type ResolvedDevtoolsOptions, devtoolsConnector };
|
package/esm/options.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { resolveDevtoolsAiOptions } from "./ai/options.mjs";
|
|
2
|
+
|
|
1
3
|
//#region ../../packages/devtools/src/options.ts
|
|
2
4
|
/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */
|
|
3
5
|
function resolveDevtoolsOptions(options = {}) {
|
|
@@ -7,6 +9,7 @@ function resolveDevtoolsOptions(options = {}) {
|
|
|
7
9
|
if (!path || !path.startsWith("/")) throw new Error("Devtools option \"path\" must be a non-root path starting with \"/\".");
|
|
8
10
|
if (maxRequests < 1) throw new Error("Devtools option \"maxRequests\" must be at least 1.");
|
|
9
11
|
if (nPlusOneThreshold < 2) throw new Error("Devtools option \"nPlusOneThreshold\" must be at least 2.");
|
|
12
|
+
if (options.ai !== void 0) resolveDevtoolsAiOptions(options.ai, "development");
|
|
10
13
|
return {
|
|
11
14
|
path,
|
|
12
15
|
maxRequests,
|
|
@@ -14,6 +17,7 @@ function resolveDevtoolsOptions(options = {}) {
|
|
|
14
17
|
allowedHosts: options.allowedHosts ?? [],
|
|
15
18
|
allowProxied: options.allowProxied ?? false,
|
|
16
19
|
panels: options.panels ?? [],
|
|
20
|
+
...options.ai === void 0 ? {} : { ai: options.ai },
|
|
17
21
|
...options.production === void 0 ? {} : { production: options.production }
|
|
18
22
|
};
|
|
19
23
|
}
|
package/esm/options.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.mjs","names":[],"sources":["../../../../../../../packages/devtools/src/options.ts"],"sourcesContent":["import type { DevtoolsOptions, ResolvedDevtoolsOptions } from \"./types\";\n\n/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */\nexport function resolveDevtoolsOptions(options: DevtoolsOptions = {}): ResolvedDevtoolsOptions {\n const path = (options.path ?? \"/__warlock\").replace(/\\/+$/, \"\");\n const maxRequests = options.maxRequests ?? 200;\n const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;\n\n if (!path || !path.startsWith(\"/\")) {\n throw new Error('Devtools option \"path\" must be a non-root path starting with \"/\".');\n }\n\n if (maxRequests < 1) {\n throw new Error('Devtools option \"maxRequests\" must be at least 1.');\n }\n\n if (nPlusOneThreshold < 2) {\n throw new Error('Devtools option \"nPlusOneThreshold\" must be at least 2.');\n }\n\n return {\n path,\n maxRequests,\n nPlusOneThreshold,\n allowedHosts: options.allowedHosts ?? [],\n allowProxied: options.allowProxied ?? false,\n panels: options.panels ?? [],\n ...(options.production === undefined ? {} : { production: options.production }),\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"options.mjs","names":[],"sources":["../../../../../../../packages/devtools/src/options.ts"],"sourcesContent":["import { resolveDevtoolsAiOptions } from \"./ai/options\";\nimport type { DevtoolsOptions, ResolvedDevtoolsOptions } from \"./types\";\n\n/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */\nexport function resolveDevtoolsOptions(options: DevtoolsOptions = {}): ResolvedDevtoolsOptions {\n const path = (options.path ?? \"/__warlock\").replace(/\\/+$/, \"\");\n const maxRequests = options.maxRequests ?? 200;\n const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;\n\n if (!path || !path.startsWith(\"/\")) {\n throw new Error('Devtools option \"path\" must be a non-root path starting with \"/\".');\n }\n\n if (maxRequests < 1) {\n throw new Error('Devtools option \"maxRequests\" must be at least 1.');\n }\n\n if (nPlusOneThreshold < 2) {\n throw new Error('Devtools option \"nPlusOneThreshold\" must be at least 2.');\n }\n\n // Validates the AI options; the mode defaults are applied where the mode is known.\n if (options.ai !== undefined) resolveDevtoolsAiOptions(options.ai, \"development\");\n\n return {\n path,\n maxRequests,\n nPlusOneThreshold,\n allowedHosts: options.allowedHosts ?? [],\n allowProxied: options.allowProxied ?? false,\n panels: options.panels ?? [],\n ...(options.ai === undefined ? {} : { ai: options.ai }),\n ...(options.production === undefined ? {} : { production: options.production }),\n };\n}\n"],"mappings":";;;;AAIA,SAAgB,uBAAuB,UAA2B,CAAC,GAA4B;CAC7F,MAAM,QAAQ,QAAQ,QAAQ,aAAY,CAAE,QAAQ,QAAQ,EAAE;CAC9D,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,oBAAoB,QAAQ,qBAAqB;CAEvD,IAAI,CAAC,QAAQ,CAAC,KAAK,WAAW,GAAG,GAC/B,MAAM,IAAI,MAAM,uEAAmE;CAGrF,IAAI,cAAc,GAChB,MAAM,IAAI,MAAM,qDAAmD;CAGrE,IAAI,oBAAoB,GACtB,MAAM,IAAI,MAAM,2DAAyD;CAI3E,IAAI,QAAQ,OAAO,QAAW,yBAAyB,QAAQ,IAAI,aAAa;CAEhF,OAAO;EACL;EACA;EACA;EACA,cAAc,QAAQ,gBAAgB,CAAC;EACvC,cAAc,QAAQ,gBAAgB;EACtC,QAAQ,QAAQ,UAAU,CAAC;EAC3B,GAAI,QAAQ,OAAO,SAAY,CAAC,IAAI,EAAE,IAAI,QAAQ,GAAG;EACrD,GAAI,QAAQ,eAAe,SAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;CAC/E;AACF"}
|
package/esm/production/boot.mjs
CHANGED
|
@@ -1,8 +1,60 @@
|
|
|
1
1
|
import { productionPanels } from "../panels.mjs";
|
|
2
|
+
import { resolveDevtoolsAiOptions } from "../ai/options.mjs";
|
|
2
3
|
import { DevtoolsProductionConfigError } from "./errors.mjs";
|
|
3
4
|
import { resolveProductionOptions } from "./options.mjs";
|
|
5
|
+
import { describeAiUnavailable, toAiUnavailableView } from "../sources/ai-source.mjs";
|
|
6
|
+
import { DEVTOOLS_MOUNTED_KEY, attachAiReports, loadAiFeed } from "../ai/attach.mjs";
|
|
4
7
|
|
|
5
8
|
//#region ../../packages/devtools/src/production/boot.ts
|
|
9
|
+
const AI_REPORT_TABS = [
|
|
10
|
+
"ai-reports",
|
|
11
|
+
"ai-models",
|
|
12
|
+
"ai-errors"
|
|
13
|
+
];
|
|
14
|
+
/** Tells other packages (Panoptic) that devtools is mounted here and where. */
|
|
15
|
+
function publishMounted(path) {
|
|
16
|
+
globalThis[DEVTOOLS_MOUNTED_KEY] = {
|
|
17
|
+
path,
|
|
18
|
+
mode: "production"
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function clearMounted() {
|
|
22
|
+
delete globalThis[DEVTOOLS_MOUNTED_KEY];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Loads the AI feed and starts this process's rollup writer (every process of
|
|
26
|
+
* a deployment adds into the same table). Never throws: a failure leaves the
|
|
27
|
+
* AI report tabs answering their unavailable view.
|
|
28
|
+
*/
|
|
29
|
+
async function attachProductionAi(options, warn) {
|
|
30
|
+
const loaded = await loadAiFeed();
|
|
31
|
+
if ("unavailable" in loaded) return {
|
|
32
|
+
feedAvailable: false,
|
|
33
|
+
reports: {
|
|
34
|
+
...loaded.unavailable,
|
|
35
|
+
async dispose() {}
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
try {
|
|
39
|
+
return {
|
|
40
|
+
feedAvailable: true,
|
|
41
|
+
reports: await attachAiReports({
|
|
42
|
+
feed: loaded.feed,
|
|
43
|
+
options: resolveDevtoolsAiOptions(options.ai, "production"),
|
|
44
|
+
warn
|
|
45
|
+
})
|
|
46
|
+
};
|
|
47
|
+
} catch (error) {
|
|
48
|
+
warn(`AI reports could not start: ${error instanceof Error ? error.message : String(error)}`);
|
|
49
|
+
return {
|
|
50
|
+
feedAvailable: true,
|
|
51
|
+
reports: {
|
|
52
|
+
...toAiUnavailableView(describeAiUnavailable("reports-off")),
|
|
53
|
+
async dispose() {}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
6
58
|
/** `/ops-…`: the first part of the path, enough to recognise it and not enough to use it. */
|
|
7
59
|
function maskDashboardPath(path) {
|
|
8
60
|
const match = /^\/[A-Za-z]{1,8}-/.exec(path);
|
|
@@ -95,7 +147,16 @@ async function bootProductionDevtools(input) {
|
|
|
95
147
|
});
|
|
96
148
|
input.onInsights?.(insights);
|
|
97
149
|
const state = httpModule.createDashboardState(store, production.path);
|
|
98
|
-
const { builtIn, panels } = productionPanels(input.panels, production.panels);
|
|
150
|
+
const { builtIn: shownTabs, panels } = productionPanels(input.panels, production.panels);
|
|
151
|
+
const aiWiring = shownTabs.some((tab) => AI_REPORT_TABS.includes(tab)) ? await attachProductionAi(options, warn) : {
|
|
152
|
+
feedAvailable: false,
|
|
153
|
+
reports: {
|
|
154
|
+
...toAiUnavailableView(describeAiUnavailable("reports-off")),
|
|
155
|
+
async dispose() {}
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
const builtIn = aiWiring.feedAvailable ? shownTabs : shownTabs.filter((tab) => !AI_REPORT_TABS.includes(tab) || production.panels[tab] === true);
|
|
159
|
+
stops.push(() => aiWiring.reports.dispose());
|
|
99
160
|
if (typeof core.excludeFromRequestLog === "function") stops.push(core.excludeFromRequestLog(production.path));
|
|
100
161
|
if (builtIn.includes("mail")) {
|
|
101
162
|
const { attachMailSource } = await import("../sources/mail-source.mjs");
|
|
@@ -104,6 +165,7 @@ async function bootProductionDevtools(input) {
|
|
|
104
165
|
httpModule.mountProductionDevtools(server, {
|
|
105
166
|
routes: {
|
|
106
167
|
...input.routes,
|
|
168
|
+
aiReports: aiWiring.reports,
|
|
107
169
|
collector: capture.collector,
|
|
108
170
|
options,
|
|
109
171
|
isDevelopment: () => false
|
|
@@ -118,8 +180,11 @@ async function bootProductionDevtools(input) {
|
|
|
118
180
|
builtInPanels: builtIn,
|
|
119
181
|
state,
|
|
120
182
|
warn,
|
|
183
|
+
...typeof core.answerUnknownUrl === "function" ? { answerUnknownUrl: core.answerUnknownUrl } : {},
|
|
121
184
|
hmac: (value) => crypto.hmac(value)
|
|
122
185
|
});
|
|
186
|
+
publishMounted(production.path);
|
|
187
|
+
stops.push(clearMounted);
|
|
123
188
|
log.info("devtools", "ready", `devtools production monitor mounted at ${maskDashboardPath(production.path)} (DEVTOOLS_PATH)`);
|
|
124
189
|
} catch (error) {
|
|
125
190
|
for (const stop of stops.splice(0).reverse()) try {
|
|
@@ -129,10 +194,12 @@ async function bootProductionDevtools(input) {
|
|
|
129
194
|
throw error;
|
|
130
195
|
}
|
|
131
196
|
return () => {
|
|
197
|
+
const finished = [];
|
|
132
198
|
for (const stop of stops.splice(0).reverse()) try {
|
|
133
|
-
Promise.resolve(stop()).catch(() => void 0);
|
|
199
|
+
finished.push(Promise.resolve(stop()).catch(() => void 0));
|
|
134
200
|
} catch {}
|
|
135
|
-
capture.dispose().catch(() => void 0);
|
|
201
|
+
finished.push(capture.dispose().catch(() => void 0));
|
|
202
|
+
return Promise.all(finished).then(() => void 0);
|
|
136
203
|
};
|
|
137
204
|
}
|
|
138
205
|
|