@warlock.js/devtools 5.59.0 → 5.60.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 +17 -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-Dg5YZGGR.cjs} +77 -14
- package/cjs/boot-Dg5YZGGR.cjs.map +1 -0
- package/cjs/{capture-CuyT8Vab.cjs → capture-CBgONYhk.cjs} +4 -4
- package/cjs/{capture-CuyT8Vab.cjs.map → capture-CBgONYhk.cjs.map} +1 -1
- 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/{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/{histogram-DTOGnNBW.cjs → histogram-CkoVizdf.cjs} +6 -6
- package/cjs/{histogram-DTOGnNBW.cjs.map → histogram-CkoVizdf.cjs.map} +1 -1
- package/cjs/{http-Biauhqi0.cjs → http-DCVCf44M.cjs} +25 -8
- package/cjs/http-DCVCf44M.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-BjJA6Ret.cjs → insights-CFof59kF.cjs} +3 -3
- package/cjs/{insights-BjJA6Ret.cjs.map → insights-CFof59kF.cjs.map} +1 -1
- 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/runs-DECWPGnq.cjs +390 -0
- package/cjs/runs-DECWPGnq.cjs.map +1 -0
- package/cjs/{server-D3XRbSSb.cjs → server-CC5DpObz.cjs} +8 -7
- package/cjs/{server-D3XRbSSb.cjs.map → server-CC5DpObz.cjs.map} +1 -1
- package/cjs/{src-QcNghoYN.cjs → src-VyOjEEAo.cjs} +178 -23
- package/cjs/src-VyOjEEAo.cjs.map +1 -0
- package/cjs/{store-CNFv3wVp.cjs → store-EFn4wp0T.cjs} +2 -2
- package/cjs/{stream-route-BqyAlfxQ.cjs → stream-route-DFHuIWgg.cjs} +107 -15
- package/cjs/stream-route-DFHuIWgg.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 +54 -2
- 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 +69 -3
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +371 -2
- 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 +13 -0
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/index.d.mts +2 -2
- 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/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 +56 -17
- package/package.json +8 -8
- package/skills/SKILL.md +56 -17
- 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/errors-BadbSDX8.cjs.map +0 -1
- package/cjs/http-Biauhqi0.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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"sourceHash": "
|
|
2
|
+
"sourceHash": "64a8dff1d77b2161ea0ab96ed2b28400a1c717ec6154443354f28b23247042db",
|
|
3
3
|
"budgetGzipBytes": 307200,
|
|
4
4
|
"files": {
|
|
5
5
|
"index.html": {
|
|
@@ -8,14 +8,14 @@
|
|
|
8
8
|
"sha256": "c3f1725dc0a8d8fcf95ea3773de64d90d84780f56f49c702f0ce7eac1ad1d55b"
|
|
9
9
|
},
|
|
10
10
|
"assets/app.js": {
|
|
11
|
-
"bytes":
|
|
12
|
-
"gzipBytes":
|
|
13
|
-
"sha256": "
|
|
11
|
+
"bytes": 512678,
|
|
12
|
+
"gzipBytes": 157117,
|
|
13
|
+
"sha256": "878253932a373fa81e644e18df57c2251c1804285a93cdc5f159c8cce648bde5"
|
|
14
14
|
},
|
|
15
15
|
"assets/app.css": {
|
|
16
|
-
"bytes":
|
|
17
|
-
"gzipBytes":
|
|
18
|
-
"sha256": "
|
|
16
|
+
"bytes": 58275,
|
|
17
|
+
"gzipBytes": 10463,
|
|
18
|
+
"sha256": "e7d14484229e3c2e3f1fa9eab9f39916fb164c51a90d014905768c17531bdb6b"
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
}
|
|
@@ -1,448 +0,0 @@
|
|
|
1
|
-
const require_app_versions = require("./app-versions-DfpPZOI2.cjs");
|
|
2
|
-
let node_fs = require("node:fs");
|
|
3
|
-
let node_path = require("node:path");
|
|
4
|
-
node_path = require_app_versions.__toESM(node_path, 1);
|
|
5
|
-
let node_url = require("node:url");
|
|
6
|
-
|
|
7
|
-
//#region ../../packages/devtools/src/ui-root.ts
|
|
8
|
-
let cachedUiRoot;
|
|
9
|
-
/**
|
|
10
|
-
* Whether `dir` is this package's root: it has the built dashboard
|
|
11
|
-
* (`ui/dashboard/index.html`) or, before the first build, the Processes panel
|
|
12
|
-
* view (`ui/panels/processes.js`), beside a `package.json` named
|
|
13
|
-
* `@warlock.js/devtools`.
|
|
14
|
-
*/
|
|
15
|
-
function isPackageRoot(dir) {
|
|
16
|
-
const hasUi = (0, node_fs.existsSync)(node_path.default.join(dir, "ui", "dashboard", "index.html")) || (0, node_fs.existsSync)(node_path.default.join(dir, "ui", "panels", "processes.js"));
|
|
17
|
-
const packageJson = node_path.default.join(dir, "package.json");
|
|
18
|
-
if (!hasUi || !(0, node_fs.existsSync)(packageJson)) return false;
|
|
19
|
-
try {
|
|
20
|
-
return JSON.parse((0, node_fs.readFileSync)(packageJson, "utf8")).name === "@warlock.js/devtools";
|
|
21
|
-
} catch {
|
|
22
|
-
return false;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Locate this package's `ui/` directory by walking up from the current
|
|
27
|
-
* module's directory. Works from `src/` in development and from the built
|
|
28
|
-
* `esm/`/`cjs/` output, since both sit beside `ui/` and `package.json` at
|
|
29
|
-
* the package root.
|
|
30
|
-
*/
|
|
31
|
-
function resolveUiRoot() {
|
|
32
|
-
if (cachedUiRoot) return cachedUiRoot;
|
|
33
|
-
let dir = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
|
|
34
|
-
while (true) {
|
|
35
|
-
if (isPackageRoot(dir)) {
|
|
36
|
-
cachedUiRoot = node_path.default.join(dir, "ui");
|
|
37
|
-
return cachedUiRoot;
|
|
38
|
-
}
|
|
39
|
-
const parent = node_path.default.dirname(dir);
|
|
40
|
-
if (parent === dir) throw new Error("Could not locate the devtools UI directory: no ancestor of this module has ui/dashboard/index.html or ui/panels/processes.js beside a package.json named @warlock.js/devtools.");
|
|
41
|
-
dir = parent;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
//#endregion
|
|
46
|
-
//#region ../../packages/devtools/src/sources/agent-trace-source.ts
|
|
47
|
-
/**
|
|
48
|
-
* Key `@warlock.js/ai` publishes its agent trace store under on
|
|
49
|
-
* `globalThis`. Reading the store from the registry, not by importing the
|
|
50
|
-
* package, keeps devtools free of an AI dependency and shares one store
|
|
51
|
-
* even when two copies of the package are installed.
|
|
52
|
-
*/
|
|
53
|
-
const AGENT_TRACES_KEY = Symbol.for("@warlock.js/ai.agentTraces");
|
|
54
|
-
const AGENT_TRACE_INSTALL_GUIDANCE = "No agent traces yet. Install @warlock.js/ai 5.38 or newer and run an agent in development (agents record traces by default there; `trace: true` turns it on elsewhere), then reload.";
|
|
55
|
-
/** One list row for a trace. */
|
|
56
|
-
function summarizeAgentTrace(trace, requestId) {
|
|
57
|
-
let toolCalls = 0;
|
|
58
|
-
let refusals = 0;
|
|
59
|
-
for (const turn of trace.turns) {
|
|
60
|
-
toolCalls += turn.toolCalls.length;
|
|
61
|
-
refusals += turn.toolCalls.filter((call) => call.refusal !== void 0).length;
|
|
62
|
-
}
|
|
63
|
-
return {
|
|
64
|
-
runId: trace.runId,
|
|
65
|
-
agent: trace.agent,
|
|
66
|
-
status: trace.status,
|
|
67
|
-
startedAt: trace.startedAt,
|
|
68
|
-
durationMs: trace.durationMs,
|
|
69
|
-
model: `${trace.model.provider}/${trace.model.name}`,
|
|
70
|
-
turns: trace.turns.length,
|
|
71
|
-
toolCalls,
|
|
72
|
-
refusals,
|
|
73
|
-
usage: {
|
|
74
|
-
input: trace.usage.input,
|
|
75
|
-
output: trace.usage.output
|
|
76
|
-
},
|
|
77
|
-
cost: trace.cost,
|
|
78
|
-
...requestId ? { requestId } : {}
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
const MAX_REQUEST_LINKS = 500;
|
|
82
|
-
/**
|
|
83
|
-
* Attach to the shared agent trace store. The store is looked up lazily on
|
|
84
|
-
* every call, so it works whichever of devtools and `@warlock.js/ai` loads
|
|
85
|
-
* first. Runs are linked to the HTTP request that was active when the
|
|
86
|
-
* store first reported them.
|
|
87
|
-
*/
|
|
88
|
-
async function attachAgentTraceSource() {
|
|
89
|
-
const { currentRequestId } = await Promise.resolve().then(() => require("./current-request-id-CeQhRz9Q.cjs")).then((n) => n.current_request_id_exports);
|
|
90
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
91
|
-
const requestIds = /* @__PURE__ */ new Map();
|
|
92
|
-
let attachedStore;
|
|
93
|
-
let detach;
|
|
94
|
-
const findStore = () => {
|
|
95
|
-
const store = globalThis[AGENT_TRACES_KEY];
|
|
96
|
-
return store && typeof store.list === "function" ? store : void 0;
|
|
97
|
-
};
|
|
98
|
-
const ensureAttached = () => {
|
|
99
|
-
const store = findStore();
|
|
100
|
-
if (store && store !== attachedStore) {
|
|
101
|
-
detach?.();
|
|
102
|
-
attachedStore = store;
|
|
103
|
-
detach = store.subscribe((event) => {
|
|
104
|
-
let requestId = requestIds.get(event.runId);
|
|
105
|
-
if (!requestId) {
|
|
106
|
-
requestId = currentRequestId();
|
|
107
|
-
if (requestId) {
|
|
108
|
-
requestIds.set(event.runId, requestId);
|
|
109
|
-
if (requestIds.size > MAX_REQUEST_LINKS) {
|
|
110
|
-
const oldest = requestIds.keys().next();
|
|
111
|
-
if (!oldest.done) requestIds.delete(oldest.value);
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
for (const listener of listeners) try {
|
|
116
|
-
listener({
|
|
117
|
-
...event,
|
|
118
|
-
...requestId ? { requestId } : {}
|
|
119
|
-
});
|
|
120
|
-
} catch {}
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
return store;
|
|
124
|
-
};
|
|
125
|
-
ensureAttached();
|
|
126
|
-
return {
|
|
127
|
-
available: () => ensureAttached() !== void 0,
|
|
128
|
-
list(filter) {
|
|
129
|
-
const store = ensureAttached();
|
|
130
|
-
if (!store) return [];
|
|
131
|
-
return store.list().map((trace) => summarizeAgentTrace(trace, requestIds.get(trace.runId))).filter((run) => filter?.requestId === void 0 || run.requestId === filter.requestId);
|
|
132
|
-
},
|
|
133
|
-
get: (runId) => ensureAttached()?.get(runId),
|
|
134
|
-
subscribe(listener) {
|
|
135
|
-
ensureAttached();
|
|
136
|
-
listeners.add(listener);
|
|
137
|
-
return () => {
|
|
138
|
-
listeners.delete(listener);
|
|
139
|
-
};
|
|
140
|
-
},
|
|
141
|
-
dispose() {
|
|
142
|
-
detach?.();
|
|
143
|
-
detach = void 0;
|
|
144
|
-
attachedStore = void 0;
|
|
145
|
-
listeners.clear();
|
|
146
|
-
requestIds.clear();
|
|
147
|
-
}
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
//#endregion
|
|
152
|
-
//#region ../../packages/devtools/src/safe-value.ts
|
|
153
|
-
const MAX_DEPTH = 6;
|
|
154
|
-
/**
|
|
155
|
-
* A JSON-safe snapshot of a value devtools keeps for later display.
|
|
156
|
-
*
|
|
157
|
-
* Log contexts and phase attributes are app data: they can hold live objects
|
|
158
|
-
* (a request, its socket) whose graphs are circular and which must not be kept
|
|
159
|
-
* alive by the collector anyway. Plain objects and arrays are copied; anything
|
|
160
|
-
* with a `toJSON()` is serialized through it; other class instances collapse
|
|
161
|
-
* to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to
|
|
162
|
-
* `[Object]` / `[Array]`.
|
|
163
|
-
*/
|
|
164
|
-
function toSafeValue(value) {
|
|
165
|
-
return snapshot(value, 0, /* @__PURE__ */ new WeakSet());
|
|
166
|
-
}
|
|
167
|
-
function snapshot(value, depth, seen) {
|
|
168
|
-
if (value === null || value === void 0) return value;
|
|
169
|
-
switch (typeof value) {
|
|
170
|
-
case "string":
|
|
171
|
-
case "number":
|
|
172
|
-
case "boolean": return value;
|
|
173
|
-
case "bigint": return value.toString();
|
|
174
|
-
case "symbol": return value.toString();
|
|
175
|
-
case "function": return;
|
|
176
|
-
}
|
|
177
|
-
const object = value;
|
|
178
|
-
if (seen.has(object)) return "[Circular]";
|
|
179
|
-
if (value instanceof Date) return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
|
|
180
|
-
if (value instanceof Error) return {
|
|
181
|
-
name: value.name,
|
|
182
|
-
message: value.message
|
|
183
|
-
};
|
|
184
|
-
if (depth >= MAX_DEPTH) return Array.isArray(value) ? "[Array]" : "[Object]";
|
|
185
|
-
seen.add(object);
|
|
186
|
-
try {
|
|
187
|
-
if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));
|
|
188
|
-
const prototype = Object.getPrototypeOf(object);
|
|
189
|
-
if (prototype !== Object.prototype && prototype !== null) {
|
|
190
|
-
const toJSON = object.toJSON;
|
|
191
|
-
if (typeof toJSON === "function") try {
|
|
192
|
-
return snapshot(toJSON.call(object), depth + 1, seen);
|
|
193
|
-
} catch {
|
|
194
|
-
return `[${constructorName(object)}]`;
|
|
195
|
-
}
|
|
196
|
-
return `[${constructorName(object)}]`;
|
|
197
|
-
}
|
|
198
|
-
const copy = {};
|
|
199
|
-
for (const [key, entry] of Object.entries(object)) {
|
|
200
|
-
const safe = snapshot(entry, depth + 1, seen);
|
|
201
|
-
if (safe !== void 0) copy[key] = safe;
|
|
202
|
-
}
|
|
203
|
-
return copy;
|
|
204
|
-
} finally {
|
|
205
|
-
seen.delete(object);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
function constructorName(object) {
|
|
209
|
-
return object.constructor?.name || "Object";
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
//#endregion
|
|
213
|
-
//#region ../../packages/devtools/src/sources/ai-source.ts
|
|
214
|
-
/** Replaces absolute file paths in an error line with their package-relative part, or `<path>`. */
|
|
215
|
-
function redactPaths(text) {
|
|
216
|
-
return text.replace(/(?:file:\/\/)?(?:[A-Za-z]:)?[\\/][^\s'"`()]*/g, (match) => {
|
|
217
|
-
const normalized = match.replace(/^file:\/\//, "").replaceAll("\\", "/");
|
|
218
|
-
const index = normalized.lastIndexOf("node_modules/");
|
|
219
|
-
return index === -1 ? "<path>" : normalized.slice(index + 13);
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
const OBSERVATION_COMMAND = "ai.config({ panoptic: { observeAll: true } })";
|
|
223
|
-
/** The answer for each reason; `detail` carries the load error and versions for `panoptic-failed`. */
|
|
224
|
-
function describeAiUnavailable(reason, detail) {
|
|
225
|
-
switch (reason) {
|
|
226
|
-
case "ai-missing": return {
|
|
227
|
-
available: false,
|
|
228
|
-
reason,
|
|
229
|
-
title: "AI isn't installed",
|
|
230
|
-
message: "Add @warlock.js/ai to see AI runs here.",
|
|
231
|
-
command: "warlock add ai"
|
|
232
|
-
};
|
|
233
|
-
case "panoptic-missing": return {
|
|
234
|
-
available: false,
|
|
235
|
-
reason,
|
|
236
|
-
title: "Panoptic isn't installed",
|
|
237
|
-
message: "Your app uses @warlock.js/ai. Add Panoptic to see its runs.",
|
|
238
|
-
command: "warlock add ai-panoptic"
|
|
239
|
-
};
|
|
240
|
-
case "panoptic-failed": return {
|
|
241
|
-
available: false,
|
|
242
|
-
reason,
|
|
243
|
-
title: "Panoptic could not be loaded",
|
|
244
|
-
message: "Panoptic is installed but failed to load. Check that both packages share a version.",
|
|
245
|
-
detail
|
|
246
|
-
};
|
|
247
|
-
case "not-collected": return {
|
|
248
|
-
available: false,
|
|
249
|
-
reason,
|
|
250
|
-
title: "AI runs are not collected here",
|
|
251
|
-
message: "The production dashboard does not collect AI runs. Open the AI tab in development (warlock dev) to see them."
|
|
252
|
-
};
|
|
253
|
-
case "observation-off": return {
|
|
254
|
-
available: false,
|
|
255
|
-
reason,
|
|
256
|
-
title: "AI observation is off",
|
|
257
|
-
message: "Turn it on in src/config/ai.ts, then restart warlock dev.",
|
|
258
|
-
command: OBSERVATION_COMMAND
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
/** Summaries use root usage once: nested spans already roll up into it. */
|
|
263
|
-
function summarizeAiTrace(trace, cost) {
|
|
264
|
-
const models = /* @__PURE__ */ new Set();
|
|
265
|
-
let toolCalls = 0;
|
|
266
|
-
let retries = 0;
|
|
267
|
-
let cacheHits;
|
|
268
|
-
let incomplete = false;
|
|
269
|
-
let truncatedTrips = 0;
|
|
270
|
-
let compactions = 0;
|
|
271
|
-
let skippedCompactions = 0;
|
|
272
|
-
let providerCompactions = 0;
|
|
273
|
-
const visit = (span) => {
|
|
274
|
-
const attributes = span.attributes ?? {};
|
|
275
|
-
const model = attributes["agent.model.name"];
|
|
276
|
-
const provider = attributes["agent.model.provider"];
|
|
277
|
-
if (typeof model === "string") models.add(typeof provider === "string" ? `${provider}/${model}` : model);
|
|
278
|
-
if (span.type === "tool") toolCalls += 1;
|
|
279
|
-
if (typeof attributes.retries === "number") retries += attributes.retries;
|
|
280
|
-
if (typeof attributes["agent.cacheHits"] === "number") cacheHits = (cacheHits ?? 0) + attributes["agent.cacheHits"];
|
|
281
|
-
if (typeof attributes["agent.truncatedTrips"] === "number") truncatedTrips += attributes["agent.truncatedTrips"];
|
|
282
|
-
if (typeof attributes["agent.providerCompactions"] === "number") providerCompactions += attributes["agent.providerCompactions"];
|
|
283
|
-
if (Array.isArray(attributes["agent.compactions"])) {
|
|
284
|
-
const records = attributes["agent.compactions"];
|
|
285
|
-
for (const record of records) {
|
|
286
|
-
if (typeof record !== "object" || record === null || !("type" in record)) continue;
|
|
287
|
-
if (record.type === "applied") compactions += 1;
|
|
288
|
-
if (record.type === "skipped") skippedCompactions += 1;
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
incomplete ||= span.status === "incomplete" || span.error?.type === "AgentIncompleteError" || span.error?.type === "AGENT_INCOMPLETE";
|
|
292
|
-
span.children.forEach(visit);
|
|
293
|
-
};
|
|
294
|
-
visit(trace.root);
|
|
295
|
-
return {
|
|
296
|
-
traceId: trace.traceId,
|
|
297
|
-
requestId: trace.requestId,
|
|
298
|
-
sessionId: trace.sessionId,
|
|
299
|
-
name: trace.root.name,
|
|
300
|
-
status: trace.root.status,
|
|
301
|
-
startedAt: trace.startedAt,
|
|
302
|
-
duration: trace.duration,
|
|
303
|
-
usage: trace.usage,
|
|
304
|
-
cost,
|
|
305
|
-
models: [...models],
|
|
306
|
-
toolCalls,
|
|
307
|
-
retries,
|
|
308
|
-
cacheHits,
|
|
309
|
-
incomplete,
|
|
310
|
-
truncatedTrips,
|
|
311
|
-
compactions,
|
|
312
|
-
skippedCompactions,
|
|
313
|
-
providerCompactions
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
/** Content-free snapshot; never retain prompts, completions or tool arguments/results. */
|
|
317
|
-
function snapshotSpan(span) {
|
|
318
|
-
return {
|
|
319
|
-
spanId: span.spanId,
|
|
320
|
-
parentSpanId: span.parentSpanId,
|
|
321
|
-
traceId: span.traceId,
|
|
322
|
-
sessionId: span.sessionId,
|
|
323
|
-
name: span.name,
|
|
324
|
-
version: span.version,
|
|
325
|
-
type: span.type,
|
|
326
|
-
status: span.status,
|
|
327
|
-
startedAt: span.startedAt,
|
|
328
|
-
endedAt: span.endedAt,
|
|
329
|
-
duration: span.duration,
|
|
330
|
-
usage: structuredClone(span.usage),
|
|
331
|
-
error: span.error ? {
|
|
332
|
-
type: span.error.type,
|
|
333
|
-
message: span.error.message
|
|
334
|
-
} : void 0,
|
|
335
|
-
attributes: toSafeValue(span.attributes),
|
|
336
|
-
children: span.children.map(snapshotSpan)
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
/**
|
|
340
|
-
* Optional, lazy integration. Retains only traces collected after devtools boots,
|
|
341
|
-
* using Panoptic's bounded query store; existing exporter/cache stores stay independent.
|
|
342
|
-
*/
|
|
343
|
-
async function attachAiSource(capacity, deps = {}) {
|
|
344
|
-
const aiPackage = "@warlock.js/ai";
|
|
345
|
-
const load = deps.load ?? ((name) => name === "@warlock.js/ai-panoptic" ? import("@warlock.js/ai-panoptic") : import(aiPackage));
|
|
346
|
-
const version = deps.version ?? ((name) => require_app_versions.installedVersion(name, process.cwd(), {}.resolve));
|
|
347
|
-
let panoptic;
|
|
348
|
-
try {
|
|
349
|
-
panoptic = await load("@warlock.js/ai-panoptic");
|
|
350
|
-
if (typeof panoptic.subscribeTraces !== "function") throw new Error("Trace subscription unavailable");
|
|
351
|
-
} catch (error) {
|
|
352
|
-
const aiVersion = version("@warlock.js/ai");
|
|
353
|
-
const panopticVersion = version("@warlock.js/ai-panoptic");
|
|
354
|
-
if (aiVersion === null) return {
|
|
355
|
-
...describeAiUnavailable("ai-missing"),
|
|
356
|
-
dispose() {}
|
|
357
|
-
};
|
|
358
|
-
if (panopticVersion === null) return {
|
|
359
|
-
...describeAiUnavailable("panoptic-missing"),
|
|
360
|
-
dispose() {}
|
|
361
|
-
};
|
|
362
|
-
return {
|
|
363
|
-
...describeAiUnavailable("panoptic-failed", `${redactPaths((error instanceof Error ? error.message : String(error)).split("\n")[0] ?? "").slice(0, 300)} (@warlock.js/ai ${aiVersion}, @warlock.js/ai-panoptic ${panopticVersion})`),
|
|
364
|
-
dispose() {}
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
let core;
|
|
368
|
-
try {
|
|
369
|
-
core = await load("@warlock.js/ai");
|
|
370
|
-
} catch {
|
|
371
|
-
core = void 0;
|
|
372
|
-
}
|
|
373
|
-
const observationOff = () => typeof core?.isObserveAll === "function" && typeof core.getObservers === "function" && !core.isObserveAll() && core.getObservers().length === 0;
|
|
374
|
-
const { currentRequestId } = await Promise.resolve().then(() => require("./current-request-id-CeQhRz9Q.cjs")).then((n) => n.current_request_id_exports);
|
|
375
|
-
const store = panoptic.createInMemoryTraceStore({ capacity });
|
|
376
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
377
|
-
const detach = panoptic.subscribeTraces((trace) => {
|
|
378
|
-
const requestId = currentRequestId() ?? trace.requestId;
|
|
379
|
-
store.add({
|
|
380
|
-
...trace,
|
|
381
|
-
requestId,
|
|
382
|
-
usage: structuredClone(trace.usage),
|
|
383
|
-
root: snapshotSpan(trace.root)
|
|
384
|
-
});
|
|
385
|
-
for (const listener of listeners) try {
|
|
386
|
-
listener({
|
|
387
|
-
traceId: trace.traceId,
|
|
388
|
-
requestId
|
|
389
|
-
});
|
|
390
|
-
} catch {}
|
|
391
|
-
});
|
|
392
|
-
return {
|
|
393
|
-
available: true,
|
|
394
|
-
observationOff,
|
|
395
|
-
store,
|
|
396
|
-
summarize: (trace) => summarizeAiTrace(trace, panoptic.totalCostUsd(trace.usage)),
|
|
397
|
-
subscribe(listener) {
|
|
398
|
-
listeners.add(listener);
|
|
399
|
-
return () => {
|
|
400
|
-
listeners.delete(listener);
|
|
401
|
-
};
|
|
402
|
-
},
|
|
403
|
-
dispose() {
|
|
404
|
-
detach();
|
|
405
|
-
listeners.clear();
|
|
406
|
-
store.clear();
|
|
407
|
-
}
|
|
408
|
-
};
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
//#endregion
|
|
412
|
-
Object.defineProperty(exports, "AGENT_TRACE_INSTALL_GUIDANCE", {
|
|
413
|
-
enumerable: true,
|
|
414
|
-
get: function () {
|
|
415
|
-
return AGENT_TRACE_INSTALL_GUIDANCE;
|
|
416
|
-
}
|
|
417
|
-
});
|
|
418
|
-
Object.defineProperty(exports, "attachAgentTraceSource", {
|
|
419
|
-
enumerable: true,
|
|
420
|
-
get: function () {
|
|
421
|
-
return attachAgentTraceSource;
|
|
422
|
-
}
|
|
423
|
-
});
|
|
424
|
-
Object.defineProperty(exports, "attachAiSource", {
|
|
425
|
-
enumerable: true,
|
|
426
|
-
get: function () {
|
|
427
|
-
return attachAiSource;
|
|
428
|
-
}
|
|
429
|
-
});
|
|
430
|
-
Object.defineProperty(exports, "describeAiUnavailable", {
|
|
431
|
-
enumerable: true,
|
|
432
|
-
get: function () {
|
|
433
|
-
return describeAiUnavailable;
|
|
434
|
-
}
|
|
435
|
-
});
|
|
436
|
-
Object.defineProperty(exports, "resolveUiRoot", {
|
|
437
|
-
enumerable: true,
|
|
438
|
-
get: function () {
|
|
439
|
-
return resolveUiRoot;
|
|
440
|
-
}
|
|
441
|
-
});
|
|
442
|
-
Object.defineProperty(exports, "toSafeValue", {
|
|
443
|
-
enumerable: true,
|
|
444
|
-
get: function () {
|
|
445
|
-
return toSafeValue;
|
|
446
|
-
}
|
|
447
|
-
});
|
|
448
|
-
//# sourceMappingURL=ai-source-BdvMfyKw.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ai-source-BdvMfyKw.cjs","names":["existsSync","path","readFileSync","fileURLToPath","installedVersion"],"sources":["../../../../../../../packages/devtools/src/ui-root.ts","../../../../../../../packages/devtools/src/sources/agent-trace-source.ts","../../../../../../../packages/devtools/src/safe-value.ts","../../../../../../../packages/devtools/src/sources/ai-source.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet cachedUiRoot: string | undefined;\n\n/**\n * Whether `dir` is this package's root: it has the built dashboard\n * (`ui/dashboard/index.html`) or, before the first build, the Processes panel\n * view (`ui/panels/processes.js`), beside a `package.json` named\n * `@warlock.js/devtools`.\n */\nfunction isPackageRoot(dir: string): boolean {\n const hasUi =\n existsSync(path.join(dir, \"ui\", \"dashboard\", \"index.html\")) ||\n existsSync(path.join(dir, \"ui\", \"panels\", \"processes.js\"));\n const packageJson = path.join(dir, \"package.json\");\n\n if (!hasUi || !existsSync(packageJson)) {\n return false;\n }\n\n try {\n const parsed = JSON.parse(readFileSync(packageJson, \"utf8\")) as { name?: string };\n return parsed.name === \"@warlock.js/devtools\";\n } catch {\n return false;\n }\n}\n\n/**\n * Locate this package's `ui/` directory by walking up from the current\n * module's directory. Works from `src/` in development and from the built\n * `esm/`/`cjs/` output, since both sit beside `ui/` and `package.json` at\n * the package root.\n */\nexport function resolveUiRoot(): string {\n if (cachedUiRoot) {\n return cachedUiRoot;\n }\n\n let dir = path.dirname(fileURLToPath(import.meta.url));\n\n while (true) {\n if (isPackageRoot(dir)) {\n cachedUiRoot = path.join(dir, \"ui\");\n return cachedUiRoot;\n }\n\n const parent = path.dirname(dir);\n if (parent === dir) {\n throw new Error(\n \"Could not locate the devtools UI directory: no ancestor of \" +\n \"this module has ui/dashboard/index.html or ui/panels/processes.js beside a package.json named \" +\n \"@warlock.js/devtools.\",\n );\n }\n\n dir = parent;\n }\n}\n","import type { DevtoolsDisposer } from \"../types\";\n\n/**\n * Key `@warlock.js/ai` publishes its agent trace store under on\n * `globalThis`. Reading the store from the registry, not by importing the\n * package, keeps devtools free of an AI dependency and shares one store\n * even when two copies of the package are installed.\n */\nexport const AGENT_TRACES_KEY = Symbol.for(\"@warlock.js/ai.agentTraces\");\n\nexport const AGENT_TRACE_INSTALL_GUIDANCE =\n \"No agent traces yet. Install @warlock.js/ai 5.38 or newer and run an agent in development (agents record traces by default there; `trace: true` turns it on elsewhere), then reload.\";\n\n/** The part of `@warlock.js/ai`'s `AgentTrace` this panel reads; the rest passes through untouched. */\nexport type DevtoolsAgentTrace = {\n runId: string;\n agent: string;\n status: string;\n startedAt: string;\n durationMs?: number;\n model: { name: string; provider: string };\n usage: { input: number; output: number; total: number };\n cost?: number;\n turns: Array<{ toolCalls: Array<{ refusal?: string }> }>;\n};\n\n/** The part of `@warlock.js/ai`'s `AgentTraceStore` devtools uses. */\nexport type DevtoolsAgentTraceStore = {\n get(runId: string): DevtoolsAgentTrace | undefined;\n list(filter?: { limit?: number }): DevtoolsAgentTrace[];\n subscribe(listener: (event: { runId: string; status: string }) => void): () => void;\n};\n\nexport type DevtoolsAgentTraceEvent = { runId: string; status: string; requestId?: string };\n\n/** One row of the run list. */\nexport type DevtoolsAgentRun = {\n runId: string;\n agent: string;\n status: string;\n startedAt: string;\n durationMs?: number;\n model: string;\n turns: number;\n toolCalls: number;\n refusals: number;\n usage: { input: number; output: number };\n cost?: number;\n requestId?: string;\n};\n\n/** Reads agent traces from the shared store; the connector builds one in development only. */\nexport type DevtoolsAgentTraceSource = {\n /** `false` until `@warlock.js/ai` has created its store in this process. */\n available(): boolean;\n list(filter?: { requestId?: string }): DevtoolsAgentRun[];\n get(runId: string): DevtoolsAgentTrace | undefined;\n subscribe(listener: (event: DevtoolsAgentTraceEvent) => void): DevtoolsDisposer;\n dispose: DevtoolsDisposer;\n};\n\n/** One list row for a trace. */\nexport function summarizeAgentTrace(\n trace: DevtoolsAgentTrace,\n requestId?: string,\n): DevtoolsAgentRun {\n let toolCalls = 0;\n let refusals = 0;\n\n for (const turn of trace.turns) {\n toolCalls += turn.toolCalls.length;\n refusals += turn.toolCalls.filter((call) => call.refusal !== undefined).length;\n }\n\n return {\n runId: trace.runId,\n agent: trace.agent,\n status: trace.status,\n startedAt: trace.startedAt,\n durationMs: trace.durationMs,\n model: `${trace.model.provider}/${trace.model.name}`,\n turns: trace.turns.length,\n toolCalls,\n refusals,\n usage: { input: trace.usage.input, output: trace.usage.output },\n cost: trace.cost,\n ...(requestId ? { requestId } : {}),\n };\n}\n\nconst MAX_REQUEST_LINKS = 500;\n\n/**\n * Attach to the shared agent trace store. The store is looked up lazily on\n * every call, so it works whichever of devtools and `@warlock.js/ai` loads\n * first. Runs are linked to the HTTP request that was active when the\n * store first reported them.\n */\nexport async function attachAgentTraceSource(): Promise<DevtoolsAgentTraceSource> {\n const { currentRequestId } = await import(\"../current-request-id\");\n const listeners = new Set<(event: DevtoolsAgentTraceEvent) => void>();\n const requestIds = new Map<string, string>();\n let attachedStore: DevtoolsAgentTraceStore | undefined;\n let detach: (() => void) | undefined;\n\n const findStore = (): DevtoolsAgentTraceStore | undefined => {\n const store = (globalThis as { [AGENT_TRACES_KEY]?: DevtoolsAgentTraceStore })[\n AGENT_TRACES_KEY\n ];\n\n return store && typeof store.list === \"function\" ? store : undefined;\n };\n\n const ensureAttached = (): DevtoolsAgentTraceStore | undefined => {\n const store = findStore();\n\n if (store && store !== attachedStore) {\n detach?.();\n attachedStore = store;\n detach = store.subscribe((event) => {\n // Read the request id before anything asynchronous: the store\n // publishes synchronously from inside the agent run.\n let requestId = requestIds.get(event.runId);\n\n if (!requestId) {\n requestId = currentRequestId();\n\n if (requestId) {\n requestIds.set(event.runId, requestId);\n\n if (requestIds.size > MAX_REQUEST_LINKS) {\n const oldest = requestIds.keys().next();\n\n if (!oldest.done) requestIds.delete(oldest.value);\n }\n }\n }\n\n for (const listener of listeners) {\n try {\n listener({ ...event, ...(requestId ? { requestId } : {}) });\n } catch {\n /* isolate clients */\n }\n }\n });\n }\n\n return store;\n };\n\n ensureAttached();\n\n return {\n available: () => ensureAttached() !== undefined,\n\n list(filter) {\n const store = ensureAttached();\n\n if (!store) return [];\n\n return store\n .list()\n .map((trace) => summarizeAgentTrace(trace, requestIds.get(trace.runId)))\n .filter((run) => filter?.requestId === undefined || run.requestId === filter.requestId);\n },\n\n get: (runId) => ensureAttached()?.get(runId),\n\n subscribe(listener) {\n ensureAttached();\n listeners.add(listener);\n\n return () => {\n listeners.delete(listener);\n };\n },\n\n dispose() {\n detach?.();\n detach = undefined;\n attachedStore = undefined;\n listeners.clear();\n requestIds.clear();\n },\n };\n}\n","const MAX_DEPTH = 6;\n\n/**\n * A JSON-safe snapshot of a value devtools keeps for later display.\n *\n * Log contexts and phase attributes are app data: they can hold live objects\n * (a request, its socket) whose graphs are circular and which must not be kept\n * alive by the collector anyway. Plain objects and arrays are copied; anything\n * with a `toJSON()` is serialized through it; other class instances collapse\n * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to\n * `[Object]` / `[Array]`.\n */\nexport function toSafeValue(value: unknown): unknown {\n return snapshot(value, 0, new WeakSet());\n}\n\nfunction snapshot(value: unknown, depth: number, seen: WeakSet<object>): unknown {\n if (value === null || value === undefined) return value;\n\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"symbol\":\n return value.toString();\n case \"function\":\n return undefined;\n }\n\n const object = value as object;\n\n if (seen.has(object)) return \"[Circular]\";\n if (value instanceof Date)\n return Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n if (value instanceof Error) return { name: value.name, message: value.message };\n\n if (depth >= MAX_DEPTH) return Array.isArray(value) ? \"[Array]\" : \"[Object]\";\n\n seen.add(object);\n\n try {\n if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));\n\n const prototype = Object.getPrototypeOf(object);\n\n if (prototype !== Object.prototype && prototype !== null) {\n const toJSON = (object as { toJSON?: unknown }).toJSON;\n\n if (typeof toJSON === \"function\") {\n try {\n return snapshot(toJSON.call(object), depth + 1, seen);\n } catch {\n return `[${constructorName(object)}]`;\n }\n }\n\n return `[${constructorName(object)}]`;\n }\n\n const copy: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(object)) {\n const safe = snapshot(entry, depth + 1, seen);\n if (safe !== undefined) copy[key] = safe;\n }\n\n return copy;\n } finally {\n seen.delete(object);\n }\n}\n\nfunction constructorName(object: object): string {\n return (object as { constructor?: { name?: string } }).constructor?.name || \"Object\";\n}\n","import type { Trace, TraceSpan, TraceStoreContract } from \"@warlock.js/ai-panoptic\";\nimport { installedVersion } from \"../app-versions\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsDisposer } from \"../types\";\n\nexport type DevtoolsAiUnavailableReason =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\";\n\n/** Why the AI tab is empty, as sent to the dashboard: a title, one line and an optional command. */\nexport type DevtoolsAiUnavailable = {\n available: false;\n reason: DevtoolsAiUnavailableReason;\n title: string;\n message: string;\n command?: string;\n detail?: string;\n};\n\n/** Replaces absolute file paths in an error line with their package-relative part, or `<path>`. */\nexport function redactPaths(text: string): string {\n return text.replace(/(?:file:\\/\\/)?(?:[A-Za-z]:)?[\\\\/][^\\s'\"`()]*/g, (match) => {\n const normalized = match.replace(/^file:\\/\\//, \"\").replaceAll(\"\\\\\", \"/\");\n const index = normalized.lastIndexOf(\"node_modules/\");\n\n return index === -1 ? \"<path>\" : normalized.slice(index + \"node_modules/\".length);\n });\n}\n\nconst OBSERVATION_COMMAND = \"ai.config({ panoptic: { observeAll: true } })\";\n\n/** The answer for each reason; `detail` carries the load error and versions for `panoptic-failed`. */\nexport function describeAiUnavailable(\n reason: DevtoolsAiUnavailableReason,\n detail?: string,\n): DevtoolsAiUnavailable {\n switch (reason) {\n case \"ai-missing\":\n return {\n available: false,\n reason,\n title: \"AI isn't installed\",\n message: \"Add @warlock.js/ai to see AI runs here.\",\n command: \"warlock add ai\",\n };\n case \"panoptic-missing\":\n return {\n available: false,\n reason,\n title: \"Panoptic isn't installed\",\n message: \"Your app uses @warlock.js/ai. Add Panoptic to see its runs.\",\n command: \"warlock add ai-panoptic\",\n };\n case \"panoptic-failed\":\n return {\n available: false,\n reason,\n title: \"Panoptic could not be loaded\",\n message:\n \"Panoptic is installed but failed to load. Check that both packages share a version.\",\n detail,\n };\n case \"not-collected\":\n return {\n available: false,\n reason,\n title: \"AI runs are not collected here\",\n message:\n \"The production dashboard does not collect AI runs. Open the AI tab in development (warlock dev) to see them.\",\n };\n case \"observation-off\":\n return {\n available: false,\n reason,\n title: \"AI observation is off\",\n message: \"Turn it on in src/config/ai.ts, then restart warlock dev.\",\n command: OBSERVATION_COMMAND,\n };\n }\n}\n\n/** Test seam: how packages are loaded and their versions read. */\nexport type AiSourceDeps = {\n load?: (name: string) => Promise<unknown>;\n version?: (name: string) => string | null;\n};\n\nexport type DevtoolsAiEvent = { traceId: string; requestId?: string };\n\n/** Only the connector's development branch constructs this source. */\nexport type DevtoolsAiSource =\n | (DevtoolsAiUnavailable & { dispose: DevtoolsDisposer })\n | {\n available: true;\n /** True when `@warlock.js/ai` has no `observeAll` and no registered observer (read per request). */\n observationOff?: () => boolean;\n store: TraceStoreContract;\n summarize: (trace: Trace) => DevtoolsAiRun;\n subscribe: (listener: (event: DevtoolsAiEvent) => void) => DevtoolsDisposer;\n dispose: DevtoolsDisposer;\n };\n\nexport type DevtoolsAiRun = {\n traceId: string;\n requestId?: string;\n sessionId?: string;\n name: string;\n status: TraceSpan[\"status\"];\n startedAt: string;\n duration: number;\n usage: Trace[\"usage\"];\n cost?: number;\n models: string[];\n toolCalls: number;\n retries: number;\n cacheHits?: number;\n incomplete: boolean;\n truncatedTrips: number;\n compactions: number;\n skippedCompactions: number;\n providerCompactions: number;\n};\n\n/** Summaries use root usage once: nested spans already roll up into it. */\nexport function summarizeAiTrace(trace: Trace, cost?: number): DevtoolsAiRun {\n const models = new Set<string>();\n let toolCalls = 0;\n let retries = 0;\n let cacheHits: number | undefined;\n let incomplete = false;\n let truncatedTrips = 0;\n let compactions = 0;\n let skippedCompactions = 0;\n let providerCompactions = 0;\n const visit = (span: TraceSpan): void => {\n const attributes = span.attributes ?? {};\n const model = attributes[\"agent.model.name\"];\n const provider = attributes[\"agent.model.provider\"];\n if (typeof model === \"string\")\n models.add(typeof provider === \"string\" ? `${provider}/${model}` : model);\n if (span.type === \"tool\") toolCalls += 1;\n if (typeof attributes.retries === \"number\") retries += attributes.retries;\n if (typeof attributes[\"agent.cacheHits\"] === \"number\")\n cacheHits = (cacheHits ?? 0) + attributes[\"agent.cacheHits\"];\n if (typeof attributes[\"agent.truncatedTrips\"] === \"number\")\n truncatedTrips += attributes[\"agent.truncatedTrips\"];\n if (typeof attributes[\"agent.providerCompactions\"] === \"number\")\n providerCompactions += attributes[\"agent.providerCompactions\"];\n if (Array.isArray(attributes[\"agent.compactions\"])) {\n const records: unknown[] = attributes[\"agent.compactions\"];\n for (const record of records) {\n if (typeof record !== \"object\" || record === null || !(\"type\" in record)) continue;\n if (record.type === \"applied\") compactions += 1;\n if (record.type === \"skipped\") skippedCompactions += 1;\n }\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 visit(trace.root);\n return {\n traceId: trace.traceId,\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n name: trace.root.name,\n status: trace.root.status,\n startedAt: trace.startedAt,\n duration: trace.duration,\n usage: trace.usage,\n cost,\n models: [...models],\n toolCalls,\n retries,\n cacheHits,\n incomplete,\n truncatedTrips,\n compactions,\n skippedCompactions,\n providerCompactions,\n };\n}\n\n/** Content-free snapshot; never retain prompts, completions or tool arguments/results. */\nfunction snapshotSpan(span: TraceSpan): TraceSpan {\n return {\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n traceId: span.traceId,\n sessionId: span.sessionId,\n name: span.name,\n version: span.version,\n type: span.type,\n status: span.status,\n startedAt: span.startedAt,\n endedAt: span.endedAt,\n duration: span.duration,\n usage: structuredClone(span.usage),\n error: span.error ? { type: span.error.type, message: span.error.message } : undefined,\n attributes: toSafeValue(span.attributes) as Record<string, unknown> | undefined,\n children: span.children.map(snapshotSpan),\n };\n}\n\n/**\n * Optional, lazy integration. Retains only traces collected after devtools boots,\n * using Panoptic's bounded query store; existing exporter/cache stores stay independent.\n */\nexport async function attachAiSource(\n capacity: number,\n deps: AiSourceDeps = {},\n): Promise<DevtoolsAiSource> {\n const aiPackage: string = \"@warlock.js/ai\"; // not a dependency of devtools: never resolved at build time\n const load =\n deps.load ??\n ((name: string) =>\n name === \"@warlock.js/ai-panoptic\" ? import(\"@warlock.js/ai-panoptic\") : import(aiPackage));\n const version =\n deps.version ?? ((name: string) => installedVersion(name, process.cwd(), import.meta.resolve));\n let panoptic: typeof import(\"@warlock.js/ai-panoptic\");\n try {\n panoptic = (await load(\"@warlock.js/ai-panoptic\")) as typeof panoptic;\n if (typeof panoptic.subscribeTraces !== \"function\")\n throw new Error(\"Trace subscription unavailable\");\n } catch (error) {\n const aiVersion = version(\"@warlock.js/ai\");\n const panopticVersion = version(\"@warlock.js/ai-panoptic\");\n if (aiVersion === null) return { ...describeAiUnavailable(\"ai-missing\"), dispose() {} };\n if (panopticVersion === null)\n return { ...describeAiUnavailable(\"panoptic-missing\"), dispose() {} };\n const text = redactPaths(\n (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0] ?? \"\",\n ).slice(0, 300);\n return {\n ...describeAiUnavailable(\n \"panoptic-failed\",\n `${text} (@warlock.js/ai ${aiVersion}, @warlock.js/ai-panoptic ${panopticVersion})`,\n ),\n dispose() {},\n };\n }\n\n let core: { isObserveAll?: () => boolean; getObservers?: () => readonly unknown[] } | undefined;\n try {\n core = (await load(\"@warlock.js/ai\")) as typeof core;\n } catch {\n core = undefined;\n }\n const observationOff = (): boolean =>\n typeof core?.isObserveAll === \"function\" &&\n typeof core.getObservers === \"function\" &&\n !core.isObserveAll() &&\n core.getObservers().length === 0;\n\n const { currentRequestId } = await import(\"../current-request-id\");\n const store = panoptic.createInMemoryTraceStore({ capacity });\n const listeners = new Set<(event: DevtoolsAiEvent) => void>();\n const detach = panoptic.subscribeTraces((trace) => {\n // Read ALS before any asynchronous exporter work, including for runs that\n // finish after the HTTP response. Never use sessionId as a request id.\n const requestId = currentRequestId() ?? trace.requestId;\n store.add({\n ...trace,\n requestId,\n usage: structuredClone(trace.usage),\n root: snapshotSpan(trace.root),\n });\n for (const listener of listeners) {\n try {\n listener({ traceId: trace.traceId, requestId });\n } catch {\n /* isolate clients */\n }\n }\n });\n\n return {\n available: true,\n observationOff,\n store,\n summarize: (trace) => summarizeAiTrace(trace, panoptic.totalCostUsd(trace.usage)),\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n detach();\n listeners.clear();\n store.clear();\n },\n };\n}\n"],"mappings":";;;;;;;AAIA,IAAI;;;;;;;AAQJ,SAAS,cAAc,KAAsB;CAC3C,MAAM,YACJA,oBAAWC,kBAAK,KAAK,KAAK,MAAM,aAAa,YAAY,CAAC,SAC1DD,oBAAWC,kBAAK,KAAK,KAAK,MAAM,UAAU,cAAc,CAAC;CAC3D,MAAM,cAAcA,kBAAK,KAAK,KAAK,cAAc;CAEjD,IAAI,CAAC,SAAS,KAACD,oBAAW,WAAW,GACnC,OAAO;CAGT,IAAI;EAEF,OADe,KAAK,UAAME,sBAAa,aAAa,MAAM,CAC9C,CAAC,CAAC,SAAS;CACzB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAgB,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K,MAAM;EAC9C,MAAM,IAAI;GACR,GAAG;GACH;GACA,OAAO,gBAAgB,MAAM,KAAK;GAClC,MAAM,aAAa,MAAM,IAAI;EAC/B,CAAC;EACD,KAAK,MAAM,YAAY,WACrB,IAAI;GACF,SAAS;IAAE,SAAS,MAAM;IAAS;GAAU,CAAC;EAChD,QAAQ,CAER;CAEJ,CAAC;CAED,OAAO;EACL,WAAW;EACX;EACA;EACA,YAAY,UAAU,iBAAiB,OAAO,SAAS,aAAa,MAAM,KAAK,CAAC;EAChF,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,OAAO;GACP,UAAU,MAAM;GAChB,MAAM,MAAM;EACd;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"app-versions-DfpPZOI2.cjs","names":["readFileSync","path","fileURLToPath"],"sources":["../../../../../../../packages/devtools/src/production/contracts.ts","../../../../../../../packages/devtools/src/app-versions.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: { name: string; counts: Record<string, number> }[];\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai\", title: \"AI\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n /** The installed `@warlock.js/core` version; `null` when signed out or not found. */\n warlockVersion: string | null;\n /** The app's own `package.json` name and version (nothing else is read); `null` when signed out or not found. */\n app: { name: string; version: string } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** The app's own name and version, as the dashboard shows them at the bottom of the sidebar. */\nexport type DevtoolsAppInfo = { name: string; version: string };\n\n/** The `version` of a `package.json` named `name`, or `null` when the file is not that package's. */\nfunction versionIn(file: string, name: string): string | null {\n try {\n const manifest = JSON.parse(readFileSync(file, \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return manifest.name === name && typeof manifest.version === \"string\" ? manifest.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The installed version of a package, read from its `package.json` without\n * going through its `exports` (published `@warlock.js/core` exports neither\n * `./package.json` nor a `require` condition). It resolves the package's entry\n * and walks up to the `package.json` with that name; when the entry cannot be\n * resolved, it looks in each `node_modules` above `from`. `null` when unknown.\n */\nexport function installedVersion(\n name: string,\n from: string,\n resolve: ((specifier: string) => string) | undefined,\n): string | null {\n try {\n const entry = resolve?.(name);\n\n if (entry !== undefined) {\n let folder = path.dirname(entry.startsWith(\"file:\") ? fileURLToPath(entry) : entry);\n\n for (;;) {\n const version = versionIn(path.join(folder, \"package.json\"), name);\n\n if (version !== null) return version;\n\n const parent = path.dirname(folder);\n\n if (parent === folder) break;\n\n folder = parent;\n }\n }\n } catch {\n // Not resolvable from here: look in the node_modules folders below.\n }\n\n for (let folder = from; ; folder = path.dirname(folder)) {\n const version = versionIn(\n path.join(folder, \"node_modules\", ...name.split(\"/\"), \"package.json\"),\n name,\n );\n\n if (version !== null) return version;\n if (path.dirname(folder) === folder) return null;\n }\n}\n\n/**\n * The app's `name` and `version` from the `package.json` in `root`. Only these\n * two strings are read; `null` when the file is missing, unreadable or lacks\n * either one.\n */\nexport function readAppInfo(root: string): DevtoolsAppInfo | null {\n try {\n const manifest = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n if (\n typeof manifest.name !== \"string\" ||\n typeof manifest.version !== \"string\" ||\n manifest.name === \"\" ||\n manifest.version === \"\"\n ) {\n return null;\n }\n\n return { name: manifest.name.slice(0, 100), version: manifest.version.slice(0, 50) };\n } catch {\n return null;\n }\n}\n\ntype Versions = { warlockVersion: string | null; app: DevtoolsAppInfo | null };\n\nlet cached: Versions | undefined;\n\n/**\n * The installed `@warlock.js/core` version and the app's name and version,\n * read once per process (`root` defaults to the working directory) and kept.\n */\nexport function readVersions(root: string = process.cwd()): Versions {\n cached ??= {\n warlockVersion: installedVersion(\n \"@warlock.js/core\",\n root,\n typeof import.meta.resolve === \"function\"\n ? (specifier: string) => import.meta.resolve(specifier)\n : undefined,\n ),\n app: readAppInfo(root),\n };\n\n return cached;\n}\n\n/** Forgets the cached versions (for tests). */\nexport function resetVersionsCache(): void {\n cached = undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;;;;AAgXA,MAAa,2BAA2B;CACtC;EAAE,IAAI;EAAY,OAAO;EAAY,YAAY;CAAK;CACtD;EAAE,IAAI;EAAW,OAAO;EAAW,YAAY;CAAK;CACpD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAa,OAAO;EAAa,YAAY;CAAK;CACxD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAM;CAC/C;EAAE,IAAI;EAAM,OAAO;EAAM,YAAY;CAAM;CAC3C;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAM;CACnD;EAAE,IAAI;EAAO,OAAO;EAAO,YAAY;CAAM;AAC/C;;AAwMA,MAAa,+BAA6D;CACxE;CACA;CACA;AACF;;;;;ACloBA,SAAS,UAAU,MAAc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SAAgB,aAAa,OAAe,QAAQ,IAAI,GAAa;CACnE,WAAW;EACT,gBAAgB,iBACd,oBACA,MACA,UAAmB,YAAY,cAC1B,mBAAkC,QAAQ,SAAS,IACpD,MACN;EACA,KAAK,YAAY,IAAI;CACvB;CAEA,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"boot-nczSvJ_F.cjs","names":["resolveProductionOptions","DevtoolsProductionConfigError","productionPanels"],"sources":["../../../../../../../packages/devtools/src/production/boot.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport { type MountedDevtoolsPanel, productionPanels } from \"../panels\";\nimport type { MountDevtoolsRoutesDeps } from \"../server/types\";\nimport type { DevtoolsDisposer, ResolvedDevtoolsOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport type { DevtoolsInsights } from \"./insights/types\";\nimport { resolveProductionOptions } from \"./options\";\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\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<DevtoolsDisposer> {\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, panels } = productionPanels(input.panels, production.panels);\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 collector: capture.collector,\n options,\n isDevelopment: () => false,\n },\n production,\n store,\n auth,\n capture,\n insights,\n instance,\n panels,\n builtInPanels: builtIn,\n state,\n warn,\n hmac: (value) => crypto.hmac(value),\n });\n\n 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 return () => {\n for (const stop of stops.splice(0).reverse()) {\n try {\n void Promise.resolve(stop()).catch(() => undefined);\n } catch {\n // Shutdown continues past a failing step.\n }\n }\n\n void capture.dispose().catch(() => undefined);\n };\n}\n"],"mappings":";;;;;;AA6BA,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,OAC2B;CAC3B,MAAM,EAAE,SAAS,KAAK,QAAQ,QAAQ;CACtC,MAAM,aAAaA,yCAAyB,QAAQ,YAAY,GAAG;CACnE,MAAM,OAAO,MAAM,OAAO;CAG1B,IAAI,CAAC,kBAFc,MAAM,gBAAgB,QAAgB,KAAK,OAAO,IAAI,GAAG,GAE5C,CAAC,gBAAgB,CAAC,GAChD,MAAM,IAAIC,6CAA8B,OAAO;CAGjD,MAAM,CAAC,EAAE,sBAAsB,YAAY,eAAe,gBAAgB,cACxE,MAAM,QAAQ,IAAI;uCAChB;uCACA;uCACA;uCACA;uCACA;CACF,CAAC;CAEH,MAAM,QAAQ,MAAM,mBAAmB,EAAE,QAAQ,WAAW,MAAM,QAAQ,CAAC;CAE3E,MAAM,MAAM,OAAO;CAEnB,MAAM,QAAQ,YAA0B;EACtC,IAAI,KAAK,YAAY,cAAc,OAAO;CAC5C;CACA,IAAI,WAAW,cAAc,OAC3B,KACE,qMACF;CAGF,MAAM,WAAW,eAAe,mBAAmB;CACnD,MAAM,CAAC,QAAQ,YAAY,MAAM,QAAQ,IAAI,CAC3C,WAAW,sBAAsB,GACjC,WAAW,qBAAqB,CAClC,CAAC;CACD,MAAM,OAAO,WAAW,mBAAmB;EACzC;EACA,SAAS;EACT;EACA;EACA;EACA;CACF,CAAC;CAED,MAAM,KAAK,iBAAiB;CAE5B,MAA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