@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
|
@@ -1,13 +1,80 @@
|
|
|
1
|
-
const require_app_versions = require("./app-versions-
|
|
2
|
-
const
|
|
3
|
-
const
|
|
4
|
-
const
|
|
1
|
+
const require_app_versions = require("./app-versions-C_ZyzuvD.cjs");
|
|
2
|
+
const require_errors = require("./errors-DNQ-g49I.cjs");
|
|
3
|
+
const require_extract = require("./extract-8kaX_cUV.cjs");
|
|
4
|
+
const require_runs = require("./runs-DECWPGnq.cjs");
|
|
5
5
|
let node_fs = require("node:fs");
|
|
6
6
|
let node_path = require("node:path");
|
|
7
7
|
node_path = require_app_versions.__toESM(node_path, 1);
|
|
8
|
-
let _warlock_js_logger = require("@warlock.js/logger");
|
|
9
8
|
let node_fs_promises = require("node:fs/promises");
|
|
9
|
+
let _warlock_js_logger = require("@warlock.js/logger");
|
|
10
10
|
|
|
11
|
+
//#region ../../packages/devtools/src/server/ai-report-routes.ts
|
|
12
|
+
/** The answer of a route whose data source is not wired in this mode. */
|
|
13
|
+
const notCollected = () => require_extract.toAiUnavailableView(require_extract.describeAiUnavailable("not-collected"));
|
|
14
|
+
/** Sends a known failure as the dashboard's error body; anything else goes to the error handler. */
|
|
15
|
+
function sendKnown(reply, error) {
|
|
16
|
+
if (error instanceof require_errors.DevtoolsApiError) return reply.code(error.statusCode).send(error.toBody());
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The AI section's report routes, inside the same guard as every panel
|
|
21
|
+
* (development loopback guard, or the production session and access table):
|
|
22
|
+
*
|
|
23
|
+
* - `GET /api/ai/reports` → `DevtoolsAiReportView`
|
|
24
|
+
* - `GET /api/ai/models` → `DevtoolsAiModelsView`
|
|
25
|
+
* - `GET /api/ai/errors` → `DevtoolsAiErrorsView`
|
|
26
|
+
* - `GET /api/ai/evaluate` → `DevtoolsAiEvaluateView`
|
|
27
|
+
* - `POST /api/ai/evaluate` → `DevtoolsAiEvaluateResult` (development only)
|
|
28
|
+
*
|
|
29
|
+
* Every answer is `Cache-Control: no-store`. Without `deps.aiReports` the
|
|
30
|
+
* report routes answer the `not-collected` view; with an unavailable one they
|
|
31
|
+
* answer it. Without `deps.aiEvaluator` both evaluate routes answer
|
|
32
|
+
* `not-collected` (GET) / `ai.evaluate-unavailable` (POST).
|
|
33
|
+
*/
|
|
34
|
+
function registerAiReportRoutes(server, deps) {
|
|
35
|
+
for (const [route, view] of [
|
|
36
|
+
["/api/ai/reports", "report"],
|
|
37
|
+
["/api/ai/models", "models"],
|
|
38
|
+
["/api/ai/errors", "errors"]
|
|
39
|
+
]) server.get(route, async (request, reply) => {
|
|
40
|
+
reply.header("Cache-Control", "no-store");
|
|
41
|
+
const reports = deps.aiReports;
|
|
42
|
+
if (!reports) return notCollected();
|
|
43
|
+
if (!reports.available) {
|
|
44
|
+
const { dispose: _dispose, ...unavailable } = reports;
|
|
45
|
+
return unavailable;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
return await reports.service[view](request.query);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
return sendKnown(reply, error);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
server.get("/api/ai/evaluate", async (_request, reply) => {
|
|
54
|
+
reply.header("Cache-Control", "no-store");
|
|
55
|
+
if (!deps.aiEvaluator) return notCollected();
|
|
56
|
+
return deps.aiEvaluator.view();
|
|
57
|
+
});
|
|
58
|
+
if (deps.mode === "production") return;
|
|
59
|
+
server.post("/api/ai/evaluate", async (request, reply) => {
|
|
60
|
+
reply.header("Cache-Control", "no-store");
|
|
61
|
+
try {
|
|
62
|
+
if (!deps.aiEvaluator) throw new require_errors.DevtoolsApiError("ai.evaluate-unavailable");
|
|
63
|
+
const body = request.body;
|
|
64
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) throw new require_errors.DevtoolsApiError("input.invalid");
|
|
65
|
+
const { runId, systemPrompt, instructions } = body;
|
|
66
|
+
return await deps.aiEvaluator.evaluate({
|
|
67
|
+
...runId === void 0 ? {} : { runId },
|
|
68
|
+
...systemPrompt === void 0 ? {} : { systemPrompt },
|
|
69
|
+
...instructions === void 0 ? {} : { instructions }
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return sendKnown(reply, error);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
11
78
|
//#region ../../packages/devtools/src/server/ai-routes.ts
|
|
12
79
|
/** Read-only AI metadata, inside the same development/loopback guard as every panel. */
|
|
13
80
|
function registerAiRoutes(server, deps) {
|
|
@@ -18,7 +85,7 @@ function registerAiRoutes(server, deps) {
|
|
|
18
85
|
if (!source) {
|
|
19
86
|
const reason = deps.mode === "production" ? "not-collected" : "ai-missing";
|
|
20
87
|
return {
|
|
21
|
-
...
|
|
88
|
+
...require_extract.describeAiUnavailable(reason),
|
|
22
89
|
runs: []
|
|
23
90
|
};
|
|
24
91
|
}
|
|
@@ -31,7 +98,7 @@ function registerAiRoutes(server, deps) {
|
|
|
31
98
|
const filter = request.query.requestId === void 0 ? void 0 : { requestId: request.query.requestId };
|
|
32
99
|
const runs = source.store.query(filter).map(source.summarize);
|
|
33
100
|
if (!runs.length && filter === void 0 && source.observationOff?.()) return {
|
|
34
|
-
...
|
|
101
|
+
...require_extract.describeAiUnavailable("observation-off"),
|
|
35
102
|
runs: []
|
|
36
103
|
};
|
|
37
104
|
return {
|
|
@@ -40,12 +107,31 @@ function registerAiRoutes(server, deps) {
|
|
|
40
107
|
aggregate: source.store.aggregate(filter)
|
|
41
108
|
};
|
|
42
109
|
});
|
|
110
|
+
server.get("/api/ai/runs", async (request, reply) => {
|
|
111
|
+
reply.header("Cache-Control", "no-store");
|
|
112
|
+
const source = deps.ai;
|
|
113
|
+
if (!source) return require_extract.toAiUnavailableView(require_extract.describeAiUnavailable(deps.mode === "production" ? "not-collected" : "ai-missing"));
|
|
114
|
+
if (!source.available) {
|
|
115
|
+
const { dispose: _dispose, ...unavailable } = source;
|
|
116
|
+
return require_extract.toAiUnavailableView(unavailable);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
return require_runs.listAiRuns(source.store.query(), request.query, {
|
|
120
|
+
totalCost: source.totalCost,
|
|
121
|
+
capacity: deps.options.maxRequests,
|
|
122
|
+
helpers: source.helpers
|
|
123
|
+
});
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error instanceof require_errors.DevtoolsApiError) return reply.code(error.statusCode).send(error.toBody());
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
43
129
|
server.get("/api/ai/agent-runs", async (request, reply) => {
|
|
44
130
|
reply.header("Cache-Control", "no-store");
|
|
45
131
|
const source = deps.agentTraces;
|
|
46
132
|
if (!source?.available()) return {
|
|
47
133
|
available: false,
|
|
48
|
-
message:
|
|
134
|
+
message: require_runs.AGENT_TRACE_INSTALL_GUIDANCE,
|
|
49
135
|
runs: []
|
|
50
136
|
};
|
|
51
137
|
return {
|
|
@@ -245,7 +331,7 @@ function registerMailRoutes(server, deps) {
|
|
|
245
331
|
|
|
246
332
|
//#endregion
|
|
247
333
|
//#region ../../packages/devtools/src/server/ui-assets.ts
|
|
248
|
-
const uiFile = (name) => () => node_path.default.join(
|
|
334
|
+
const uiFile = (name) => () => node_path.default.join(require_runs.resolveUiRoot(), name);
|
|
249
335
|
/**
|
|
250
336
|
* The only assets that can be requested. The request's asset name is looked
|
|
251
337
|
* up here and never joined into a filesystem path.
|
|
@@ -300,7 +386,7 @@ function registerUiAssets(server, options = {}) {
|
|
|
300
386
|
reply.code(308).header("Cache-Control", "no-store").redirect(`${base}/${search === void 0 ? "" : `?${search}`}`, 308);
|
|
301
387
|
return;
|
|
302
388
|
}
|
|
303
|
-
const index = node_path.default.join(
|
|
389
|
+
const index = node_path.default.join(require_runs.resolveUiRoot(), "dashboard", "index.html");
|
|
304
390
|
if (!(0, node_fs.existsSync)(index)) {
|
|
305
391
|
reply.code(503).header("Cache-Control", "no-store").header("Content-Type", "text/html; charset=utf-8").send(NOT_BUILT_HTML);
|
|
306
392
|
return;
|
|
@@ -308,18 +394,15 @@ function registerUiAssets(server, options = {}) {
|
|
|
308
394
|
reply.header("Cache-Control", "no-store").header("Content-Type", "text/html; charset=utf-8").send((0, node_fs.readFileSync)(index));
|
|
309
395
|
};
|
|
310
396
|
server.get("/", serveIndex);
|
|
311
|
-
server.get("/assets/:name", (request, reply) => {
|
|
397
|
+
server.get("/assets/:name", async (request, reply) => {
|
|
312
398
|
const asset = Object.hasOwn(UI_ASSETS, request.params.name) ? UI_ASSETS[request.params.name] : void 0;
|
|
313
399
|
const file = asset?.file();
|
|
314
400
|
if (!asset || !file || !(0, node_fs.existsSync)(file)) {
|
|
315
|
-
if (options.notFound)
|
|
316
|
-
|
|
317
|
-
return;
|
|
318
|
-
}
|
|
319
|
-
reply.code(404).header("Cache-Control", "no-store").send();
|
|
320
|
-
return;
|
|
401
|
+
if (options.notFound) return options.notFound(request, reply);
|
|
402
|
+
return reply.code(404).header("Cache-Control", "no-store").send();
|
|
321
403
|
}
|
|
322
404
|
sendFile(reply, file, asset.contentType);
|
|
405
|
+
return reply;
|
|
323
406
|
});
|
|
324
407
|
}
|
|
325
408
|
|
|
@@ -347,10 +430,10 @@ function registerOpenApiRoutes(server, deps) {
|
|
|
347
430
|
});
|
|
348
431
|
const frameable = (reply) => reply.header("X-Frame-Options", "SAMEORIGIN").header("Content-Security-Policy", "frame-ancestors 'self'");
|
|
349
432
|
server.get("/docs", (_request, reply) => {
|
|
350
|
-
sendFile(frameable(reply), node_path.default.join(
|
|
433
|
+
sendFile(frameable(reply), node_path.default.join(require_runs.resolveUiRoot(), "docs.html"), "text/html; charset=utf-8");
|
|
351
434
|
});
|
|
352
435
|
server.get("/docs/swagger", (_request, reply) => {
|
|
353
|
-
sendFile(frameable(reply), node_path.default.join(
|
|
436
|
+
sendFile(frameable(reply), node_path.default.join(require_runs.resolveUiRoot(), "docs-swagger.html"), "text/html; charset=utf-8");
|
|
354
437
|
});
|
|
355
438
|
}
|
|
356
439
|
|
|
@@ -390,7 +473,7 @@ async function resolvePanelFile(files, requested) {
|
|
|
390
473
|
async function sendPanelFile(panel, requested, request, reply, notFound) {
|
|
391
474
|
const file = panel.files === null ? null : await resolvePanelFile(panel.files, requested);
|
|
392
475
|
if (file === null) return notFound(request, reply);
|
|
393
|
-
reply.header("X-Content-Type-Options", "nosniff").header("Cache-Control", "no-store").header("Content-Type",
|
|
476
|
+
reply.header("X-Content-Type-Options", "nosniff").header("Cache-Control", "no-store").header("Content-Type", require_extract.panelContentType(file));
|
|
394
477
|
return reply.send((0, node_fs.createReadStream)(file));
|
|
395
478
|
}
|
|
396
479
|
/**
|
|
@@ -437,7 +520,7 @@ function registerPanelRoutes(server, panels, options = {}) {
|
|
|
437
520
|
return;
|
|
438
521
|
}
|
|
439
522
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
440
|
-
sendFile(reply, file,
|
|
523
|
+
sendFile(reply, file, require_extract.panelContentType(name));
|
|
441
524
|
});
|
|
442
525
|
}
|
|
443
526
|
|
|
@@ -863,6 +946,12 @@ function registerStreamRoute(server, deps) {
|
|
|
863
946
|
}
|
|
864
947
|
|
|
865
948
|
//#endregion
|
|
949
|
+
Object.defineProperty(exports, "registerAiReportRoutes", {
|
|
950
|
+
enumerable: true,
|
|
951
|
+
get: function () {
|
|
952
|
+
return registerAiReportRoutes;
|
|
953
|
+
}
|
|
954
|
+
});
|
|
866
955
|
Object.defineProperty(exports, "registerAiRoutes", {
|
|
867
956
|
enumerable: true,
|
|
868
957
|
get: function () {
|
|
@@ -947,4 +1036,4 @@ Object.defineProperty(exports, "sendPanelFile", {
|
|
|
947
1036
|
return sendPanelFile;
|
|
948
1037
|
}
|
|
949
1038
|
});
|
|
950
|
-
//# sourceMappingURL=stream-route-
|
|
1039
|
+
//# sourceMappingURL=stream-route-B6WAjbPG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-route-B6WAjbPG.cjs","names":["toAiUnavailableView","describeAiUnavailable","DevtoolsApiError","describeAiUnavailable","toAiUnavailableView","listAiRuns","DevtoolsApiError","AGENT_TRACE_INSTALL_GUIDANCE","DevtoolsApiError","createErrorRef","DevtoolsApiError","path","resolveUiRoot","readFileSync","existsSync","path","resolveUiRoot","path","realpath","stat","panelContentType","createReadStream","DevtoolsApiError"],"sources":["../../../../../../../packages/devtools/src/server/ai-report-routes.ts","../../../../../../../packages/devtools/src/server/ai-routes.ts","../../../../../../../packages/devtools/src/server/explain-route.ts","../../../../../../../packages/devtools/src/server/insights-routes.ts","../../../../../../../packages/devtools/src/server/log-routes.ts","../../../../../../../packages/devtools/src/server/mail-routes.ts","../../../../../../../packages/devtools/src/server/ui-assets.ts","../../../../../../../packages/devtools/src/server/openapi-routes.ts","../../../../../../../packages/devtools/src/server/panel-files.ts","../../../../../../../packages/devtools/src/server/panel-routes.ts","../../../../../../../packages/devtools/src/request-history.ts","../../../../../../../packages/devtools/src/server/requests-routes.ts","../../../../../../../packages/devtools/src/server/route-routes.ts","../../../../../../../packages/devtools/src/server/stream-route.ts"],"sourcesContent":["import type { FastifyInstance, FastifyReply } from \"fastify\";\nimport type { DevtoolsAiRangeQuery } from \"../ai/reports/range\";\nimport { DevtoolsApiError } from \"../production/errors\";\nimport { describeAiUnavailable, toAiUnavailableView } from \"../sources/ai-source\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/** The answer of a route whose data source is not wired in this mode. */\nconst notCollected = () => toAiUnavailableView(describeAiUnavailable(\"not-collected\"));\n\n/** Sends a known failure as the dashboard's error body; anything else goes to the error handler. */\nfunction sendKnown(reply: FastifyReply, error: unknown): FastifyReply {\n if (error instanceof DevtoolsApiError) return reply.code(error.statusCode).send(error.toBody());\n\n throw error;\n}\n\n/**\n * The AI section's report routes, inside the same guard as every panel\n * (development loopback guard, or the production session and access table):\n *\n * - `GET /api/ai/reports` → `DevtoolsAiReportView`\n * - `GET /api/ai/models` → `DevtoolsAiModelsView`\n * - `GET /api/ai/errors` → `DevtoolsAiErrorsView`\n * - `GET /api/ai/evaluate` → `DevtoolsAiEvaluateView`\n * - `POST /api/ai/evaluate` → `DevtoolsAiEvaluateResult` (development only)\n *\n * Every answer is `Cache-Control: no-store`. Without `deps.aiReports` the\n * report routes answer the `not-collected` view; with an unavailable one they\n * answer it. Without `deps.aiEvaluator` both evaluate routes answer\n * `not-collected` (GET) / `ai.evaluate-unavailable` (POST).\n */\nexport function registerAiReportRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n for (const [route, view] of [\n [\"/api/ai/reports\", \"report\"],\n [\"/api/ai/models\", \"models\"],\n [\"/api/ai/errors\", \"errors\"],\n ] as const) {\n server.get<{ Querystring: DevtoolsAiRangeQuery }>(route, async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n\n const reports = deps.aiReports;\n\n if (!reports) return notCollected();\n\n if (!reports.available) {\n const { dispose: _dispose, ...unavailable } = reports;\n\n return unavailable;\n }\n\n try {\n return await reports.service[view](request.query);\n } catch (error) {\n return sendKnown(reply, error);\n }\n });\n }\n\n server.get(\"/api/ai/evaluate\", async (_request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n\n if (!deps.aiEvaluator) return notCollected();\n\n return deps.aiEvaluator.view();\n });\n\n // Evaluate spends a model call and reads prompt text: it exists in development only.\n if (deps.mode === \"production\") return;\n\n server.post<{ Body: unknown }>(\"/api/ai/evaluate\", async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n\n try {\n if (!deps.aiEvaluator) throw new DevtoolsApiError(\"ai.evaluate-unavailable\");\n\n const body = request.body;\n\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const { runId, systemPrompt, instructions } = body as Record<string, unknown>;\n\n return await deps.aiEvaluator.evaluate({\n ...(runId === undefined ? {} : { runId: runId as string }),\n ...(systemPrompt === undefined ? {} : { systemPrompt: systemPrompt as string }),\n ...(instructions === undefined ? {} : { instructions: instructions as string }),\n });\n } catch (error) {\n return sendKnown(reply, error);\n }\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport { listAiRuns, type DevtoolsAiRunsQuery } from \"../ai/reports/runs\";\nimport { DevtoolsApiError } from \"../production/errors\";\nimport { AGENT_TRACE_INSTALL_GUIDANCE } from \"../sources/agent-trace-source\";\nimport { describeAiUnavailable, toAiUnavailableView } from \"../sources/ai-source\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/** Read-only AI metadata, inside the same development/loopback guard as every panel. */\nexport function registerAiRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get<{ Querystring: { requestId?: string } }>(\"/api/ai\", async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n const source = deps.ai;\n if (!source?.available) {\n if (!source) {\n // Production never attaches the feed: say so instead of claiming AI is missing.\n const reason = deps.mode === \"production\" ? \"not-collected\" : \"ai-missing\";\n return { ...describeAiUnavailable(reason), runs: [] };\n }\n const { dispose: _dispose, ...unavailable } = source;\n return { ...unavailable, runs: [] };\n }\n const filter =\n request.query.requestId === undefined ? undefined : { requestId: request.query.requestId };\n const runs = source.store.query(filter).map(source.summarize);\n // Nothing collected and nothing that would collect: say how to turn it on.\n if (!runs.length && filter === undefined && source.observationOff?.()) {\n return { ...describeAiUnavailable(\"observation-off\"), runs: [] };\n }\n return {\n available: true,\n runs,\n aggregate: source.store.aggregate(filter),\n };\n });\n\n // The filtered, grouped and summarised run list the Runs page reads. Production keeps no run details.\n server.get<{ Querystring: DevtoolsAiRunsQuery }>(\"/api/ai/runs\", async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n const source = deps.ai;\n\n if (!source) {\n return toAiUnavailableView(\n describeAiUnavailable(deps.mode === \"production\" ? \"not-collected\" : \"ai-missing\"),\n );\n }\n\n if (!source.available) {\n const { dispose: _dispose, ...unavailable } = source;\n\n return toAiUnavailableView(unavailable);\n }\n\n try {\n return listAiRuns(source.store.query(), request.query, {\n totalCost: source.totalCost,\n capacity: deps.options.maxRequests,\n helpers: source.helpers,\n });\n } catch (error) {\n if (error instanceof DevtoolsApiError)\n return reply.code(error.statusCode).send(error.toBody());\n\n throw error;\n }\n });\n\n // Per-turn agent traces recorded by `@warlock.js/ai` itself (system prompt,\n // tools offered, tool calls, refusals, retries, usage and cost). Unlike the\n // Panoptic feed above, these carry prompt and tool content: they exist for\n // debugging in development and sit behind the same guard.\n server.get<{ Querystring: { requestId?: string } }>(\n \"/api/ai/agent-runs\",\n async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n const source = deps.agentTraces;\n\n if (!source?.available()) {\n return { available: false, message: AGENT_TRACE_INSTALL_GUIDANCE, runs: [] };\n }\n\n return {\n available: true,\n runs: source.list(\n request.query.requestId === undefined\n ? undefined\n : { requestId: request.query.requestId },\n ),\n };\n },\n );\n\n server.get<{ Params: { id: string } }>(\"/api/ai/agent-runs/:id\", async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n const trace = deps.agentTraces?.get(request.params.id);\n\n if (!trace) return reply.code(404).send();\n\n return trace;\n });\n\n server.get<{ Params: { id: string } }>(\"/api/ai/runs/:id\", async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n const source = deps.ai;\n const trace = source?.available ? source.store.get(request.params.id) : undefined;\n if (!trace) return reply.code(404).send();\n return trace;\n });\n}\n","import { log } from \"@warlock.js/logger\";\nimport type { FastifyInstance } from \"fastify\";\nimport { createErrorRef, DevtoolsApiError } from \"../production/errors\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/**\n * The value the logger's redaction substitutes for a censored leaf\n * (`logger/src/redact/redact.ts`, `DEFAULT_CENSOR`). Not exported from\n * `@warlock.js/logger`, so matched by literal here.\n */\nconst REDACTED_PLACEHOLDER = \"[REDACTED]\";\n\nfunction isExplainableSql(sql: string | undefined): boolean {\n return /^\\s*(select|with)\\b/i.test(sql ?? \"\");\n}\n\n/** Registers the EXPLAIN route: Postgres `SELECT`/`WITH` queries only. */\nexport function registerExplainRoute(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.post<{ Params: { requestId: string; queryId: string } }>(\n \"/api/requests/:requestId/queries/:queryId/explain\",\n async (request, reply) => {\n const found = deps.collector.getRequest(request.params.requestId);\n const query = found?.queries.find((item) => item.id === request.params.queryId);\n\n if (!query) {\n reply.code(404).send();\n return;\n }\n\n if (query.driver !== \"postgres\" || !isExplainableSql(query.sql) || !deps.explain) {\n reply.code(400).send({ error: \"Only Postgres SELECT or WITH queries can be explained\" });\n return;\n }\n\n if (query.bindings?.some((binding) => binding === REDACTED_PLACEHOLDER)) {\n reply.code(400).send({ error: \"bindings redacted\" });\n return;\n }\n\n try {\n const plan = await deps.explain(query);\n return { plan };\n } catch (error) {\n reply.code(500).send({ error: error instanceof Error ? error.message : String(error) });\n }\n },\n );\n}\n\n/**\n * Registers `POST /api/queries/:shapeId/explain`: EXPLAIN for a query shape,\n * run by the process that kept an example of it (development and production).\n * A failure answers `{ error, code, ref?, instance? }` with the code's status.\n */\nexport function registerShapeExplainRoute(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n const explainShape = deps.explainShape;\n\n if (!explainShape) return;\n\n server.post<{ Params: { shapeId: string } }>(\n \"/api/queries/:shapeId/explain\",\n async (request, reply) => {\n try {\n return await explainShape(request.params.shapeId);\n } catch (error) {\n if (error instanceof DevtoolsApiError) {\n reply.code(error.statusCode).send(error.toBody());\n return;\n }\n\n const failure = new DevtoolsApiError(\"server.error\", { ref: createErrorRef() });\n\n log.error(\n \"devtools\",\n \"explain\",\n `EXPLAIN route failed (ref ${failure.ref}): ${error instanceof Error ? error.message : String(error)}`,\n );\n reply.code(failure.statusCode).send(failure.toBody());\n }\n },\n );\n}\n","import type { FastifyInstance } from \"fastify\";\nimport { DevtoolsApiError } from \"../production/errors\";\nimport type { DevtoolsInsightQuery, DevtoolsInsights } from \"../production/insights/types\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\ntype InsightsQuerystring = { instance?: string; sort?: string; limit?: string };\n\nconst QUERY_SORTS = [\"total\", \"p95\", \"count\", \"n+1\"] as const;\nconst ROUTE_SORTS = [\"total\", \"p95\", \"count\", \"errors\"] as const;\n\n/**\n * Reads `?instance=&sort=&limit=`. A sort outside `sorts` or a limit that is\n * not a whole number from 1 to 500 answers `input.invalid`.\n */\nexport function parseInsightQuery(\n query: InsightsQuerystring,\n sorts?: readonly string[],\n): DevtoolsInsightQuery {\n const result: DevtoolsInsightQuery = { instance: query.instance || \"all\" };\n\n if (sorts && query.sort !== undefined && query.sort !== \"\") {\n if (!sorts.includes(query.sort)) throw new DevtoolsApiError(\"input.invalid\");\n\n result.sort = query.sort;\n }\n\n if (query.limit !== undefined && query.limit !== \"\") {\n const limit = Number(query.limit);\n\n if (!Number.isInteger(limit) || limit < 1 || limit > 500) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n result.limit = limit;\n }\n\n return result;\n}\n\n/**\n * The read-only routes of the Resources, Queries (statistics), Routes\n * (statistics), Health, Errors, Logs (production) and Jobs tabs, over\n * `deps.insights`: `GET /api/instances`, `/api/resources`,\n * `/api/queries/stats`, `/api/routes/stats`, `/api/health`, `/api/errors`,\n * `/api/jobs`. Each takes `?instance=<id|all>` (default `all`). Without\n * `deps.insights` nothing is registered.\n */\nexport function registerInsightsRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n const insights: DevtoolsInsights | undefined = deps.insights;\n\n if (!insights) return;\n\n const route = (\n path: string,\n sorts: readonly string[] | undefined,\n read: (query: DevtoolsInsightQuery) => Promise<unknown>,\n ): void => {\n server.get<{ Querystring: InsightsQuerystring }>(path, async (request, reply) => {\n const query = parseInsightQuery(request.query, sorts);\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return read(query);\n });\n };\n\n route(\"/api/instances\", undefined, () => insights.instances());\n route(\"/api/resources\", undefined, (query) => insights.resources(query));\n route(\"/api/queries/stats\", QUERY_SORTS, (query) => insights.queryStats(query));\n route(\"/api/routes/stats\", ROUTE_SORTS, (query) => insights.routeStats(query));\n route(\"/api/health\", undefined, (query) => insights.health(query));\n route(\"/api/errors\", undefined, (query) => insights.errors(query));\n route(\"/api/jobs\", undefined, (query) => insights.jobs(query));\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { DevtoolsLogRow } from \"../production/contracts\";\nimport type { DevtoolsLogEntry } from \"../types\";\nimport { parseInsightQuery } from \"./insights-routes\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\ntype LogsQuery = {\n level?: DevtoolsLogEntry[\"level\"];\n module?: string;\n instance?: string;\n limit?: string;\n};\n\n/**\n * Registers the log listing route, filterable by `level` and `module`. In\n * production it answers from the insights (every instance, no `context`);\n * in development it answers from the collector's logs, which keep `context`.\n */\nexport function registerLogRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get<{ Querystring: LogsQuery }>(\"/api/logs\", async (request, reply) => {\n const { level, module } = request.query;\n\n if (deps.mode === \"production\" && deps.insights) {\n const query = parseInsightQuery(request.query);\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return deps.insights.logs({\n ...query,\n ...(level ? { level } : {}),\n ...(module ? { module } : {}),\n });\n }\n\n const rows: DevtoolsLogRow[] = deps.collector.listLogs({ level, module }).map((entry) => ({\n level: entry.level,\n module: entry.module,\n action: entry.action,\n message: entry.message,\n at: entry.at,\n requestId: null,\n instance: null,\n context: entry.context,\n }));\n\n return rows;\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\nconst MAIL_HTML_CSP =\n \"sandbox; default-src 'none'; img-src data: https: http:; style-src 'unsafe-inline'\";\n\n/** Registers the mailbox list, single-mail detail, and mail HTML routes. */\nexport function registerMailRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get(\"/api/mails\", async () => deps.collector.listMails());\n\n server.get<{ Params: { id: string } }>(\"/api/mails/:id\", async (request, reply) => {\n const mail = deps.collector.getMail(request.params.id);\n\n if (!mail) {\n reply.code(404).send();\n return;\n }\n\n const { html, ...rest } = mail;\n return rest;\n });\n\n server.get<{ Params: { id: string } }>(\"/api/mails/:id/html\", async (request, reply) => {\n const mail = deps.collector.getMail(request.params.id);\n\n if (!mail || !mail.html) {\n reply.code(404).send();\n return;\n }\n\n reply\n .header(\"Content-Security-Policy\", MAIL_HTML_CSP)\n .header(\"X-Content-Type-Options\", \"nosniff\")\n .header(\"Content-Type\", \"text/html; charset=utf-8\")\n .send(mail.html);\n });\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { resolveUiRoot } from \"../ui-root\";\n\n/**\n * Where an asset's bytes come from: a file in this package's `ui/` folder.\n */\ntype UiAsset = {\n contentType: string;\n file: () => string;\n};\n\nconst uiFile = (name: string) => () => path.join(resolveUiRoot(), name);\n\n/**\n * The only assets that can be requested. The request's asset name is looked\n * up here and never joined into a filesystem path.\n */\nconst UI_ASSETS: Record<string, UiAsset> = {\n \"app.js\": {\n contentType: \"text/javascript; charset=utf-8\",\n file: uiFile(\"dashboard/assets/app.js\"),\n },\n \"app.css\": { contentType: \"text/css; charset=utf-8\", file: uiFile(\"dashboard/assets/app.css\") },\n \"scalar.js\": {\n contentType: \"text/javascript; charset=utf-8\",\n file: uiFile(\"vendor/scalar/standalone.js\"),\n },\n \"swagger-ui-bundle.js\": {\n contentType: \"text/javascript; charset=utf-8\",\n file: uiFile(\"vendor/swagger-ui/swagger-ui-bundle.js\"),\n },\n \"swagger-ui.css\": {\n contentType: \"text/css; charset=utf-8\",\n file: uiFile(\"vendor/swagger-ui/swagger-ui.css\"),\n },\n \"docs-swagger.js\": {\n contentType: \"text/javascript; charset=utf-8\",\n file: uiFile(\"docs-swagger.js\"),\n },\n};\n\n/** Sends `file` with `contentType` and no caching. */\nexport function sendFile(reply: FastifyReply, file: string, contentType: string): void {\n reply\n .header(\"Cache-Control\", \"no-store\")\n .header(\"Content-Type\", contentType)\n .send(readFileSync(file));\n}\n\nconst NOT_BUILT_HTML =\n \"<!doctype html><title>Warlock Devtools</title><p>The devtools dashboard has not been built. Run <code>pnpm --filter @warlock.js/devtools build:ui</code>.</p>\";\n\n/**\n * Serves the static dashboard: the built `ui/dashboard/index.html` at the\n * dashboard root and the whitelisted assets (`app.js`, `app.css`, the\n * vendored Scalar bundle as `scalar.js`, and the vendored Swagger UI files\n * plus their init script). The asset name is matched against a fixed\n * whitelist — never joined into a filesystem path — so no request can\n * traverse outside it. Before the first `build:ui` the root answers 503 with\n * a note that says how to build. `notFound` answers an unknown asset (the\n * production gate passes its uniform 404, so the public asset route answers\n * like any unknown URL of the app); without it the answer is a bare 404.\n */\nexport function registerUiAssets(\n server: FastifyInstance,\n options: {\n notFound?: (\n request: FastifyRequest,\n reply: FastifyReply,\n ) => FastifyReply | Promise<FastifyReply>;\n } = {},\n): void {\n const serveIndex = (request: FastifyRequest, reply: FastifyReply): void => {\n // The address as sent: core's server drops a trailing slash before routing.\n const [pathname = \"\", search] = (request.originalUrl ?? request.url).split(\"?\");\n\n // The page loads its assets by relative URL, so it must be served from `<path>/`. The target is built from\n // the route, never from the request, so it always stays on the dashboard path.\n if (!pathname.endsWith(\"/\")) {\n const base = (request.routeOptions.url ?? pathname).replace(/\\/+$/, \"\");\n\n reply\n .code(308)\n .header(\"Cache-Control\", \"no-store\")\n .redirect(`${base}/${search === undefined ? \"\" : `?${search}`}`, 308);\n return;\n }\n\n const index = path.join(resolveUiRoot(), \"dashboard\", \"index.html\");\n\n if (!existsSync(index)) {\n reply\n .code(503)\n .header(\"Cache-Control\", \"no-store\")\n .header(\"Content-Type\", \"text/html; charset=utf-8\")\n .send(NOT_BUILT_HTML);\n return;\n }\n\n reply\n .header(\"Cache-Control\", \"no-store\")\n .header(\"Content-Type\", \"text/html; charset=utf-8\")\n .send(readFileSync(index));\n };\n\n server.get(\"/\", serveIndex);\n\n server.get<{ Params: { name: string } }>(\"/assets/:name\", async (request, reply) => {\n const asset = Object.hasOwn(UI_ASSETS, request.params.name)\n ? UI_ASSETS[request.params.name]\n : undefined;\n const file = asset?.file();\n\n if (!asset || !file || !existsSync(file)) {\n if (options.notFound) {\n return options.notFound(request, reply);\n }\n\n return reply.code(404).header(\"Cache-Control\", \"no-store\").send();\n }\n\n sendFile(reply, file, asset.contentType);\n\n return reply;\n });\n}\n","import path from \"node:path\";\nimport type { FastifyInstance, FastifyReply } from \"fastify\";\nimport { resolveUiRoot } from \"../ui-root\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\nimport { sendFile } from \"./ui-assets\";\n\n/**\n * Registers the API docs: `GET /api/openapi.json` returns the document core\n * builds from the registered routes (`deps.getOpenApiDocument`), and\n * `GET /docs` serves the page that renders it with Scalar and\n * `GET /docs/swagger` the same document in Swagger UI;\n * `GET /api/postman.json` returns the Postman collection core builds\n * (`deps.getPostmanCollection`). The pages use relative URLs, so it works under whatever base path the dashboard is\n * mounted on.\n */\nexport function registerOpenApiRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n server.get(\"/api/openapi.json\", async (_request, reply) => {\n if (!deps.getOpenApiDocument) {\n return reply.code(503).header(\"Cache-Control\", \"no-store\").send({\n error: \"The OpenAPI document is not available: the host did not provide a generator.\",\n });\n }\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return deps.getOpenApiDocument();\n });\n\n server.get(\"/api/postman.json\", async (_request, reply) => {\n if (!deps.getPostmanCollection) {\n return reply.code(503).header(\"Cache-Control\", \"no-store\").send({\n error: \"The Postman collection is not available: the host did not provide a generator.\",\n });\n }\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return deps.getPostmanCollection();\n });\n\n // The API tab shows these pages in a frame. The app's own headers (core's security headers forbid framing) are\n // replaced on the reply; production sets its full docs policy on top.\n const frameable = (reply: FastifyReply): FastifyReply =>\n reply\n .header(\"X-Frame-Options\", \"SAMEORIGIN\")\n .header(\"Content-Security-Policy\", \"frame-ancestors 'self'\");\n\n server.get(\"/docs\", (_request, reply) => {\n sendFile(frameable(reply), path.join(resolveUiRoot(), \"docs.html\"), \"text/html; charset=utf-8\");\n });\n\n server.get(\"/docs/swagger\", (_request, reply) => {\n sendFile(\n frameable(reply),\n path.join(resolveUiRoot(), \"docs-swagger.html\"),\n \"text/html; charset=utf-8\",\n );\n });\n}\n","import { realpath, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { MountedPanelFiles } from \"../panels\";\n\n/** The longest request path a panel's file route looks at. */\nconst MAX_PATH_LENGTH = 512;\n\n/**\n * Resolves a request path inside a panel's folder of images, or `null` when\n * it must answer 404. The path is the one URL decoding left (decoded once);\n * it is refused when it is empty, absolute, has an empty, `.` or `..`\n * segment, a backslash, a colon or a NUL byte, or an extension the panel did\n * not list. The resolved file must be a regular file whose real path (links\n * followed) stays inside the real path of the folder.\n */\nexport async function resolvePanelFile(\n files: MountedPanelFiles,\n requested: unknown,\n): Promise<string | null> {\n if (typeof requested !== \"string\" || requested === \"\" || requested.length > MAX_PATH_LENGTH) {\n return null;\n }\n\n if (/[\\0\\\\:]/.test(requested) || requested.startsWith(\"/\")) return null;\n\n const segments = requested.split(\"/\");\n\n if (segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\")) {\n return null;\n }\n\n const extension = path.extname(segments[segments.length - 1] ?? \"\").toLowerCase();\n\n if (!files.extensions.includes(extension)) return null;\n\n try {\n const root = await realpath(files.dir);\n const real = await realpath(path.join(root, ...segments));\n\n if (!real.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) return null;\n\n // A link inside the folder must not turn an image name into another kind of file.\n if (!files.extensions.includes(path.extname(real).toLowerCase())) return null;\n\n return (await stat(real)).isFile() ? real : null;\n } catch {\n return null;\n }\n}\n","import { createReadStream } from \"node:fs\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { type MountedDevtoolsPanel, panelContentType } from \"../panels\";\nimport type { DevtoolsPanelRequest } from \"../types\";\nimport { resolvePanelFile } from \"./panel-files\";\nimport { sendFile } from \"./ui-assets\";\n\n/** Answers 404; the production mount passes its uniform not-found answer. */\nexport type PanelNotFound = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => FastifyReply | Promise<FastifyReply>;\n\n/** Sends one image of a panel's folder with its content type, or answers 404. */\nexport async function sendPanelFile(\n panel: Pick<MountedDevtoolsPanel, \"files\">,\n requested: unknown,\n request: FastifyRequest,\n reply: FastifyReply,\n notFound: PanelNotFound,\n): Promise<FastifyReply | void> {\n const file = panel.files === null ? null : await resolvePanelFile(panel.files, requested);\n\n if (file === null) return notFound(request, reply);\n\n reply\n .header(\"X-Content-Type-Options\", \"nosniff\")\n .header(\"Cache-Control\", \"no-store\")\n .header(\"Content-Type\", panelContentType(file));\n\n return reply.send(createReadStream(file));\n}\n\n/**\n * Mounts each panel's data routes at `/api/<id><route path>`, its view\n * module and assets at `/panels/<id>/<name>`, and its folder of images at\n * `/panels/<id>/files/<path>`. Callers register this inside the devtools\n * scope, so the guard covers every one of them. A file is served only when\n * its name is listed by the panel (or, for `files`, resolves inside the\n * panel's folder with a listed extension); the request never becomes a\n * filesystem path on its own.\n */\nexport function registerPanelRoutes(\n server: FastifyInstance,\n panels: readonly MountedDevtoolsPanel[],\n options: { notFound?: PanelNotFound } = {},\n): void {\n const byId = new Map(panels.map((panel) => [panel.id, panel]));\n const notFound: PanelNotFound =\n options.notFound ??\n ((_request, reply) => {\n reply.code(404).header(\"Cache-Control\", \"no-store\").send();\n\n return reply;\n });\n\n for (const panel of panels) {\n for (const route of panel.routes) {\n server.route({\n method: route.method,\n url: `/api/${panel.id}${route.path}`,\n handler: async (request, reply) => {\n const input: DevtoolsPanelRequest = {\n params: (request.params ?? {}) as Record<string, string>,\n query: (request.query ?? {}) as Record<string, string | string[]>,\n body: request.body,\n };\n const result = await route.handler(input);\n\n reply.header(\"cache-control\", \"no-store\");\n\n if (result === undefined) return reply.code(204).send();\n\n return result;\n },\n });\n }\n }\n\n server.get<{ Params: { id: string; \"*\": string } }>(\n \"/panels/:id/files/*\",\n async (request, reply) => {\n const panel = byId.get(request.params.id);\n\n if (panel === undefined) return notFound(request, reply);\n\n return sendPanelFile(panel, request.params[\"*\"], request, reply, notFound);\n },\n );\n\n server.get<{ Params: { id: string; name: string } }>(\"/panels/:id/:name\", (request, reply) => {\n const panel = byId.get(request.params.id);\n const name = request.params.name;\n const file =\n panel === undefined\n ? undefined\n : name === \"view.js\"\n ? panel.view\n : Object.hasOwn(panel.assets, name)\n ? panel.assets[name]\n : undefined;\n\n if (file === undefined) {\n reply.code(404).header(\"Cache-Control\", \"no-store\").send();\n return;\n }\n\n reply.header(\"X-Content-Type-Options\", \"nosniff\");\n sendFile(reply, file, panelContentType(name));\n });\n}\n","import type { RequestLogFilter, RequestLogRecord, RequestLogSummary } from \"@warlock.js/core\";\nimport type {\n DevtoolsLogEntry,\n DevtoolsRequestDetail,\n DevtoolsRequestSummary,\n DevtoolsWarning,\n} from \"./types\";\n\n/** The list row filters run over, from an in-memory summary. */\nexport function summaryToRow(summary: DevtoolsRequestSummary): RequestLogSummary {\n return {\n id: summary.id,\n time: new Date(summary.startedAt).toISOString(),\n method: summary.method,\n url: summary.path,\n ...(summary.route ? { route: summary.route } : {}),\n status: summary.status ?? 0,\n durationMs: summary.durationMs ?? 0,\n };\n}\n\n/** An in-memory-shaped list row from a persisted one. */\nexport function rowToSummary(row: RequestLogSummary): DevtoolsRequestSummary {\n return {\n id: row.id,\n method: row.method,\n path: row.url,\n route: row.route,\n status: row.status,\n startedAt: Date.parse(row.time),\n durationMs: row.durationMs,\n queryCount: row.queryCount ?? 0,\n warningCount: row.nPlusOneCount ?? 0,\n persisted: true,\n };\n}\n\n/**\n * Merge the live ring buffer with the persisted log, newest first, without\n * duplicates: a request in both is shown from memory (it has the full\n * timeline). Persisted rows fill in what a restart or the ring buffer's size\n * evicted.\n */\nexport function mergeRequestHistory(\n live: readonly DevtoolsRequestSummary[],\n persisted: readonly RequestLogSummary[],\n limit: number,\n): DevtoolsRequestSummary[] {\n const seen = new Set(live.map((summary) => summary.id));\n const merged = [...live];\n\n for (const row of persisted) {\n if (seen.has(row.id)) continue;\n\n seen.add(row.id);\n merged.push(rowToSummary(row));\n }\n\n return merged.sort((first, second) => second.startedAt - first.startedAt).slice(0, limit);\n}\n\nconst FILTER_KEYS = [\"status\", \"route\", \"method\", \"since\", \"until\", \"q\"] as const;\n\n/** The request log filter in a `GET /api/requests` query string. */\nexport function filterFromQuery(query: Record<string, unknown>): RequestLogFilter {\n const filter: RequestLogFilter = {};\n\n for (const key of FILTER_KEYS) {\n const value = query[key];\n\n if (typeof value === \"string\" && value.trim() !== \"\") filter[key] = value.trim();\n }\n\n const limit = Number(query.limit);\n\n if (Number.isInteger(limit) && limit > 0) filter.limit = limit;\n\n return filter;\n}\n\n/** Whether a filter narrows anything. */\nexport function hasFilter(filter: RequestLogFilter): boolean {\n return FILTER_KEYS.some((key) => filter[key] !== undefined);\n}\n\nfunction toLogLevel(level: string): DevtoolsLogEntry[\"level\"] {\n return level === \"debug\" || level === \"info\" || level === \"warn\" || level === \"success\"\n ? level\n : \"error\";\n}\n\n/**\n * A request detail rebuilt from a persisted record, in the shape of an\n * in-memory one: phases, logs and N+1 warnings carry over; query-by-query\n * and cache detail live only in memory, so those lists are empty. `record`\n * has everything the log kept.\n */\nexport function recordToDetail(record: RequestLogRecord): DevtoolsRequestDetail {\n const startedAt = Date.parse(record.time);\n const warnings: DevtoolsWarning[] = (record.queries?.nPlusOne ?? []).map((finding) => ({\n type: \"n+1\",\n message: `${finding.query} ran ${finding.count} times`,\n shape: finding.query,\n count: finding.count,\n }));\n\n return {\n id: record.id,\n method: record.method,\n path: record.url,\n route: record.route.pattern,\n status: record.status,\n startedAt,\n durationMs: record.durationMs,\n error: record.error?.message,\n phases: (record.phases ?? []).map((phase) => ({\n name: phase.name,\n startedAt,\n durationMs: phase.durationMs,\n })),\n queries: [],\n cache: [],\n logs: (record.logs ?? []).map((entry) => ({\n level: toLogLevel(entry.level),\n module: entry.module,\n action: entry.action,\n message: entry.message,\n at: entry.at,\n ...(entry.context ? { context: entry.context } : {}),\n })),\n mails: [],\n warnings,\n persisted: true,\n record,\n };\n}\n","import type { RequestLogFilter } from \"@warlock.js/core\";\nimport type { FastifyInstance, FastifyReply } from \"fastify\";\nimport { DevtoolsApiError } from \"../production/errors\";\nimport type { DevtoolsSampleFilter } from \"../production/store/types\";\nimport {\n filterFromQuery,\n hasFilter,\n mergeRequestHistory,\n recordToDetail,\n summaryToRow,\n} from \"../request-history\";\nimport type { DevtoolsRequestDetail } from \"../types\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\nconst STATUS_FILTER = /^(?:[1-5]\\d\\d|[1-5]xx)$/i;\nconst METHOD_FILTER = /^[A-Za-z]{1,16}$/;\nconst RELATIVE_SINCE = /^(\\d+)(s|m|h|d)$/;\nconst UNIT_MS = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 } as const;\nconst DEFAULT_SAMPLE_LIMIT = 200;\nconst MAX_SAMPLE_LIMIT = 1000;\n\n/** A time bound as epoch ms: a number, an ISO date, or (for `since`) a duration back such as `15m`. */\nfunction parseTimeBound(value: string, allowRelative: boolean): number {\n if (/^\\d+$/.test(value)) return Number(value);\n\n const relative = allowRelative ? RELATIVE_SINCE.exec(value) : null;\n\n if (relative) {\n return Date.now() - Number(relative[1]) * UNIT_MS[relative[2] as keyof typeof UNIT_MS];\n }\n\n const parsed = Date.parse(value);\n\n if (Number.isNaN(parsed)) throw new DevtoolsApiError(\"request.invalid-filter\");\n\n return parsed;\n}\n\n/** The stored-sample filter in a `GET /api/requests` query string; throws `request.invalid-filter`. */\nfunction sampleFilterFromQuery(\n query: Record<string, unknown>,\n filter: RequestLogFilter,\n fallbackLimit: number,\n): DevtoolsSampleFilter {\n const result: DevtoolsSampleFilter = {\n limit: Math.min(MAX_SAMPLE_LIMIT, filter.limit ?? fallbackLimit),\n };\n\n if (filter.status !== undefined) {\n const status = String(filter.status);\n\n if (!STATUS_FILTER.test(status)) throw new DevtoolsApiError(\"request.invalid-filter\");\n\n result.status = status.toLowerCase();\n }\n\n if (filter.method !== undefined) {\n if (!METHOD_FILTER.test(String(filter.method))) {\n throw new DevtoolsApiError(\"request.invalid-filter\");\n }\n\n result.method = String(filter.method);\n }\n\n if (filter.route !== undefined) result.route = String(filter.route);\n if (filter.q !== undefined) result.q = String(filter.q);\n if (filter.since !== undefined) result.since = parseTimeBound(String(filter.since), true);\n if (filter.until !== undefined) result.until = parseTimeBound(String(filter.until), false);\n\n const instance = query.instance;\n\n if (typeof instance === \"string\" && instance.trim() !== \"\" && instance !== \"all\") {\n result.instance = instance.trim();\n }\n\n return result;\n}\n\nfunction sendApiError(reply: FastifyReply, error: DevtoolsApiError): void {\n reply.code(error.statusCode).send(error.toBody());\n}\n\n/**\n * Production: the same four routes over the request source (stored samples\n * and this process's memory), merged with the persisted request log the way\n * development merges it with the ring buffer.\n */\nfunction registerProductionRequestsRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n const source = deps.requests;\n\n if (!source) return;\n\n server.get<{ Querystring: Record<string, unknown> }>(\"/api/requests\", async (request, reply) => {\n const { requestLog, options } = deps;\n\n try {\n const filter = filterFromQuery(request.query);\n const sampleFilter = sampleFilterFromQuery(request.query, filter, DEFAULT_SAMPLE_LIMIT);\n const limit = Math.min(MAX_SAMPLE_LIMIT, filter.limit ?? options.maxRequests);\n let persisted: Awaited<ReturnType<NonNullable<typeof requestLog>[\"list\"]>> = [];\n\n if (requestLog) {\n try {\n requestLog.compile(filter);\n persisted = await requestLog.list({ ...filter, limit });\n } catch (error) {\n // A bad filter value is the caller's mistake; a read failure leaves the samples.\n if (error instanceof Error && /^Invalid /.test(error.message)) {\n throw new DevtoolsApiError(\"request.invalid-filter\");\n }\n }\n }\n\n const samples = await source.list({ ...sampleFilter, limit });\n\n return mergeRequestHistory(samples, persisted, limit);\n } catch (error) {\n if (error instanceof DevtoolsApiError) {\n sendApiError(reply, error);\n return;\n }\n\n throw error;\n }\n });\n\n server.get<{ Params: { id: string } }>(\"/api/requests/:id\", async (request, reply) => {\n const { id } = request.params;\n const persisted = await deps.requestLog?.get(id).catch(() => undefined);\n const found = await source.get(id);\n\n if (found) {\n const hasTimeline = \"phases\" in found;\n\n if (hasTimeline) return persisted ? { ...found, record: persisted } : found;\n\n // A slow or failed request that was not sampled: the summary, plus what the log kept.\n if (persisted) {\n return {\n ...recordToDetail(persisted),\n ...(found.instance === undefined ? {} : { instance: found.instance }),\n partial: true,\n };\n }\n\n return found;\n }\n\n if (!persisted) {\n sendApiError(reply, new DevtoolsApiError(\"request.not-found\"));\n return;\n }\n\n return recordToDetail(persisted);\n });\n\n server.get<{ Params: { id: string } }>(\"/api/requests/:id/curl\", async (request, reply) => {\n const { id } = request.params;\n const baseUrl = `${request.protocol}://${request.headers.host ?? \"localhost\"}`;\n const persisted = await deps.requestLog?.get(id).catch(() => undefined);\n\n if (persisted && deps.requestLog) return { curl: deps.requestLog.curl(persisted, baseUrl) };\n\n const found = await source.get(id);\n\n if (!found) {\n sendApiError(reply, new DevtoolsApiError(\"request.not-found\"));\n return;\n }\n\n return { curl: `curl -X ${found.method} '${baseUrl}${found.path.replace(/'/g, `'\\\\''`)}'` };\n });\n\n server.delete(\"/api/requests\", async (_request, reply) => {\n await source.clear();\n deps.collector.clear();\n reply.code(204).send();\n });\n}\n\n/**\n * Registers the request list, single-request detail, \"copy as curl\", and\n * clear routes.\n *\n * With core's persistent request log available, the list and the detail also\n * read the JSON-lines history, so requests survive a restart. The list\n * accepts `status` (404 or 5xx), `route`, `method`, `since`, `until`, `q`\n * and `limit` query parameters.\n */\nexport function registerRequestsRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n if (deps.requests) {\n registerProductionRequestsRoutes(server, deps);\n return;\n }\n\n server.get<{ Querystring: Record<string, unknown> }>(\"/api/requests\", async (request, reply) => {\n const { requestLog, collector, options } = deps;\n\n if (!requestLog) return collector.listRequests();\n\n try {\n const filter = filterFromQuery(request.query);\n const matches = requestLog.compile(filter);\n const live = hasFilter(filter)\n ? collector.listRequests().filter((summary) => matches(summaryToRow(summary)))\n : collector.listRequests();\n const limit = filter.limit ?? options.maxRequests;\n const persisted = await requestLog.list({ ...filter, limit });\n\n return mergeRequestHistory(live, persisted, limit);\n } catch (error) {\n // A bad filter value is the caller's mistake; a read failure leaves the live list.\n if (error instanceof Error && /^Invalid /.test(error.message)) {\n reply.code(400).send({ error: error.message });\n return;\n }\n\n return collector.listRequests();\n }\n });\n\n server.get<{ Params: { id: string } }>(\"/api/requests/:id\", async (request, reply) => {\n const { id } = request.params;\n const persisted = await deps.requestLog?.get(id).catch(() => undefined);\n const found = deps.collector.getRequest(id);\n\n if (found) {\n const detail: DevtoolsRequestDetail = persisted ? { ...found, record: persisted } : found;\n\n return detail;\n }\n\n if (!persisted) {\n reply.code(404).send();\n return;\n }\n\n return recordToDetail(persisted);\n });\n\n server.get<{ Params: { id: string } }>(\"/api/requests/:id/curl\", async (request, reply) => {\n const { id } = request.params;\n const baseUrl = `${request.protocol}://${request.headers.host ?? \"localhost\"}`;\n const persisted = await deps.requestLog?.get(id).catch(() => undefined);\n\n if (persisted && deps.requestLog) return { curl: deps.requestLog.curl(persisted, baseUrl) };\n\n // Without a persisted record only the method and path are known.\n const live = deps.collector.getRequest(id);\n\n if (!live) {\n reply.code(404).send();\n return;\n }\n\n return { curl: `curl -X ${live.method} '${baseUrl}${live.path.replace(/'/g, `'\\\\''`)}'` };\n });\n\n server.delete(\"/api/requests\", async (_request, reply) => {\n deps.collector.clear();\n if (deps.ai?.available) deps.ai.store.clear();\n reply.code(204).send();\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/** Registers the route map, sourced from core's router via `deps.listRoutes`. */\nexport function registerRouteRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get(\"/api/routes\", async () => (deps.listRoutes ? deps.listRoutes() : []));\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"./types\";\nimport type { DevtoolsLogEntry, DevtoolsStreamEvent } from \"../types\";\n\nconst PING_INTERVAL_MS = 15_000;\n\n/** How long a browser waits before it reconnects a dropped stream. */\nconst RETRY_MS = 5000;\n\n/** The log entry as the production stream sends it: no context (it may hold values). */\nfunction withoutContext(entry: DevtoolsLogEntry): DevtoolsLogEntry {\n return {\n level: entry.level,\n module: entry.module,\n action: entry.action,\n message: entry.message,\n at: entry.at,\n };\n}\n\n/**\n * Registers the SSE stream: one `event: <type>\\ndata: <json>\\n\\n` frame per\n * collector event, plus a `: ping` comment every 15s to keep intermediaries\n * from closing an idle connection. The reply is hijacked so Fastify never\n * tries to serialize or close the response itself.\n *\n * The first frames are `retry: 5000` and an `event: hello` with the mode,\n * instance and role. In production (`deps.streamSession` set) the session and\n * the open state are checked again at every ping and the stream ends when\n * either fails; log entries carry no context; mail, AI and agent events flow\n * only when those tabs are enabled.\n */\nexport function registerStreamRoute(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get(\"/api/stream\", async (request, reply) => {\n // Opening first, so a refused stream (`stream.too-many`) is a normal JSON error.\n const session: DevtoolsStreamSession | null = deps.streamSession\n ? await deps.streamSession(request)\n : null;\n const enabled = new Set(deps.builtInPanels ?? []);\n const instanceId = deps.instance?.id;\n const mode = deps.mode ?? \"development\";\n\n reply.hijack();\n const res = reply.raw;\n\n res.writeHead(200, {\n ...session?.headers,\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-store\",\n Connection: \"keep-alive\",\n \"X-Accel-Buffering\": \"no\",\n });\n\n const write = (frame: string): void => {\n if (!res.writableEnded && !res.destroyed) res.write(frame);\n };\n\n write(`retry: ${RETRY_MS}\\n\\n`);\n\n const hello: Extract<DevtoolsStreamEvent, { type: \"hello\" }>[\"data\"] = {\n mode,\n instance: instanceId ?? null,\n role: session?.role ?? (mode === \"development\" ? \"admin\" : null),\n };\n\n write(`event: hello\\ndata: ${JSON.stringify(hello)}\\n\\n`);\n\n const dispose = deps.collector.subscribe((event) => {\n if (event.type === \"hello\") return;\n\n if (session !== null) {\n if (event.type === \"mail\" && !enabled.has(\"mail\")) return;\n\n if (event.type === \"log\") {\n if (!session.logLevels.includes(event.data.level)) return;\n\n const row = withoutContext(event.data);\n\n write(\n `event: log\\ndata: ${JSON.stringify(instanceId !== undefined ? { ...row, instance: instanceId } : row)}\\n\\n`,\n );\n return;\n }\n }\n\n const data =\n event.type === \"request\" && instanceId !== undefined\n ? { ...event.data, instance: instanceId }\n : event.data;\n\n write(`event: ${event.type}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n });\n\n const aiAllowed = session === null || enabled.has(\"ai\");\n const agentsAllowed = session === null || enabled.has(\"agents\");\n\n const disposeAi =\n aiAllowed && deps.ai?.available\n ? deps.ai.subscribe((event) => {\n write(`event: ai\\ndata: ${JSON.stringify(event)}\\n\\n`);\n })\n : undefined;\n\n const disposeAgentTraces = agentsAllowed\n ? deps.agentTraces?.subscribe((event) => {\n write(`event: agent-trace\\ndata: ${JSON.stringify(event)}\\n\\n`);\n })\n : undefined;\n\n let closed = false;\n\n const close = (): void => {\n if (closed) return;\n\n closed = true;\n clearInterval(pingTimer);\n dispose();\n disposeAi?.();\n disposeAgentTraces?.();\n session?.release();\n\n if (!res.writableEnded && !res.destroyed) res.end();\n };\n\n const pingTimer = setInterval(() => {\n if (session === null) {\n write(\": ping\\n\\n\");\n return;\n }\n\n session.revalidate().then(\n (stillValid) => {\n if (closed) return;\n\n if (stillValid) write(\": ping\\n\\n\");\n else close();\n },\n () => close(),\n );\n }, PING_INTERVAL_MS);\n pingTimer.unref();\n\n request.raw.on(\"close\", close);\n res.on(\"error\", close);\n });\n}\n"],"mappings":";;;;;;;;;;;;AAOA,MAAM,qBAAqBA,oCAAoBC,sCAAsB,eAAe,CAAC;;AAGrF,SAAS,UAAU,OAAqB,OAA8B;CACpE,IAAI,iBAAiBC,iCAAkB,OAAO,MAAM,KAAK,MAAM,UAAU,CAAC,CAAC,KAAK,MAAM,OAAO,CAAC;CAE9F,MAAM;AACR;;;;;;;;;;;;;;;;AAiBA,SAAgB,uBACd,QACA,MACM;CACN,KAAK,MAAM,CAAC,OAAO,SAAS;EAC1B,CAAC,mBAAmB,QAAQ;EAC5B,CAAC,kBAAkB,QAAQ;EAC3B,CAAC,kBAAkB,QAAQ;CAC7B,GACE,OAAO,IAA2C,OAAO,OAAO,SAAS,UAAU;EACjF,MAAM,OAAO,iBAAiB,UAAU;EAExC,MAAM,UAAU,KAAK;EAErB,IAAI,CAAC,SAAS,OAAO,aAAa;EAElC,IAAI,CAAC,QAAQ,WAAW;GACtB,MAAM,EAAE,SAAS,UAAU,GAAG,gBAAgB;GAE9C,OAAO;EACT;EAEA,IAAI;GACF,OAAO,MAAM,QAAQ,QAAQ,KAAK,CAAC,QAAQ,KAAK;EAClD,SAAS,OAAO;GACd,OAAO,UAAU,OAAO,KAAK;EAC/B;CACF,CAAC;CAGH,OAAO,IAAI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I,YAAY,MAAM;IACpB,MAAM,YAAY;IAClB;GACF;GAEA,QAAQ,WAAW,CAAC,CAAC,MAClB,eAAe;IACd,IAAI,QAAQ;IAEZ,IAAI,YAAY,MAAM,YAAY;SAC7B,MAAM;GACb,SACM,MAAM,CACd;EACF,GAAG,gBAAgB;EACnB,UAAU,MAAM;EAEhB,QAAQ,IAAI,GAAG,SAAS,KAAK;EAC7B,IAAI,GAAG,SAAS,KAAK;CACvB,CAAC;AACH"}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { describeAiUnavailable, loadAiPackages, toAiUnavailableView } from "../sources/ai-source.mjs";
|
|
2
|
+
import { createAiReportService } from "./reports/service.mjs";
|
|
3
|
+
import { createCascadeAiRollupStore } from "./rollup/cascade-store.mjs";
|
|
4
|
+
import { createFileAiRollupStore } from "./rollup/file-store.mjs";
|
|
5
|
+
import { startAiRollupWriter } from "./rollup/writer.mjs";
|
|
6
|
+
import "./rollup/index.mjs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
//#region ../../packages/devtools/src/ai/attach.ts
|
|
10
|
+
/**
|
|
11
|
+
* Loads Panoptic's trace feed (`subscribeTraces`, `totalCostUsd`) and
|
|
12
|
+
* `@warlock.js/ai`'s observer registry lazily, plus the Runs helpers. Returns
|
|
13
|
+
* `{ unavailable }` (`ai-missing`, `panoptic-missing`, `panoptic-failed`)
|
|
14
|
+
* when they do not load. Shared by the development and production wiring.
|
|
15
|
+
*/
|
|
16
|
+
async function loadAiFeed(deps) {
|
|
17
|
+
const loaded = await loadAiPackages(deps);
|
|
18
|
+
if ("unavailable" in loaded) return { unavailable: toAiUnavailableView(loaded.unavailable) };
|
|
19
|
+
const { panoptic, observationOff } = loaded;
|
|
20
|
+
return {
|
|
21
|
+
feed: {
|
|
22
|
+
subscribe: (listener) => panoptic.subscribeTraces(listener),
|
|
23
|
+
totalCost: (usage) => panoptic.totalCostUsd(usage),
|
|
24
|
+
observationOff
|
|
25
|
+
},
|
|
26
|
+
helpers: {
|
|
27
|
+
filterTraces: panoptic.filterTraces,
|
|
28
|
+
groupBySession: panoptic.groupBySession,
|
|
29
|
+
groupByPrompt: panoptic.groupByPrompt,
|
|
30
|
+
groupByType: panoptic.groupByType,
|
|
31
|
+
percentile: panoptic.percentile,
|
|
32
|
+
tracePromptKey: panoptic.tracePromptKey
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const TABLE_MISSING_WARNING = "AI reports are off: the devtools_ai_rollups table is missing. Run the devtools migrations (warlock migrate), then restart.";
|
|
37
|
+
/**
|
|
38
|
+
* Starts the AI reports of this process: with `options.reports` off answers
|
|
39
|
+
* `reports-off`; otherwise builds the store for the mode (development: the
|
|
40
|
+
* file store in `directory`; production: the cascade store, `table-missing`
|
|
41
|
+
* when `verify()` is false, logged once with the migration hint), starts the
|
|
42
|
+
* rollup writer on `feed.subscribe`, and builds the report service.
|
|
43
|
+
* `dispose` unsubscribes and stops the writer (final flush).
|
|
44
|
+
*/
|
|
45
|
+
async function attachAiReports(input) {
|
|
46
|
+
const { feed, options, warn } = input;
|
|
47
|
+
const off = (reason) => ({
|
|
48
|
+
...toAiUnavailableView(describeAiUnavailable(reason)),
|
|
49
|
+
async dispose() {}
|
|
50
|
+
});
|
|
51
|
+
if (!options.reports) return off("reports-off");
|
|
52
|
+
const production = options.mode === "production";
|
|
53
|
+
let store;
|
|
54
|
+
try {
|
|
55
|
+
store = production ? await createCascadeAiRollupStore() : createFileAiRollupStore({ directory: input.directory ?? path.join(process.cwd(), "storage", "devtools", "ai-rollups") });
|
|
56
|
+
if (!await store.verify()) {
|
|
57
|
+
warn(TABLE_MISSING_WARNING);
|
|
58
|
+
return off("table-missing");
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
warn(`${TABLE_MISSING_WARNING} (${error instanceof Error ? error.message : String(error)})`);
|
|
62
|
+
return off("table-missing");
|
|
63
|
+
}
|
|
64
|
+
const writer = startAiRollupWriter({
|
|
65
|
+
store,
|
|
66
|
+
totalCost: feed.totalCost,
|
|
67
|
+
options,
|
|
68
|
+
warn
|
|
69
|
+
});
|
|
70
|
+
const unsubscribe = feed.subscribe((trace) => writer.record(trace));
|
|
71
|
+
return {
|
|
72
|
+
available: true,
|
|
73
|
+
service: createAiReportService({
|
|
74
|
+
store,
|
|
75
|
+
pending: () => writer.pending(),
|
|
76
|
+
retentionDays: options.retentionDays,
|
|
77
|
+
observationOff: () => feed.observationOff(),
|
|
78
|
+
...input.recentFailures ? { recentFailures: input.recentFailures } : {}
|
|
79
|
+
}),
|
|
80
|
+
writer,
|
|
81
|
+
async dispose() {
|
|
82
|
+
unsubscribe();
|
|
83
|
+
await writer.stop();
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** The global key devtools publishes once mounted, read by Panoptic to keep its own dashboard off. */
|
|
88
|
+
const DEVTOOLS_MOUNTED_KEY = Symbol.for("@warlock.js/devtools.mounted");
|
|
89
|
+
|
|
90
|
+
//#endregion
|
|
91
|
+
export { DEVTOOLS_MOUNTED_KEY, attachAiReports, loadAiFeed };
|
|
92
|
+
//# sourceMappingURL=attach.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/ai/attach.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { DevtoolsAiFailedRun, DevtoolsAiUnavailableView } from \"../production/contracts\";\nimport { describeAiUnavailable, loadAiPackages, toAiUnavailableView } from \"../sources/ai-source\";\nimport { createAiReportService, type DevtoolsAiReportService } from \"./reports/service\";\nimport type { DevtoolsAiRecentFailuresFilter, DevtoolsAiRunHelpers } from \"./reports/runs\";\nimport { createCascadeAiRollupStore, createFileAiRollupStore, startAiRollupWriter } from \"./rollup\";\nimport type {\n DevtoolsAiFeed,\n DevtoolsAiRollupStore,\n DevtoolsAiRollupWriter,\n ResolvedDevtoolsAiOptions,\n} from \"./types\";\n\n/** The AI reports wiring of one process, as the routes receive it. */\nexport type DevtoolsAiReports =\n | {\n available: true;\n service: DevtoolsAiReportService;\n writer: DevtoolsAiRollupWriter;\n dispose(): Promise<void>;\n }\n | (DevtoolsAiUnavailableView & { dispose(): Promise<void> });\n\n/**\n * Loads Panoptic's trace feed (`subscribeTraces`, `totalCostUsd`) and\n * `@warlock.js/ai`'s observer registry lazily, plus the Runs helpers. Returns\n * `{ unavailable }` (`ai-missing`, `panoptic-missing`, `panoptic-failed`)\n * when they do not load. Shared by the development and production wiring.\n */\nexport async function loadAiFeed(deps?: {\n load?: (name: string) => Promise<unknown>;\n version?: (name: string) => string | null;\n}): Promise<\n | { feed: DevtoolsAiFeed; helpers: DevtoolsAiRunHelpers }\n | { unavailable: DevtoolsAiUnavailableView }\n> {\n const loaded = await loadAiPackages(deps);\n\n if (\"unavailable\" in loaded) return { unavailable: toAiUnavailableView(loaded.unavailable) };\n\n const { panoptic, observationOff } = loaded;\n\n return {\n feed: {\n subscribe: (listener) => panoptic.subscribeTraces(listener),\n totalCost: (usage) => panoptic.totalCostUsd(usage),\n observationOff,\n },\n helpers: {\n filterTraces: panoptic.filterTraces,\n groupBySession: panoptic.groupBySession,\n groupByPrompt: panoptic.groupByPrompt,\n groupByType: panoptic.groupByType,\n percentile: panoptic.percentile,\n tracePromptKey: panoptic.tracePromptKey,\n },\n };\n}\n\nconst TABLE_MISSING_WARNING =\n \"AI reports are off: the devtools_ai_rollups table is missing. Run the devtools migrations (warlock migrate), then restart.\";\n\n/**\n * Starts the AI reports of this process: with `options.reports` off answers\n * `reports-off`; otherwise builds the store for the mode (development: the\n * file store in `directory`; production: the cascade store, `table-missing`\n * when `verify()` is false, logged once with the migration hint), starts the\n * rollup writer on `feed.subscribe`, and builds the report service.\n * `dispose` unsubscribes and stops the writer (final flush).\n */\nexport async function attachAiReports(input: {\n feed: DevtoolsAiFeed;\n options: ResolvedDevtoolsAiOptions;\n /** Development only: where the file store writes (core's `storagePath(\"devtools/ai-rollups\")`). */\n directory?: string;\n /** Development only: recent failures from the Runs store, scoped to a page's range and filters. */\n recentFailures?: (filter: DevtoolsAiRecentFailuresFilter) => DevtoolsAiFailedRun[];\n warn: (message: string) => void;\n}): Promise<DevtoolsAiReports> {\n const { feed, options, warn } = input;\n const off = (reason: \"reports-off\" | \"table-missing\"): DevtoolsAiReports => ({\n ...toAiUnavailableView(describeAiUnavailable(reason)),\n async dispose() {},\n });\n\n if (!options.reports) return off(\"reports-off\");\n\n const production = options.mode === \"production\";\n let store: DevtoolsAiRollupStore;\n\n try {\n store = production\n ? await createCascadeAiRollupStore()\n : createFileAiRollupStore({\n directory:\n input.directory ?? path.join(process.cwd(), \"storage\", \"devtools\", \"ai-rollups\"),\n });\n\n if (!(await store.verify())) {\n warn(TABLE_MISSING_WARNING);\n\n return off(\"table-missing\");\n }\n } catch (error) {\n warn(`${TABLE_MISSING_WARNING} (${error instanceof Error ? error.message : String(error)})`);\n\n return off(\"table-missing\");\n }\n\n const writer = startAiRollupWriter({ store, totalCost: feed.totalCost, options, warn });\n const unsubscribe = feed.subscribe((trace) => writer.record(trace));\n const service = createAiReportService({\n store,\n pending: () => writer.pending(),\n retentionDays: options.retentionDays,\n observationOff: () => feed.observationOff(),\n ...(input.recentFailures ? { recentFailures: input.recentFailures } : {}),\n });\n\n return {\n available: true,\n service,\n writer,\n async dispose() {\n unsubscribe();\n await writer.stop();\n },\n };\n}\n\n/** The global key devtools publishes once mounted, read by Panoptic to keep its own dashboard off. */\nexport const DEVTOOLS_MOUNTED_KEY = Symbol.for(\"@warlock.js/devtools.mounted\");\n\n/** What is published under `DEVTOOLS_MOUNTED_KEY`. */\nexport type DevtoolsMountedMarker = { path: string; mode: \"development\" | \"production\" };\n"],"mappings":";;;;;;;;;;;;;;;AA6BA,eAAsB,WAAW,MAM/B;CACA,MAAM,SAAS,MAAM,eAAe,IAAI;CAExC,IAAI,iBAAiB,QAAQ,OAAO,EAAE,aAAa,oBAAoB,OAAO,WAAW,EAAE;CA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gB,MAAM,eAAe,IAAI,CAAC;EACzE,CAIQ;EACN;EACA,MAAM,UAAU;GACd,YAAY;GACZ,MAAM,OAAO,KAAK;EACpB;CACF;AACF;;AAGA,MAAa,uBAAuB,OAAO,IAAI,8BAA8B"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region ../../packages/devtools/src/ai/options.ts
|
|
2
|
+
/** Default `retentionDays` per mode. */
|
|
3
|
+
const DEVTOOLS_AI_RETENTION_DAYS = {
|
|
4
|
+
development: 30,
|
|
5
|
+
production: 90
|
|
6
|
+
};
|
|
7
|
+
/** Default `flushIntervalMs`. */
|
|
8
|
+
const DEVTOOLS_AI_FLUSH_INTERVAL_MS = 6e4;
|
|
9
|
+
/**
|
|
10
|
+
* Applies the defaults of `devtools.ai` for `mode`. Throws an `Error` naming
|
|
11
|
+
* the option when `retentionDays` is not a whole number from 1 to 400 or
|
|
12
|
+
* `flushIntervalMs` is below 5000 (the same style as `resolveDevtoolsOptions`).
|
|
13
|
+
*/
|
|
14
|
+
function resolveDevtoolsAiOptions(options, mode) {
|
|
15
|
+
const reports = options?.reports ?? true;
|
|
16
|
+
const retentionDays = options?.retentionDays ?? DEVTOOLS_AI_RETENTION_DAYS[mode];
|
|
17
|
+
const flushIntervalMs = options?.flushIntervalMs ?? 6e4;
|
|
18
|
+
if (typeof reports !== "boolean") throw new Error("Devtools option \"ai.reports\" must be true or false.");
|
|
19
|
+
if (!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 400) throw new Error("Devtools option \"ai.retentionDays\" must be a whole number from 1 to 400.");
|
|
20
|
+
if (typeof flushIntervalMs !== "number" || !Number.isFinite(flushIntervalMs) || flushIntervalMs < 5e3) throw new Error("Devtools option \"ai.flushIntervalMs\" must be at least 5000.");
|
|
21
|
+
return {
|
|
22
|
+
reports,
|
|
23
|
+
retentionDays,
|
|
24
|
+
flushIntervalMs,
|
|
25
|
+
mode
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
export { DEVTOOLS_AI_FLUSH_INTERVAL_MS, DEVTOOLS_AI_RETENTION_DAYS, resolveDevtoolsAiOptions };
|
|
31
|
+
//# sourceMappingURL=options.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/ai/options.ts"],"sourcesContent":["import type { DevtoolsMode } from \"../production/contracts\";\nimport type { DevtoolsAiOptions, ResolvedDevtoolsAiOptions } from \"./types\";\n\n/** Default `retentionDays` per mode. */\nexport const DEVTOOLS_AI_RETENTION_DAYS: Readonly<Record<DevtoolsMode, number>> = {\n development: 30,\n production: 90,\n};\n\n/** Default `flushIntervalMs`. */\nexport const DEVTOOLS_AI_FLUSH_INTERVAL_MS = 60_000;\n\n/**\n * Applies the defaults of `devtools.ai` for `mode`. Throws an `Error` naming\n * the option when `retentionDays` is not a whole number from 1 to 400 or\n * `flushIntervalMs` is below 5000 (the same style as `resolveDevtoolsOptions`).\n */\nexport function resolveDevtoolsAiOptions(\n options: DevtoolsAiOptions | undefined,\n mode: DevtoolsMode,\n): ResolvedDevtoolsAiOptions {\n const reports = options?.reports ?? true;\n const retentionDays = options?.retentionDays ?? DEVTOOLS_AI_RETENTION_DAYS[mode];\n const flushIntervalMs = options?.flushIntervalMs ?? DEVTOOLS_AI_FLUSH_INTERVAL_MS;\n\n if (typeof reports !== \"boolean\") {\n throw new Error('Devtools option \"ai.reports\" must be true or false.');\n }\n\n if (!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 400) {\n throw new Error('Devtools option \"ai.retentionDays\" must be a whole number from 1 to 400.');\n }\n\n if (\n typeof flushIntervalMs !== \"number\" ||\n !Number.isFinite(flushIntervalMs) ||\n flushIntervalMs < 5000\n ) {\n throw new Error('Devtools option \"ai.flushIntervalMs\" must be at least 5000.');\n }\n\n return { reports, retentionDays, flushIntervalMs, mode };\n}\n"],"mappings":";;AAIA,MAAa,6BAAqE;CAChF,aAAa;CACb,YAAY;AACd;;AAGA,MAAa,gCAAgC;;;;;;AAO7C,SAAgB,yBACd,SACA,MAC2B;CAC3B,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,gBAAgB,SAAS,iBAAiB,2BAA2B;CAC3E,MAAM,kBAAkB,SAAS;CAEjC,IAAI,OAAO,YAAY,WACrB,MAAM,IAAI,MAAM,uDAAqD;CAGvE,IAAI,CAAC,OAAO,UAAU,aAAa,KAAK,gBAAgB,KAAK,gBAAgB,KAC3E,MAAM,IAAI,MAAM,4EAA0E;CAG5F,IACE,OAAO,oBAAoB,YAC3B,CAAC,OAAO,SAAS,eAAe,KAChC,kBAAkB,KAElB,MAAM,IAAI,MAAM,+DAA6D;CAG/E,OAAO;EAAE;EAAS;EAAe;EAAiB;CAAK;AACzD"}
|