@brickkit/cli 0.16.0-beta.1 → 0.16.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +35 -8
  2. package/dashboard-dist/{api-reference-C2_JX174.js → api-reference-ZQs4Z4Yd.js} +71 -71
  3. package/dashboard-dist/app.css +1 -1
  4. package/dashboard-dist/app.js +12 -12
  5. package/dashboard-dist/{client-DsITZplk.js → client-CFM1S4Xv.js} +1 -1
  6. package/dashboard-dist/{core-sW89OSz5.js → core-VNHGFYB7.js} +1 -1
  7. package/dashboard-dist/{docs-D3U7gUWq.js → docs-CM2krp6H.js} +2 -2
  8. package/dashboard-dist/kit.js +1 -1
  9. package/dashboard-dist/popover-CVY1eRNY.js +1 -0
  10. package/dashboard-dist/theme.css +48 -39
  11. package/dist/bin.js +3 -2
  12. package/dist/bin.js.map +1 -1
  13. package/dist/build.js +6 -1
  14. package/dist/build.js.map +1 -1
  15. package/dist/dashboard-host.js +2594 -889
  16. package/dist/dashboard-host.js.map +1 -1
  17. package/dist/dashboard-protocol.js +10 -6
  18. package/dist/dashboard-protocol.js.map +1 -1
  19. package/dist/dashboard.d.ts +3 -3
  20. package/dist/dev-inspector.js +111 -0
  21. package/dist/dev-inspector.js.map +1 -0
  22. package/dist/dev-worker.js +1 -102
  23. package/dist/dev-worker.js.map +1 -1
  24. package/dist/package.js +5 -0
  25. package/dist/package.js.map +1 -0
  26. package/dist/production-dashboard.js +27 -2
  27. package/dist/production-dashboard.js.map +1 -1
  28. package/dist/production-dashboard2.d.ts +5 -0
  29. package/dist/project.js +2 -3
  30. package/dist/project.js.map +1 -1
  31. package/dist/vite.js +2 -1
  32. package/dist/vite.js.map +1 -1
  33. package/inspector-dist/NOTICE +3 -1
  34. package/inspector-dist/client/assets/{app-Wfnqu2Ic.css → app-PJHZvcxl.css} +49 -40
  35. package/inspector-dist/client/assets/{manifest-cfc09adc.js → manifest-274ef876.js} +1 -1
  36. package/inspector-dist/client/assets/{root-CVescmwt.css → root-CPvk93Fe.css} +49 -40
  37. package/inspector-dist/server/assets/{app-w0nTXgJd.js → app-DdYuYhBk.js} +89 -17
  38. package/inspector-dist/server/assets/{functions-B9XwHSzK.js → functions-BebJWj30.js} +2 -2
  39. package/inspector-dist/server/assets/{serialization-DsMds3lJ.js → serialization-Cgu5b7aC.js} +1 -1
  40. package/inspector-dist/server/assets/{token-CvvD8Y5H.js → token-3-nUtxO2.js} +1 -1
  41. package/inspector-dist/server/assets/{token-CxjWFNNq.js → token-DH652a7D.js} +1 -1
  42. package/inspector-dist/server/assets/token-util-wQgchIHA.js +3 -0
  43. package/inspector-dist/server/assets/{ws-transport-CamzQ5O8.js → ws-transport-7nLI4Gq9.js} +1 -1
  44. package/inspector-dist/server/index.js +1 -1
  45. package/package.json +2 -2
  46. package/dashboard-dist/PopoverPopup-CiI2avT_.js +0 -1
  47. package/dashboard-dist/popover-Bb2Q3jiK.js +0 -1
  48. package/inspector-dist/server/assets/token-util-D9IsWeEs.js +0 -3
  49. /package/inspector-dist/client/assets/{root-CVhM1JOR.js → root-2KbsWt-J.js} +0 -0
@@ -1,9 +1,10 @@
1
1
  import { n as ConfigError, r as DEFAULT_DASHBOARD_PORT } from "./config2.js";
2
- import { _ as matchRoute, a as INSPECTOR_TOKEN_HEADER, c as SHARED_MODULES, d as assetUrl, f as decode, g as isExternalHref, h as docsHref, i as DOCS_PATHS, l as SPAN, m as docsFileUrl, n as ATTR, o as LIVE_LIMITS, s as ROUTES, t as ASSETS, u as THEME_STORAGE_KEY } from "./dashboard-protocol.js";
2
+ import { _ as isExternalHref, a as INSPECTOR_READ_ONLY_HEADER, c as ROUTES, d as THEME_STORAGE_KEY, f as assetUrl, g as docsHref, h as docsFileUrl, i as DOCS_PATHS, l as SHARED_MODULES, m as describeSchedule, n as ATTR, o as INSPECTOR_TOKEN_HEADER, p as decode, s as LIVE_LIMITS, t as ASSETS, u as SPAN, v as matchRoute, y as viewsWithout } from "./dashboard-protocol.js";
3
+ import { t as version } from "./package.js";
3
4
  import { createRequire } from "node:module";
4
5
  import { existsSync, mkdirSync, watch, writeFileSync } from "node:fs";
5
6
  import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
6
- import { DASHBOARD_IDENTITY_HEADER, signDashboardIdentity } from "@brickkit/core";
7
+ import { DASHBOARD_IDENTITY_HEADER, DASHBOARD_MCP_ROUTE, UnknownToolError, WRAP_RESULT, createMcpHandler, signDashboardIdentity, signDashboardMcp } from "@brickkit/core";
7
8
  import { fileURLToPath, pathToFileURL } from "node:url";
8
9
  import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
9
10
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -657,6 +658,16 @@ var DevDocs = class {
657
658
  revision: this.revision
658
659
  };
659
660
  }
661
+ /** A page as written, without its frontmatter, for a reader that is not the dashboard's page. */
662
+ source(slugs) {
663
+ const file = this.#pages.get(slugs.join("/"));
664
+ return file && {
665
+ title: file.title,
666
+ description: file.description,
667
+ path: file.path,
668
+ content: file.content
669
+ };
670
+ }
660
671
  /** Compile one page; undefined when there is no such page. */
661
672
  async page(slugs) {
662
673
  const key = slugs.join("/");
@@ -950,6 +961,14 @@ function outcomeOf(row) {
950
961
  function endpointOf(trace) {
951
962
  return trace.method && trace.route ? `${trace.method} ${trace.route}` : trace.name;
952
963
  }
964
+ /** A live request as a log row; the same shape the history API returns. */
965
+ function toRow(trace) {
966
+ const { spans: _spans, ...row } = trace;
967
+ return {
968
+ ...row,
969
+ endpoint: endpointOf(trace)
970
+ };
971
+ }
953
972
  const OUTCOMES = [
954
973
  "ok",
955
974
  "client",
@@ -990,6 +1009,52 @@ const SEARCHED = [
990
1009
  "action",
991
1010
  "message"
992
1011
  ];
1012
+ /** Whether `row` passes the filters, leaving out `skip` when counting its facet. */
1013
+ function matches(row, filters, skip) {
1014
+ const anyOf = (facet, values, value) => skip === facet || !values?.length || value !== void 0 && values.includes(value);
1015
+ if (!anyOf("endpoint", filters.endpoints, row.endpoint)) return false;
1016
+ if (!anyOf("method", filters.methods, row.method)) return false;
1017
+ if (!anyOf("service", filters.services, row.service)) return false;
1018
+ if (!anyOf("outcome", filters.outcomes, outcomeOf(row))) return false;
1019
+ if (filters.minMs !== void 0 && filters.minMs > 0 && (row.durationMs ?? 0) < filters.minMs) return false;
1020
+ const needle = filters.query?.trim().toLowerCase();
1021
+ if (needle) return SEARCHED.some((field) => String(row[field] ?? "").toLowerCase().includes(needle));
1022
+ return true;
1023
+ }
1024
+ /** Newest first, or slowest first and then newest. */
1025
+ function compareRows(sort) {
1026
+ return sort === "slowest" ? (a, b) => (b.durationMs ?? 0) - (a.durationMs ?? 0) || b.startMs - a.startMs : (a, b) => b.startMs - a.startMs;
1027
+ }
1028
+ function applyFilters(rows, filters) {
1029
+ return rows.filter((row) => matches(row, filters)).sort(compareRows(filters.sort));
1030
+ }
1031
+ const FACET_VALUE = {
1032
+ outcome: outcomeOf,
1033
+ method: (row) => row.method,
1034
+ service: (row) => row.service,
1035
+ endpoint: (row) => row.endpoint
1036
+ };
1037
+ /** Counts for each filter, as if that filter were not applied. */
1038
+ function computeFacets(rows, filters) {
1039
+ const count = (facet) => {
1040
+ const counts = /* @__PURE__ */ new Map();
1041
+ for (const row of rows) {
1042
+ if (!matches(row, filters, facet)) continue;
1043
+ const value = FACET_VALUE[facet](row);
1044
+ if (value !== void 0) counts.set(value, (counts.get(value) ?? 0) + 1);
1045
+ }
1046
+ return [...counts.entries()].map(([value, total]) => ({
1047
+ value,
1048
+ count: total
1049
+ })).sort((a, b) => b.count - a.count || (a.value < b.value ? -1 : a.value > b.value ? 1 : 0)).slice(0, 30);
1050
+ };
1051
+ return {
1052
+ outcome: count("outcome"),
1053
+ method: count("method"),
1054
+ service: count("service"),
1055
+ endpoint: count("endpoint")
1056
+ };
1057
+ }
993
1058
  /** The width of each of `count` buckets across [from, to]: whole milliseconds, at least one. */
994
1059
  const bucketSize = (from, to, count) => Math.max(Math.ceil((to - from) / count), 1);
995
1060
  /** Linear-interpolated percentile of an ascending list; 0 for an empty list. */
@@ -1000,6 +1065,86 @@ function percentile(sorted, fraction) {
1000
1065
  const upper = Math.ceil(position);
1001
1066
  return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);
1002
1067
  }
1068
+ const LOG_LEVELS = [
1069
+ "debug",
1070
+ "info",
1071
+ "warn",
1072
+ "error"
1073
+ ];
1074
+ /** A line with no level, or one this does not know, is `info`, as the Logs view reads it. */
1075
+ const levelOf = (value) => LOG_LEVELS.find((level) => level === value) ?? "info";
1076
+ /** Newest first, then by request and position, so a page never repeats or skips a line. */
1077
+ function compareLogLines(a, b) {
1078
+ return b.timeMs - a.timeMs || (a.traceId < b.traceId ? -1 : a.traceId > b.traceId ? 1 : 0) || a.spanIndex - b.spanIndex || a.eventIndex - b.eventIndex;
1079
+ }
1080
+ /** The matching log lines of these requests, newest first. */
1081
+ function searchLogLines(traces, search) {
1082
+ const needle = search.query?.toLowerCase();
1083
+ const lines = [];
1084
+ for (const trace of traces) {
1085
+ const endpoint = endpointOf(trace);
1086
+ if (trace.startMs < search.from || trace.startMs > search.to || search.service !== void 0 && trace.service !== search.service || search.endpoint !== void 0 && endpoint !== search.endpoint) continue;
1087
+ for (const [spanIndex, span] of trace.spans.entries()) for (const [eventIndex, event] of span.events.entries()) {
1088
+ if (event.name !== SPAN.logEvent) continue;
1089
+ const level = levelOf(event.attributes[ATTR.logLevel]);
1090
+ const message = String(event.attributes[ATTR.logMessage] ?? "");
1091
+ if (search.level !== void 0 && level !== search.level || needle !== void 0 && !message.toLowerCase().includes(needle)) continue;
1092
+ lines.push({
1093
+ timeMs: event.timeMs,
1094
+ level,
1095
+ message,
1096
+ traceId: trace.traceId,
1097
+ endpoint,
1098
+ span: span.name,
1099
+ spanIndex,
1100
+ eventIndex
1101
+ });
1102
+ }
1103
+ }
1104
+ return lines.sort(compareLogLines);
1105
+ }
1106
+ function slowestEndpoints(rows, limit) {
1107
+ const byEndpoint = /* @__PURE__ */ new Map();
1108
+ for (const row of rows) {
1109
+ if (row.durationMs === void 0) continue;
1110
+ const stats = byEndpoint.get(row.endpoint) ?? {
1111
+ requests: 0,
1112
+ serverErrors: 0,
1113
+ totalMs: 0,
1114
+ maxMs: 0
1115
+ };
1116
+ stats.requests += 1;
1117
+ if (outcomeOf(row) === "server") stats.serverErrors += 1;
1118
+ stats.totalMs += row.durationMs;
1119
+ stats.maxMs = Math.max(stats.maxMs, row.durationMs);
1120
+ byEndpoint.set(row.endpoint, stats);
1121
+ }
1122
+ return [...byEndpoint.entries()].map(([endpoint, { totalMs, ...stats }]) => ({
1123
+ endpoint,
1124
+ ...stats,
1125
+ avgMs: totalMs / stats.requests
1126
+ })).sort((a, b) => b.avgMs - a.avgMs || b.requests - a.requests).slice(0, limit);
1127
+ }
1128
+ /** The numbers for the cards at the top of the log, for these requests. */
1129
+ function summarizeRows(rows) {
1130
+ let clientErrors = 0;
1131
+ let serverErrors = 0;
1132
+ const durations = [];
1133
+ for (const row of rows) {
1134
+ const outcome = outcomeOf(row);
1135
+ if (outcome === "client") clientErrors += 1;
1136
+ if (outcome === "server") serverErrors += 1;
1137
+ if (row.durationMs !== void 0) durations.push(row.durationMs);
1138
+ }
1139
+ durations.sort((a, b) => a - b);
1140
+ return {
1141
+ total: rows.length,
1142
+ clientErrors,
1143
+ serverErrors,
1144
+ medianMs: percentile(durations, .5),
1145
+ p95Ms: percentile(durations, .95)
1146
+ };
1147
+ }
1003
1148
  const CSV_COLUMNS = [
1004
1149
  "time",
1005
1150
  "method",
@@ -1093,991 +1238,2543 @@ ${IMPORT_MAP}
1093
1238
  </html>
1094
1239
  `;
1095
1240
  }
1096
- // src/dashboard-access.ts
1097
- /** How long the app's `authorize` may take before the request is refused. */
1098
- const AUTHORIZE_TIMEOUT_MS = 5e3;
1099
- function isLoopbackHost(host) {
1100
- const name = host.toLowerCase();
1101
- return name === "localhost" || name === "::1" || name === "[::1]" || /^127(\.\d{1,3}){3}$/.test(name);
1241
+ // src/dashboard-mcp-args.ts
1242
+ const MINUTE = 6e4;
1243
+ const UNITS = {
1244
+ s: 1e3,
1245
+ m: MINUTE,
1246
+ h: 60 * MINUTE,
1247
+ d: 1440 * MINUTE
1248
+ };
1249
+ const DAY = UNITS.d;
1250
+ const EPOCH_MS = new RegExp(`^\\d{10,}$`);
1251
+ const TIME_HELP = "An ISO 8601 time, epoch milliseconds, or a time ago such as \"30m\", \"2h\" or \"7d\".";
1252
+ const READ_ONLY = { readOnlyHint: true };
1253
+ function time(value, name, now) {
1254
+ if (value === void 0) return void 0;
1255
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1256
+ if (typeof value === "string") {
1257
+ if (EPOCH_MS.test(value.trim())) return Number(value.trim());
1258
+ const ago = /^(\d+)\s*([smhd])$/.exec(value.trim());
1259
+ if (ago) return now - Number(ago[1]) * UNITS[ago[2]];
1260
+ const parsed = Date.parse(value);
1261
+ if (!Number.isNaN(parsed)) return parsed;
1262
+ }
1263
+ throw new Error(`${name} must be an ISO 8601 time, epoch milliseconds, or a time ago such as "30m", "2h" or "7d".`);
1102
1264
  }
1103
- const NOT_COPIED = /* @__PURE__ */ new Set([
1104
- "set-cookie",
1105
- "content-length",
1106
- "content-encoding",
1107
- "transfer-encoding",
1108
- "connection",
1109
- "keep-alive"
1110
- ]);
1111
- const digest = (value) => createHash("sha256").update(value).digest();
1112
- /** Whether `candidate` is one of `tokens`, in the same time whichever it is. */
1113
- function isToken(candidate, tokens) {
1114
- if (candidate === void 0) return false;
1115
- const given = digest(candidate);
1116
- let match = false;
1117
- for (const token of tokens) if (timingSafeEqual(given, digest(token))) match = true;
1118
- return match;
1265
+ function window(args, defaultSpanMs) {
1266
+ const now = Date.now();
1267
+ const to = time(args.to, "to", now) ?? now;
1268
+ const from = time(args.from, "from", now) ?? to - defaultSpanMs;
1269
+ if (from > to) throw new Error("from must not be after to.");
1270
+ return {
1271
+ from,
1272
+ to
1273
+ };
1119
1274
  }
1120
- /** The secret in an `Authorization` header: a Bearer token, or a Basic password. */
1121
- function credential(request) {
1122
- const header = request.headers.authorization;
1123
- if (!header) return void 0;
1124
- const space = header.indexOf(" ");
1125
- if (space < 0) return void 0;
1126
- const scheme = header.slice(0, space).toLowerCase();
1127
- const value = header.slice(space + 1).trim();
1128
- if (scheme === "bearer") return value;
1129
- if (scheme === "basic") {
1130
- const decoded = Buffer.from(value, "base64").toString("utf8");
1131
- const colon = decoded.indexOf(":");
1132
- return colon < 0 ? void 0 : decoded.slice(colon + 1);
1133
- }
1275
+ function integer(args, name, min, max, fallback) {
1276
+ const value = args[name];
1277
+ if (value === void 0) return fallback;
1278
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new Error(`${name} must be a whole number.`);
1279
+ return Math.min(Math.max(value, min), max);
1134
1280
  }
1135
- /** The protocol the client used: https when a proxy in front terminated TLS and says so. */
1136
- function requestProtocol(request) {
1137
- const forwarded = request.headers["x-forwarded-proto"];
1138
- return (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(",")[0]?.trim() === "https" ? "https" : "http";
1281
+ function text$1(args, name) {
1282
+ const value = args[name];
1283
+ if (value === void 0) return void 0;
1284
+ if (typeof value !== "string") throw new Error(`${name} must be a string.`);
1285
+ return value.trim() || void 0;
1139
1286
  }
1140
- /** The request as the app's `authorize` sees it: standard, with no body. */
1141
- function webRequest(request) {
1142
- const headers = new Headers();
1143
- for (const [name, value] of Object.entries(request.headers)) {
1144
- if (value === void 0) continue;
1145
- try {
1146
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
1147
- } catch {}
1287
+ const iso = (ms) => new Date(ms).toISOString();
1288
+ const round = (ms) => ms === void 0 ? void 0 : Math.round(ms * 10) / 10;
1289
+ const cut = (value, limit) => value !== void 0 && value.length > limit ? `${value.slice(0, limit)}… [${value.length - limit} more characters]` : value;
1290
+ const compactJson = (value) => JSON.stringify(value);
1291
+ // src/dashboard-mcp-docs.ts
1292
+ /** An answer about the OpenAPI document or a docs page is cut to about this many characters. */
1293
+ const MAX_DOCS_CHARS = 5e4;
1294
+ const MAX_OPERATIONS_LISTED = 300;
1295
+ const MAX_REFERENCED_SCHEMAS = 100;
1296
+ /** The last resort for an operation too large to show: how much of it to try, each time half as much. */
1297
+ const PREVIEW_CHARS_MOST_FIRST = [
1298
+ 25e3,
1299
+ 1e4,
1300
+ 2e3
1301
+ ];
1302
+ const MAX_NAMED_SCHEMAS = 20;
1303
+ const MAX_NAME_CHARS = 200;
1304
+ const HTTP_METHODS = [
1305
+ "get",
1306
+ "put",
1307
+ "post",
1308
+ "delete",
1309
+ "options",
1310
+ "head",
1311
+ "patch",
1312
+ "trace"
1313
+ ];
1314
+ const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();
1315
+ function pickDocument(documents, name) {
1316
+ const found = name ? documents.find((item) => sameName(item.title, name)) : documents[0];
1317
+ if (!found) throw new Error(`No OpenAPI document called ${name}. The app has: ${documents.map((item) => item.title).join(", ")}.`);
1318
+ return found;
1319
+ }
1320
+ /** Each operation of a document: its method and path, and the operation object. */
1321
+ function operationsOf(document) {
1322
+ const found = [];
1323
+ for (const [path, item] of Object.entries(document.paths ?? {})) for (const method of HTTP_METHODS) if (item?.[method]) found.push({
1324
+ method,
1325
+ path,
1326
+ operation: item[method]
1327
+ });
1328
+ return found;
1329
+ }
1330
+ /** `GET /api/pages/:id` and `get /api/pages/{id}` are the same operation. */
1331
+ const normalizePath = (path) => path.replace(/:(\w+)/g, "{$1}");
1332
+ function findOperation(document, wanted) {
1333
+ const operations = operationsOf(document);
1334
+ const spaced = /^(\w+)\s+(\S+)$/.exec(wanted.trim());
1335
+ const found = spaced ? operations.find((item) => sameName(item.method, spaced[1]) && item.path === normalizePath(spaced[2])) : operations.find((item) => item.operation.operationId === wanted.trim());
1336
+ if (!found) throw new Error(`No operation ${wanted} in that document. Call get_openapi without operation to list them.`);
1337
+ return found;
1338
+ }
1339
+ /** The schemas an operation points to with `$ref`, and those they point to in turn. */
1340
+ function referencedSchemas(document, operation) {
1341
+ const schemas = {};
1342
+ const pending = [operation];
1343
+ while (pending.length && Object.keys(schemas).length < MAX_REFERENCED_SCHEMAS) {
1344
+ const value = pending.pop();
1345
+ if (Array.isArray(value)) pending.push(...value);
1346
+ else if (value && typeof value === "object") for (const [key, entry] of Object.entries(value)) if (key === "$ref" && typeof entry === "string") {
1347
+ const target = entry.startsWith("#/") ? entry.slice(2).split("/").reduce((at, part) => at?.[part], document) : void 0;
1348
+ if (target !== void 0 && !(entry in schemas)) {
1349
+ schemas[entry] = target;
1350
+ pending.push(target);
1351
+ }
1352
+ } else pending.push(entry);
1148
1353
  }
1149
- const protocol = requestProtocol(request);
1150
- const host = request.headers.host ?? "localhost";
1151
- let url;
1152
- try {
1153
- url = new URL(request.url ?? "/", `${protocol}://${host}`).href;
1154
- } catch {
1155
- url = `${protocol}://localhost${request.url ?? "/"}`;
1354
+ return schemas;
1355
+ }
1356
+ function getOpenapi(documents, args) {
1357
+ const { title, document } = pickDocument(documents, text$1(args, "document"));
1358
+ const wanted = text$1(args, "operation");
1359
+ if (!wanted) {
1360
+ const operations = operationsOf(document);
1361
+ const listed = operations.slice(0, MAX_OPERATIONS_LISTED);
1362
+ return compactJson({
1363
+ documents: documents.map((item) => item.title),
1364
+ document: title,
1365
+ info: document.info,
1366
+ servers: document.servers,
1367
+ operations: listed.map(({ method, path, operation }) => ({
1368
+ method: method.toUpperCase(),
1369
+ path,
1370
+ operationId: operation.operationId,
1371
+ summary: operation.summary,
1372
+ tags: operation.tags
1373
+ })),
1374
+ ...listed.length < operations.length ? { note: `${operations.length - listed.length} more operations are left out. Ask for one by operation.` } : {}
1375
+ });
1156
1376
  }
1157
- return new Request(url, {
1158
- method: request.method ?? "GET",
1159
- headers
1377
+ const { method, path, operation } = findOperation(document, wanted);
1378
+ const schemas = referencedSchemas(document, operation);
1379
+ const answer = (parts, note) => compactJson({
1380
+ document: cut(title, MAX_NAME_CHARS),
1381
+ method: method.toUpperCase(),
1382
+ path: cut(path, MAX_NAME_CHARS),
1383
+ operation: parts.operation,
1384
+ referenced: parts.schemas,
1385
+ ...note ? { note } : {}
1160
1386
  });
1161
- }
1162
- const isIdentity = (value) => typeof value === "object" && value !== null && !(value instanceof Response) && typeof value.user?.id === "string";
1163
- const refusal = (status, body, headers = {}) => ({
1164
- allowed: false,
1165
- status,
1166
- body,
1167
- headers: {
1168
- "content-type": "text/plain; charset=utf-8",
1169
- ...headers
1387
+ let result = answer({
1388
+ operation,
1389
+ schemas
1390
+ });
1391
+ if (result.length <= 5e4) return result;
1392
+ result = answer({
1393
+ operation,
1394
+ schemas: Object.keys(schemas)
1395
+ }, "Cut to fit about 50 KB: the schemas the operation refers to are named, not shown.");
1396
+ if (result.length <= 5e4) return result;
1397
+ const names = Object.keys(schemas).slice(0, MAX_NAMED_SCHEMAS).map((name) => cut(name, MAX_NAME_CHARS));
1398
+ const json = JSON.stringify(operation);
1399
+ for (const chars of PREVIEW_CHARS_MOST_FIRST) {
1400
+ result = answer({
1401
+ operation: { preview: cut(json, chars) },
1402
+ schemas: names
1403
+ }, "Cut to fit about 50 KB: the operation itself is too large, so only its start is shown.");
1404
+ if (result.length <= 5e4) return result;
1170
1405
  }
1171
- });
1172
- /**
1173
- * The check for the dashboard's requests. A request passes with a valid token,
1174
- * or when the app's `authorize` returns `true` or an identity (`{ user }`). Anything else is answered:
1175
- * what `authorize` returned if it returned a `Response`, else 401 (with a
1176
- * browser sign-in prompt when tokens are in use), and 503 when `authorize`
1177
- * threw or ran out of time, since a check that cannot answer must not let
1178
- * anyone in.
1179
- */
1180
- function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS) {
1181
- const tokens = auth.token === void 0 ? [] : typeof auth.token === "string" ? [auth.token] : [...auth.token];
1182
- const prompt = tokens.length > 0 ? { "www-authenticate": "Basic realm=\"Brick dashboard\", charset=\"UTF-8\"" } : {};
1183
- return async (request) => {
1184
- if (tokens.length > 0 && isToken(credential(request), tokens)) return {
1185
- allowed: true,
1186
- identity: {}
1187
- };
1188
- if (!auth.authorize) return refusal(401, "Unauthorized", prompt);
1189
- let decision;
1190
- let timer;
1191
- try {
1192
- decision = await Promise.race([Promise.resolve(auth.authorize(webRequest(request))), new Promise((_, reject) => {
1193
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error("dashboard authorize timed out")), timeoutMs);
1194
- })]);
1195
- } catch (error) {
1196
- onError(error);
1197
- return refusal(503, "Sign-in is unavailable.");
1198
- } finally {
1199
- clearTimeout(timer);
1200
- }
1201
- if (decision === true) return {
1202
- allowed: true,
1203
- identity: {}
1204
- };
1205
- if (isIdentity(decision)) return {
1206
- allowed: true,
1207
- identity: { user: {
1208
- id: decision.user.id,
1209
- ...typeof decision.user.name === "string" ? { name: decision.user.name } : {}
1210
- } }
1211
- };
1212
- if (decision instanceof Response) {
1213
- const headers = {};
1214
- decision.headers.forEach((value, name) => {
1215
- if (!NOT_COPIED.has(name)) headers[name] = value;
1216
- });
1217
- const cookies = decision.headers.getSetCookie();
1218
- if (cookies.length > 0) headers["set-cookie"] = cookies;
1219
- return {
1220
- allowed: false,
1221
- status: decision.status,
1222
- headers,
1223
- body: new Uint8Array(await decision.arrayBuffer())
1224
- };
1406
+ return answer({
1407
+ operation: "left out",
1408
+ schemas: names
1409
+ }, `The operation is ${json.length} characters long, too large to show even cut down. Read it in the dashboard's APIs view.`);
1410
+ }
1411
+ /** The pages of the docs tree in order, each with the folders it sits in. */
1412
+ function pagesOf(nodes, section) {
1413
+ return nodes.flatMap((node) => {
1414
+ if (node.type === "page") return [{
1415
+ path: node.url.replace(/^\//, ""),
1416
+ title: node.name,
1417
+ description: node.description,
1418
+ section
1419
+ }];
1420
+ if (node.type !== "folder") return [];
1421
+ return [...node.index ? [{
1422
+ path: node.index.url.replace(/^\//, ""),
1423
+ title: node.index.name,
1424
+ section: node.name
1425
+ }] : [], ...pagesOf(node.children, node.name)];
1426
+ });
1427
+ }
1428
+ /** What the APIs view and the Docs view show, while the dashboard serves them. */
1429
+ function docsTools(sources) {
1430
+ const dev = sources.mode === "dev";
1431
+ const documents = () => sources.store.apiDocuments();
1432
+ const docs = () => dev ? sources.docs?.() : void 0;
1433
+ return [
1434
+ {
1435
+ definition: {
1436
+ name: "get_openapi",
1437
+ description: "The app's OpenAPI documents, as the APIs view renders them. Without operation it lists the operations of one document (method, path, operation id, summary, tags) with its info and servers. With operation (\"POST /api/orders/order\" or an operation id) it returns that operation in full, with the schemas it refers to. Output is cut to about 50 KB and says what was left out. Only under `brick dev`.",
1438
+ inputSchema: {
1439
+ type: "object",
1440
+ properties: {
1441
+ document: {
1442
+ type: "string",
1443
+ description: "The document's title. Default: the first, which is the app's own."
1444
+ },
1445
+ operation: {
1446
+ type: "string",
1447
+ description: "One operation: \"METHOD /path\" (the path as in the document, `{id}` or `:id`), or its operationId."
1448
+ }
1449
+ },
1450
+ additionalProperties: false
1451
+ },
1452
+ annotations: READ_ONLY
1453
+ },
1454
+ available: () => dev && documents().length > 0,
1455
+ run: (args) => getOpenapi(documents(), args)
1456
+ },
1457
+ {
1458
+ definition: {
1459
+ name: "list_docs",
1460
+ description: "The app's developer documentation, as the Docs view lists it: each page's path, title and description, in order, with the section it sits in. Open one with read_doc. Only under `brick dev`, and only for an app that sets `documentation`.",
1461
+ inputSchema: {
1462
+ type: "object",
1463
+ properties: {},
1464
+ additionalProperties: false
1465
+ },
1466
+ annotations: READ_ONLY
1467
+ },
1468
+ available: () => docs() !== void 0,
1469
+ run: () => {
1470
+ const { tree } = docs().info();
1471
+ return compactJson({
1472
+ title: tree.name,
1473
+ pages: pagesOf(tree.children)
1474
+ });
1475
+ }
1476
+ },
1477
+ {
1478
+ definition: {
1479
+ name: "read_doc",
1480
+ description: `One page of the app's developer documentation, by path: its title, description and source (Markdown or MDX, without the frontmatter), cut to about ${MAX_DOCS_CHARS / 1e3} KB with a note when it is longer. Only under \`brick dev\`, and only for an app that sets \`documentation\`.`,
1481
+ inputSchema: {
1482
+ type: "object",
1483
+ properties: { path: {
1484
+ type: "string",
1485
+ description: "From list_docs, such as \"guide/setup\". The home page is \"\" or \"/\"."
1486
+ } },
1487
+ required: ["path"],
1488
+ additionalProperties: false
1489
+ },
1490
+ annotations: READ_ONLY
1491
+ },
1492
+ available: () => docs() !== void 0,
1493
+ run: (args) => {
1494
+ const path = args.path;
1495
+ if (typeof path !== "string") throw new Error("path is required.");
1496
+ const page = docs().source(path.split("/").filter(Boolean));
1497
+ if (!page) throw new Error(`No docs page at ${JSON.stringify(path)}. Call list_docs for the paths.`);
1498
+ return compactJson({
1499
+ title: page.title,
1500
+ description: page.description,
1501
+ file: page.path,
1502
+ content: cut(page.content, MAX_DOCS_CHARS),
1503
+ ...page.content.length > 5e4 ? { note: `The page is ${page.content.length} characters long and was cut to ${MAX_DOCS_CHARS}.` } : {}
1504
+ });
1505
+ }
1225
1506
  }
1226
- return refusal(401, "Unauthorized", prompt);
1227
- };
1507
+ ];
1228
1508
  }
1229
- // src/dev-dashboard.ts
1230
- const KEEPALIVE_MS = 15e3;
1231
- const MAX_INGEST_BYTES = 5242880;
1232
- const MAX_PROXY_BYTES = 10485760;
1233
- const NOT_FORWARDED = /* @__PURE__ */ new Set([
1234
- "host",
1235
- "connection",
1236
- "keep-alive",
1237
- "proxy-connection",
1238
- "transfer-encoding",
1239
- "te",
1240
- "trailer",
1241
- "upgrade",
1242
- "content-length",
1243
- "accept-encoding",
1244
- "origin",
1245
- "referer",
1246
- "cookie"
1247
- ]);
1248
- const NOT_RETURNED = /* @__PURE__ */ new Set([
1249
- "connection",
1250
- "keep-alive",
1251
- "transfer-encoding",
1252
- "content-length",
1253
- "content-encoding",
1254
- "set-cookie"
1255
- ]);
1256
- const PRODUCTION_HEADERS = {
1257
- "x-content-type-options": "nosniff",
1258
- "x-frame-options": "DENY",
1259
- "referrer-policy": "no-referrer",
1260
- "cross-origin-opener-policy": "same-origin",
1261
- "cross-origin-resource-policy": "same-origin",
1262
- "cache-control": "no-store",
1263
- "content-security-policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
1264
- };
1265
- /** How long `/_health` waits for the app before calling it down. */
1266
- const PROBE_TIMEOUT_MS = 3e3;
1509
+ const DOCS_TOOL_NAMES = [
1510
+ "get_openapi",
1511
+ "list_docs",
1512
+ "read_doc"
1513
+ ];
1514
+ // src/dev-history.ts
1515
+ const DAY_MS = 864e5;
1516
+ const MAX_TRACES = 1e5;
1517
+ const FLUSH_MS = 250;
1518
+ const PRUNE_MS = 18e5;
1519
+ const VOLUME_BUCKETS = 48;
1520
+ const MAX_LIMIT = 500;
1521
+ const MAX_EXPORT_ROWS = 1e5;
1522
+ /** A log search reads the spans of this many requests, the newest of its window. */
1523
+ const MAX_SCANNED_REQUESTS = 2e4;
1524
+ /** A text search reads at most this many log lines, newest first, of those requests. */
1525
+ const MAX_SCANNED_LOG_LINES = 1e5;
1267
1526
  /**
1268
- * Serve the dashboard, on loopback unless told otherwise. On loopback requests
1269
- * must name a local host (blocks DNS rebinding), and restart requires a header
1270
- * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is
1271
- * required and decides who gets in. Uses node:http, so it runs under Bun and
1272
- * under Node (Vite's dev server runs under Node).
1527
+ * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and
1528
+ * `node:sqlite` under Node, which is what runs Vite's dev server. Both are
1529
+ * imported by a variable name so bundlers leave them alone.
1273
1530
  */
1274
- function startDevDashboard(options) {
1275
- const host = options.host ?? "127.0.0.1";
1276
- const loopback = isLoopbackHost(host);
1277
- const production = options.mode === "production";
1278
- if (!loopback && !options.auth) return Promise.reject(new ConfigError(`Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`));
1279
- let theme;
1280
- try {
1281
- theme = themeCss(options.dashboard?.theme);
1282
- } catch (error) {
1283
- return Promise.reject(error);
1531
+ async function openDatabase(file) {
1532
+ if (typeof Bun !== "undefined") {
1533
+ const { Database } = await import("bun:sqlite");
1534
+ return new Database(file, { create: true });
1284
1535
  }
1285
- const extension = options.dashboard?.extension || !production || options.plugins?.some((plugin) => plugin.dashboard) ? new DashboardExtensions(options.dashboard?.extension, (message) => console.warn(message)) : void 0;
1286
- const access = options.auth ? createAccess(options.auth, (error) => console.error("[Brick-TS] The dashboard sign-in check failed:", error)) : void 0;
1287
- let allowedHosts = /* @__PURE__ */ new Set();
1288
- const server = createServer((request, response) => {
1289
- respond(request, response).catch((error) => {
1290
- console.error("[Brick-TS] The dashboard failed to answer:", error);
1291
- if (response.headersSent) response.end();
1292
- else send(response, 500, "Server error");
1293
- });
1536
+ const specifier = "node:sqlite";
1537
+ const emit = process.emitWarning;
1538
+ process.emitWarning = ((warning, ...rest) => {
1539
+ if (typeof warning === "string" && warning.includes("SQLite")) return;
1540
+ return emit.call(process, warning, ...rest);
1294
1541
  });
1295
- async function respond(request, response) {
1296
- if (production) for (const [name, value] of Object.entries(PRODUCTION_HEADERS)) response.setHeader(name, value);
1297
- if (loopback && !allowedHosts.has(request.headers.host ?? "")) {
1298
- send(response, 403, "Forbidden");
1299
- return;
1300
- }
1301
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
1302
- const route = matchRoute(request.method, url.pathname);
1303
- if (route === "health") {
1304
- await health(response);
1305
- return;
1306
- }
1307
- let identity = {};
1308
- if (access) {
1309
- const decision = await access(request);
1310
- if (!decision.allowed) {
1311
- send(response, decision.status, decision.body, decision.headers);
1312
- return;
1313
- }
1314
- identity = decision.identity;
1315
- }
1316
- if (!route || production && !servedInProduction(route)) {
1317
- send(response, 404, "Not found");
1318
- return;
1319
- }
1320
- if ("csrf" in ROUTES[route] && request.headers["x-brick-dashboard"] !== "1") {
1321
- send(response, 403, "Forbidden");
1322
- return;
1323
- }
1324
- await handlers[route](request, response, url, identity);
1542
+ try {
1543
+ const { DatabaseSync } = await import(specifier);
1544
+ return new DatabaseSync(file);
1545
+ } finally {
1546
+ process.emitWarning = emit;
1325
1547
  }
1326
- function servedInProduction(route) {
1327
- const served = ROUTES[route].production;
1328
- return served === "extension" ? Boolean(extension?.active) : served;
1548
+ }
1549
+ /**
1550
+ * Open the request history, or return undefined when it is turned off or this
1551
+ * runtime has no SQLite. Never throws: the dashboard works without history.
1552
+ */
1553
+ async function openHistory(options) {
1554
+ if (!(options.days > 0)) return void 0;
1555
+ try {
1556
+ const folder = join(options.directory, ".brick");
1557
+ mkdirSync(folder, { recursive: true });
1558
+ const ignore = join(folder, ".gitignore");
1559
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
1560
+ return new DevHistory(await openDatabase(join(folder, "telemetry.sqlite")), options.days, options.warn);
1561
+ } catch (error) {
1562
+ const reason = error instanceof Error ? error.message : String(error);
1563
+ options.warn?.(`[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`);
1564
+ return;
1329
1565
  }
1330
- /** 200 while the app answers its own health check, 503 when it does not. */
1331
- async function health(response) {
1332
- const probe = options.probe;
1333
- let up = true;
1334
- if (probe) {
1335
- let timer;
1336
- up = await Promise.race([probe().catch(() => false), new Promise((resolve) => {
1337
- timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);
1338
- })]);
1339
- clearTimeout(timer);
1340
- }
1341
- send(response, up ? 200 : 503, JSON.stringify({
1342
- status: up ? "ok" : "degraded",
1343
- ...probe ? { app: up ? "up" : "down" } : {}
1344
- }), {
1345
- "content-type": "application/json",
1346
- "cache-control": "no-store"
1347
- });
1566
+ }
1567
+ const text = (value) => value === null || value === void 0 ? void 0 : String(value);
1568
+ const number = (value) => value === null || value === void 0 ? void 0 : Number(value);
1569
+ const LOG_LEVEL_SQL = `CASE WHEN json_extract(event.value, '$.attributes."${ATTR.logLevel}"') IN (${LOG_LEVELS.map((level) => `'${level}'`).join(", ")})
1570
+ THEN json_extract(event.value, '$.attributes."${ATTR.logLevel}"') ELSE 'info' END`;
1571
+ const LOG_MESSAGE_SQL = `COALESCE(json_extract(event.value, '$.attributes."${ATTR.logMessage}"'), '')`;
1572
+ /** Each row's outcome, by the rules of `outcomeOf`. */
1573
+ const OUTCOME_CASE = `CASE
1574
+ WHEN status = 'error' OR http_status >= 500 THEN 'server'
1575
+ WHEN http_status >= 400 THEN 'client'
1576
+ ELSE 'ok' END`;
1577
+ const FACET_COLUMNS = {
1578
+ outcome: OUTCOME_CASE,
1579
+ method: "method",
1580
+ service: "service",
1581
+ endpoint: "endpoint"
1582
+ };
1583
+ /** The WHERE clause for a query, leaving out one filter when counting its facet. */
1584
+ function filterSql(query, skip) {
1585
+ const clauses = ["start_ms >= ?", "start_ms <= ?"];
1586
+ const params = [query.from, query.to];
1587
+ const anyOf = (column, values) => {
1588
+ if (!values || values.length === 0) return;
1589
+ clauses.push(`${column} IN (${values.map(() => "?").join(", ")})`);
1590
+ params.push(...values);
1591
+ };
1592
+ if (skip !== "endpoint") anyOf("endpoint", query.endpoints);
1593
+ if (skip !== "method") anyOf("method", query.methods);
1594
+ if (skip !== "service") anyOf("service", query.services);
1595
+ if (skip !== "outcome") anyOf(OUTCOME_CASE, query.outcomes);
1596
+ if (query.minMs !== void 0 && query.minMs > 0) {
1597
+ clauses.push("duration_ms >= ?");
1598
+ params.push(query.minMs);
1348
1599
  }
1349
- const handlers = {
1350
- shell: (_request, response) => send(response, 200, dashboardShell({
1351
- extension: extension?.active ? {
1352
- revision: extension.revision,
1353
- js: Boolean(extension.built),
1354
- css: Boolean(extension.built?.css)
1355
- } : void 0,
1356
- theme: theme !== "",
1357
- mode: production ? "production" : "dev"
1358
- }), {
1359
- "content-type": "text/html; charset=utf-8",
1360
- "cache-control": "no-store"
1361
- }),
1362
- assets(_request, response, url) {
1363
- const name = url.pathname.slice(ROUTES.assets.path.length + 1);
1364
- const own = name === ASSETS.theme ? theme : extension?.asset(name);
1365
- if (own !== void 0) send(response, 200, own, {
1366
- "content-type": assetType(name),
1367
- "cache-control": "no-store"
1368
- });
1369
- else serveAsset(response, name);
1370
- },
1371
- app,
1372
- state: (_request, response) => json(response, snapshot()),
1373
- events: eventStream,
1374
- history(_request, response, url) {
1375
- if (options.history) history(options.history, url.pathname, url.searchParams, response);
1376
- else send(response, 404, "Not found");
1377
- },
1378
- docs: (_request, response, url) => docsRoute(response, url.pathname, url.searchParams),
1379
- openapi: (_request, response) => json(response, options.store.apiDocuments()),
1380
- proxy,
1381
- workflows(request, response, url) {
1382
- frameOnlyHere(response);
1383
- return inspector(request, response, url);
1384
- },
1385
- schedules: (request, response, url) => inspector(request, response, url),
1386
- ingest,
1387
- restart(request, response) {
1388
- if (!options.restart) {
1389
- send(response, 404, "Not found");
1390
- return;
1391
- }
1392
- options.restart();
1393
- send(response, 202, "");
1394
- }
1600
+ const needle = query.query?.trim();
1601
+ if (needle) {
1602
+ const pattern = `%${needle.replace(/[\\%_]/g, "\\$&")}%`;
1603
+ clauses.push(`(${SEARCHED.map((column) => `${column} LIKE ? ESCAPE '\\'`).join(" OR ")})`);
1604
+ params.push(...SEARCHED.map(() => pattern));
1605
+ }
1606
+ return {
1607
+ sql: clauses.join(" AND "),
1608
+ params
1395
1609
  };
1396
- function snapshot() {
1397
- return {
1398
- ...options.store.snapshot(),
1399
- canRestart: Boolean(options.restart),
1400
- historyDays: options.history?.days ?? 0,
1401
- mode: production ? "production" : "dev",
1402
- extension: extension?.active ? {
1403
- revision: extension.revision,
1404
- error: extension.error
1405
- } : null
1406
- };
1610
+ }
1611
+ const orderSql = (sort) => sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
1612
+ const LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,
1613
+ start_ms, end_ms, duration_ms, status, truncated, service, action, message`;
1614
+ function toHistoryTrace(row) {
1615
+ return {
1616
+ traceId: String(row.trace_id),
1617
+ name: String(row.name),
1618
+ endpoint: String(row.endpoint),
1619
+ method: text(row.method),
1620
+ route: text(row.route),
1621
+ path: text(row.path),
1622
+ httpStatus: number(row.http_status),
1623
+ generation: Number(row.generation),
1624
+ startMs: Number(row.start_ms),
1625
+ endMs: number(row.end_ms),
1626
+ durationMs: number(row.duration_ms),
1627
+ status: String(row.status),
1628
+ truncated: Number(row.truncated) === 1,
1629
+ service: text(row.service),
1630
+ action: text(row.action),
1631
+ message: text(row.message)
1632
+ };
1633
+ }
1634
+ /**
1635
+ * Requests kept on disk between runs, for looking back over weeks
1636
+ * instead of the last few minutes. Writes are batched; reads see them.
1637
+ */
1638
+ var DevHistory = class {
1639
+ days;
1640
+ #database;
1641
+ #pendingTraces = /* @__PURE__ */ new Map();
1642
+ #flushTimer;
1643
+ #pruneTimer;
1644
+ #closed = false;
1645
+ #warn;
1646
+ /** Failure kinds already reported: one warning each, not one per batch. */
1647
+ #warned = /* @__PURE__ */ new Set();
1648
+ constructor(database, days, warn) {
1649
+ this.#database = database;
1650
+ this.days = days;
1651
+ this.#warn = warn;
1652
+ database.exec(`
1653
+ PRAGMA journal_mode = WAL;
1654
+ PRAGMA synchronous = NORMAL;
1655
+ PRAGMA busy_timeout = 2000;
1656
+ CREATE TABLE IF NOT EXISTS traces (
1657
+ trace_id TEXT PRIMARY KEY,
1658
+ name TEXT NOT NULL,
1659
+ endpoint TEXT NOT NULL,
1660
+ method TEXT,
1661
+ route TEXT,
1662
+ path TEXT,
1663
+ http_status INTEGER,
1664
+ generation INTEGER NOT NULL,
1665
+ start_ms INTEGER NOT NULL,
1666
+ end_ms INTEGER,
1667
+ duration_ms REAL,
1668
+ status TEXT NOT NULL,
1669
+ truncated INTEGER NOT NULL,
1670
+ spans TEXT NOT NULL,
1671
+ service TEXT,
1672
+ action TEXT,
1673
+ message TEXT
1674
+ );
1675
+ CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);
1676
+ CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);
1677
+ -- Earlier versions kept failures here; nothing reads them now.
1678
+ DROP TABLE IF EXISTS failures;
1679
+ `);
1680
+ this.#addMissingColumns();
1681
+ this.prune();
1682
+ this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);
1683
+ this.#pruneTimer.unref?.();
1407
1684
  }
1408
- /**
1409
- * Accept telemetry from an application process that cannot share memory with
1410
- * the dashboard, such as a dev server worker: span batches, and a notice when
1411
- * the app loads.
1412
- */
1413
- async function ingest(request, response) {
1414
- const body = await readBytes(request, MAX_INGEST_BYTES);
1415
- if (!body) {
1416
- tooLarge(response);
1417
- return;
1685
+ /** A folder from an earlier version has the table without the newer columns. */
1686
+ #addMissingColumns() {
1687
+ const present = new Set(this.#database.prepare("PRAGMA table_info(traces)").all().map((column) => String(column.name)));
1688
+ for (const column of [
1689
+ "service",
1690
+ "action",
1691
+ "message"
1692
+ ]) if (!present.has(column)) this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);
1693
+ }
1694
+ /** Queue a finished request. A later save of the same request replaces it. */
1695
+ saveTrace(trace) {
1696
+ if (this.#closed) return;
1697
+ this.#pendingTraces.set(trace.traceId, trace);
1698
+ this.#scheduleFlush();
1699
+ }
1700
+ #scheduleFlush() {
1701
+ if (this.#flushTimer) return;
1702
+ this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
1703
+ this.#flushTimer.unref?.();
1704
+ }
1705
+ flush() {
1706
+ if (this.#flushTimer) {
1707
+ clearTimeout(this.#flushTimer);
1708
+ this.#flushTimer = void 0;
1418
1709
  }
1419
- let payload;
1710
+ if (this.#closed || this.#pendingTraces.size === 0) return;
1711
+ const traces = [...this.#pendingTraces.values()];
1712
+ this.#pendingTraces.clear();
1420
1713
  try {
1421
- payload = JSON.parse(Buffer.from(body).toString("utf8"));
1422
- } catch {
1423
- payload = null;
1424
- }
1425
- if (payload === null || typeof payload !== "object") {
1426
- send(response, 400, "Bad request");
1427
- return;
1714
+ this.#database.exec("BEGIN");
1715
+ const saveTrace = this.#database.prepare(`INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,
1716
+ http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,
1717
+ service, action, message)
1718
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
1719
+ for (const trace of traces) saveTrace.run(trace.traceId, trace.name, endpointOf(trace), trace.method ?? null, trace.route ?? null, trace.path ?? null, trace.httpStatus ?? null, trace.generation, trace.startMs, trace.endMs ?? null, trace.durationMs ?? null, trace.status, trace.truncated ? 1 : 0, JSON.stringify(trace.spans), trace.service ?? null, trace.action ?? null, trace.message ?? null);
1720
+ this.#database.exec("COMMIT");
1721
+ } catch (error) {
1722
+ this.#warnOnce("save requests to", error);
1723
+ try {
1724
+ this.#database.exec("ROLLBACK");
1725
+ } catch {}
1428
1726
  }
1429
- if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
1430
- if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
1431
- send(response, 204, "");
1432
1727
  }
1433
- async function docsRoute(response, pathname, params) {
1434
- const docs = options.docs?.();
1435
- if (!docs) {
1436
- send(response, 404, "The app has no documentation.");
1437
- return;
1438
- }
1728
+ /** Drop what is past retention, then the oldest beyond the size cap. */
1729
+ prune(now = Date.now()) {
1730
+ if (this.#closed) return;
1439
1731
  try {
1440
- if (pathname === DOCS_PATHS.info) return json(response, docs.info());
1441
- if (pathname === DOCS_PATHS.search) return json(response, await docs.search(params.get("q") ?? ""));
1442
- if (pathname === DOCS_PATHS.components) {
1443
- const code = await docs.components();
1444
- if (code === void 0) return send(response, 404, "No components.");
1445
- return send(response, 200, code, {
1446
- "content-type": "text/javascript; charset=utf-8",
1447
- "cache-control": "no-store"
1448
- });
1449
- }
1450
- const pagePrefix = DOCS_PATHS.page;
1451
- if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {
1452
- const slugs = pathname.slice(pagePrefix.length).split("/").filter(Boolean).map(decodeURIComponent);
1453
- const page = await docs.page(slugs);
1454
- return page ? json(response, page) : send(response, 404, "No such page.");
1455
- }
1456
- const filePrefix = `${DOCS_PATHS.files}/`;
1457
- if (pathname.startsWith(filePrefix)) {
1458
- const file = await docs.file(pathname.slice(filePrefix.length).split("/").map(decodeURIComponent).join("/"));
1459
- if (!file) return send(response, 404, "No such file.");
1460
- return send(response, 200, file.body, {
1461
- "content-type": file.type,
1462
- "cache-control": "no-store",
1463
- "content-security-policy": "sandbox"
1464
- });
1465
- }
1466
- send(response, 404, "Not found");
1732
+ const cutoff = now - this.days * DAY_MS;
1733
+ this.#database.prepare("DELETE FROM traces WHERE start_ms < ?").run(cutoff);
1734
+ const count = Number(this.#database.prepare("SELECT COUNT(*) AS n FROM traces").get()?.n ?? 0);
1735
+ if (count > MAX_TRACES) this.#database.prepare("DELETE FROM traces WHERE trace_id IN (SELECT trace_id FROM traces ORDER BY start_ms ASC LIMIT ?)").run(count - MAX_TRACES);
1467
1736
  } catch (error) {
1468
- send(response, error instanceof URIError ? 400 : 500, error instanceof Error ? error.message : String(error));
1737
+ this.#warnOnce("prune", error);
1469
1738
  }
1470
1739
  }
1471
- /**
1472
- * Pass a request to the workflow inspector, which the app serves on a port of
1473
- * its own, and stream its answer back (it follows a run's output as it
1474
- * grows). Anyone who can open the dashboard may look, but a change must come
1475
- * from the dashboard's own page: the inspector can cancel runs and resume
1476
- * hooks, and a page on another site could otherwise post to it.
1477
- */
1478
- async function inspector(request, response, url) {
1479
- const target = options.store.inspectorTarget();
1480
- if (!target) {
1481
- send(response, 503, "The workflow inspector and schedules are not being served. The app may be restarting, or it may have neither workflows nor schedules.", { "content-type": "text/plain; charset=utf-8" });
1482
- return;
1483
- }
1484
- if (!isBodyless(request) && !fromOwnPage(request)) {
1485
- send(response, 403, "Forbidden");
1486
- return;
1487
- }
1488
- await forward(request, response, `http://127.0.0.1:${target.port}${url.pathname}${url.search}`, (headers) => headers.set(INSPECTOR_TOKEN_HEADER, target.token), "Could not reach the workflow inspector.");
1740
+ #warnOnce(action, error) {
1741
+ if (this.#warned.has(action)) return;
1742
+ this.#warned.add(action);
1743
+ const reason = error instanceof Error ? error.message : String(error);
1744
+ this.#warn?.(`[Brick-TS] Could not ${action} the request history (${reason}).`);
1489
1745
  }
1490
- /**
1491
- * Pass `/app/*` to the app, so the extension's pages read it from the
1492
- * dashboard's own origin. Only the dashboard's page may use it, as with the
1493
- * API proxy. A credential for the dashboard itself is not passed on; who the
1494
- * dashboard let in is, signed, for `ctx.dashboard` and `dashboardUser()`.
1495
- */
1496
- async function app(request, response, url, identity) {
1497
- if (!fromOwnPage(request)) {
1498
- send(response, 403, "Forbidden");
1499
- return;
1500
- }
1501
- const appUrl = options.appUrl ?? options.store.apiSnapshot()?.appUrl;
1502
- if (!appUrl) {
1503
- send(response, 503, "The app is not running yet.");
1504
- return;
1746
+ info() {
1747
+ this.flush();
1748
+ const row = this.#database.prepare("SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces").get();
1749
+ return {
1750
+ days: this.days,
1751
+ count: Number(row?.n ?? 0),
1752
+ oldestMs: number(row?.oldest)
1753
+ };
1754
+ }
1755
+ /** Matching requests, without spans, and how many match in total. */
1756
+ traces(query) {
1757
+ this.flush();
1758
+ const { sql, params } = filterSql(query);
1759
+ const total = Number(this.#database.prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`).get(...params)?.n ?? 0);
1760
+ const limit = Math.min(Math.max(query.limit ?? 100, 1), MAX_LIMIT);
1761
+ const offset = Math.max(query.offset ?? 0, 0);
1762
+ return {
1763
+ total,
1764
+ traces: this.#database.prepare(`SELECT ${LIST_COLUMNS}
1765
+ FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ? OFFSET ?`).all(...params, limit, offset).map(toHistoryTrace)
1766
+ };
1767
+ }
1768
+ /** Counts for each filter over the range, ignoring that filter's own choice. */
1769
+ facets(query) {
1770
+ this.flush();
1771
+ const count = (facet) => {
1772
+ const { sql, params } = filterSql(query, facet);
1773
+ const column = FACET_COLUMNS[facet];
1774
+ return this.#database.prepare(`SELECT ${column} AS value, COUNT(*) AS n FROM traces
1775
+ WHERE ${sql} AND ${column} IS NOT NULL
1776
+ GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`).all(...params, 30).map((row) => ({
1777
+ value: String(row.value),
1778
+ count: Number(row.n)
1779
+ }));
1780
+ };
1781
+ return {
1782
+ outcome: count("outcome"),
1783
+ method: count("method"),
1784
+ service: count("service"),
1785
+ endpoint: count("endpoint")
1786
+ };
1787
+ }
1788
+ /** Matching requests per time bucket across the range, by outcome. */
1789
+ volume(query, buckets = VOLUME_BUCKETS) {
1790
+ this.flush();
1791
+ const { sql, params } = filterSql(query);
1792
+ const bucketMs = bucketSize(query.from, query.to, buckets);
1793
+ const result = Array.from({ length: buckets }, (_, index) => ({
1794
+ start: query.from + index * bucketMs,
1795
+ ok: 0,
1796
+ client: 0,
1797
+ server: 0
1798
+ }));
1799
+ const rows = this.#database.prepare(`SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,
1800
+ COUNT(*) AS n
1801
+ FROM traces WHERE ${sql} GROUP BY bucket, outcome`).all(query.from, bucketMs, ...params);
1802
+ for (const row of rows) {
1803
+ const bucket = result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];
1804
+ const outcome = String(row.outcome);
1805
+ if (bucket) bucket[outcome] += Number(row.n);
1505
1806
  }
1506
- frameOnlyHere(response);
1507
- await forward(request, response, `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || "/"}${url.search}`, (headers) => {
1508
- if (access) headers.delete("authorization");
1509
- headers.set(DASHBOARD_IDENTITY_HEADER, signDashboardIdentity(identity));
1510
- }, "Could not reach the app.");
1807
+ return result;
1511
1808
  }
1512
- /**
1513
- * Send the request on to `target` and stream its answer back. `body`: the
1514
- * request's body when the caller already read it; else it is streamed.
1515
- */
1516
- async function forward(request, response, target, adjust, unreachable, body) {
1517
- const headers = forwardedHeaders(request);
1518
- adjust(headers);
1519
- const abort = new AbortController();
1520
- response.on("close", () => abort.abort());
1521
- try {
1522
- const upstream = await fetch(target, {
1523
- method: request.method,
1524
- headers,
1525
- redirect: "manual",
1526
- signal: abort.signal,
1527
- ...isBodyless(request) ? {} : body ? { body } : {
1528
- body: Readable.toWeb(request),
1529
- duplex: "half"
1530
- }
1531
- });
1532
- response.writeHead(upstream.status, returnedHeaders(upstream));
1533
- if (!upstream.body || request.method === "HEAD") {
1534
- response.end();
1535
- return;
1536
- }
1537
- await pipeline(Readable.fromWeb(upstream.body), response);
1538
- } catch {
1539
- if (response.headersSent) response.destroy();
1540
- else send(response, 502, unreachable);
1809
+ /** Every matching request, newest first, as CSV for a spreadsheet. */
1810
+ exportCsv(query) {
1811
+ this.flush();
1812
+ const { sql, params } = filterSql(query);
1813
+ return tracesToCsv(this.#database.prepare(`SELECT ${LIST_COLUMNS}
1814
+ FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ?`).all(...params, MAX_EXPORT_ROWS).map(toHistoryTrace));
1815
+ }
1816
+ trace(traceId) {
1817
+ this.flush();
1818
+ const row = this.#database.prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`).get(traceId);
1819
+ if (!row) return void 0;
1820
+ const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);
1821
+ return {
1822
+ ...trace,
1823
+ spans: JSON.parse(String(row.spans))
1824
+ };
1825
+ }
1826
+ /** How many requests match, how many failed, and how long they took. */
1827
+ summary(query) {
1828
+ this.flush();
1829
+ const { sql, params } = filterSql(query);
1830
+ let total = 0;
1831
+ let clientErrors = 0;
1832
+ let serverErrors = 0;
1833
+ const counts = this.#database.prepare(`SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n
1834
+ FROM traces WHERE ${sql} GROUP BY outcome`).all(...params);
1835
+ for (const row of counts) {
1836
+ const n = Number(row.n);
1837
+ total += n;
1838
+ if (row.outcome === "client") clientErrors = n;
1839
+ if (row.outcome === "server") serverErrors = n;
1541
1840
  }
1841
+ const durations = this.#database.prepare(`SELECT duration_ms FROM traces
1842
+ WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`).all(...params).map((row) => Number(row.duration_ms));
1843
+ return {
1844
+ total,
1845
+ clientErrors,
1846
+ serverErrors,
1847
+ medianMs: percentile(durations, .5),
1848
+ p95Ms: percentile(durations, .95)
1849
+ };
1542
1850
  }
1543
1851
  /**
1544
- * Send a request on to the app for the APIs view, which cannot call the app
1545
- * directly: it is another origin. Only the dashboard's own page may use this,
1546
- * and only to reach the app being shown. The address to call is `?url=`; a
1547
- * `?cookie=` is the cookie parameters the reader typed into Try it, and the
1548
- * only cookie the app is sent (the dashboard's own are never forwarded).
1852
+ * Log lines (span events named `log`) of the requests in a window, newest
1853
+ * first, found with SQLite's JSON functions over each request's stored spans.
1854
+ * Only the newest `MAX_SCANNED_REQUESTS` requests of the window are searched;
1855
+ * `requestsInWindow` says how many it held. SQLite's `LIKE` folds only
1856
+ * ASCII, so text is matched here, as the in-memory search does, over at most
1857
+ * `MAX_SCANNED_LOG_LINES` lines; `linesCapped` says it stopped there.
1549
1858
  */
1550
- async function proxy(request, response, url) {
1551
- if (!fromOwnPage(request)) {
1552
- send(response, 403, "Forbidden");
1553
- return;
1859
+ searchLogLines(search, page) {
1860
+ this.flush();
1861
+ const { sql, params } = filterSql({
1862
+ from: search.from,
1863
+ to: search.to,
1864
+ endpoints: search.endpoint ? [search.endpoint] : void 0,
1865
+ services: search.service ? [search.service] : void 0
1866
+ });
1867
+ const requestsInWindow = Number(this.#database.prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`).get(...params)?.n ?? 0);
1868
+ const clauses = [`json_extract(event.value, '$.name') = '${SPAN.logEvent}'`];
1869
+ const filters = [];
1870
+ if (search.level) {
1871
+ clauses.push(`${LOG_LEVEL_SQL} = ?`);
1872
+ filters.push(search.level);
1554
1873
  }
1555
- let target;
1874
+ const needle = search.query?.toLowerCase();
1875
+ const rows = this.#database.prepare(`WITH newest AS (
1876
+ SELECT trace_id, endpoint, spans FROM traces WHERE ${sql}
1877
+ ORDER BY start_ms DESC LIMIT ?)
1878
+ SELECT newest.trace_id, newest.endpoint,
1879
+ json_extract(span.value, '$.name') AS span_name,
1880
+ json_extract(event.value, '$.timeMs') AS time_ms,
1881
+ ${LOG_LEVEL_SQL} AS level, ${LOG_MESSAGE_SQL} AS message,
1882
+ span.key AS span_index, event.key AS event_index
1883
+ FROM newest, json_each(newest.spans) AS span,
1884
+ json_each(span.value, '$.events') AS event
1885
+ WHERE ${clauses.join(" AND ")}
1886
+ ORDER BY time_ms DESC, newest.trace_id ASC, span_index ASC, event_index ASC
1887
+ LIMIT ? OFFSET ?`).all(...params, MAX_SCANNED_REQUESTS, ...filters, needle === void 0 ? page.limit : MAX_SCANNED_LOG_LINES, needle === void 0 ? page.offset : 0);
1888
+ const lines = rows.map((row) => ({
1889
+ timeMs: Number(row.time_ms),
1890
+ level: String(row.level),
1891
+ message: String(row.message),
1892
+ traceId: String(row.trace_id),
1893
+ endpoint: String(row.endpoint),
1894
+ span: String(row.span_name),
1895
+ spanIndex: Number(row.span_index),
1896
+ eventIndex: Number(row.event_index)
1897
+ })).filter((line) => needle === void 0 || line.message.toLowerCase().includes(needle));
1898
+ return {
1899
+ requestsInWindow,
1900
+ lines: needle === void 0 ? lines : lines.slice(page.offset, page.offset + page.limit),
1901
+ linesCapped: needle !== void 0 && rows.length === 1e5
1902
+ };
1903
+ }
1904
+ slowestEndpoints(query, limit) {
1905
+ this.flush();
1906
+ const { sql, params } = filterSql(query);
1907
+ return this.#database.prepare(`SELECT endpoint, COUNT(*) AS n,
1908
+ SUM(CASE WHEN ${OUTCOME_CASE} = 'server' THEN 1 ELSE 0 END) AS errors,
1909
+ AVG(duration_ms) AS avg_ms, MAX(duration_ms) AS max_ms
1910
+ FROM traces WHERE ${sql} AND duration_ms IS NOT NULL
1911
+ GROUP BY endpoint ORDER BY avg_ms DESC, n DESC LIMIT ?`).all(...params, limit).map((row) => ({
1912
+ endpoint: String(row.endpoint),
1913
+ requests: Number(row.n),
1914
+ serverErrors: Number(row.errors),
1915
+ avgMs: Number(row.avg_ms),
1916
+ maxMs: Number(row.max_ms)
1917
+ }));
1918
+ }
1919
+ /** Write what is queued and release the database. */
1920
+ close() {
1921
+ if (this.#closed) return;
1922
+ this.flush();
1923
+ this.#closed = true;
1924
+ clearInterval(this.#pruneTimer);
1556
1925
  try {
1557
- target = new URL(url.searchParams.get("url") ?? "");
1926
+ this.#database.close();
1558
1927
  } catch {}
1559
- const appUrl = options.store.apiSnapshot()?.appUrl;
1560
- if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {
1561
- send(response, 403, "Only the app shown in the dashboard can be reached.");
1562
- return;
1563
- }
1564
- const body = await readBytes(request, MAX_PROXY_BYTES);
1565
- if (!body) {
1566
- tooLarge(response);
1567
- return;
1568
- }
1569
- const cookie = url.searchParams.get("cookie");
1570
- await forward(request, response, target.href, (headers) => {
1571
- if (cookie) headers.set("cookie", cookie);
1572
- }, "Could not reach the app.", body);
1573
1928
  }
1574
- function eventStream(request, response) {
1575
- response.writeHead(200, {
1576
- "content-type": "text/event-stream",
1577
- "cache-control": "no-cache",
1578
- connection: "keep-alive",
1579
- "x-accel-buffering": "no"
1929
+ };
1930
+ // src/dashboard-mcp-logs.ts
1931
+ const DEFAULT_LOG_LIMIT = 50;
1932
+ const MAX_LOG_LIMIT = 200;
1933
+ const MAX_MESSAGE_CHARS = 500;
1934
+ function hit(line) {
1935
+ return {
1936
+ time: iso(line.timeMs),
1937
+ level: line.level,
1938
+ message: cut(line.message, MAX_MESSAGE_CHARS),
1939
+ traceId: line.traceId,
1940
+ endpoint: line.endpoint,
1941
+ span: line.span
1942
+ };
1943
+ }
1944
+ function searchLogs(sources, args) {
1945
+ const { from, to } = window(args, DAY);
1946
+ const level = text$1(args, "level");
1947
+ if (level && !LOG_LEVELS.includes(level)) throw new Error(`level must be one of: ${LOG_LEVELS.join(", ")}.`);
1948
+ const search = {
1949
+ from,
1950
+ to,
1951
+ query: text$1(args, "query"),
1952
+ level,
1953
+ service: text$1(args, "service"),
1954
+ endpoint: text$1(args, "endpoint")
1955
+ };
1956
+ const limit = integer(args, "limit", 1, MAX_LOG_LIMIT, DEFAULT_LOG_LIMIT);
1957
+ const offset = integer(args, "offset", 0, Number.MAX_SAFE_INTEGER, 0);
1958
+ const { history, store } = sources;
1959
+ let found;
1960
+ let note;
1961
+ if (history) {
1962
+ const stored = history.searchLogLines(search, {
1963
+ limit: limit + 1,
1964
+ offset
1580
1965
  });
1581
- const write = (chunk) => {
1582
- if (response.writableEnded || response.destroyed) return;
1583
- response.write(chunk);
1584
- };
1585
- const emit = (name, data) => write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
1586
- emit("snapshot", snapshot());
1587
- const unsubscribe = options.store.subscribe((event) => emit(event.type, event));
1588
- const unwatch = extension?.onChange(() => emit("extension", snapshot().extension));
1589
- const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
1590
- request.on("close", () => {
1591
- clearInterval(keepalive);
1592
- unsubscribe();
1593
- unwatch?.();
1966
+ found = stored.lines;
1967
+ if (stored.requestsInWindow > 2e4) note = `The window holds ${stored.requestsInWindow} requests and only the newest ${MAX_SCANNED_REQUESTS} were searched. Narrow from and to to search older ones.`;
1968
+ if (stored.linesCapped) note = `${note ? `${note} ` : ""}The text was looked for in the newest ${MAX_SCANNED_LOG_LINES} log lines only. Narrow from and to, or add level, service or endpoint, to search older ones.`;
1969
+ } else found = searchLogLines(store.snapshot().traces, search).slice(offset, offset + limit + 1);
1970
+ const lines = found.slice(0, limit);
1971
+ return compactJson({
1972
+ window: {
1973
+ from: iso(from),
1974
+ to: iso(to)
1975
+ },
1976
+ source: history ? "history" : "memory",
1977
+ offset,
1978
+ ...found.length > limit ? { nextOffset: offset + limit } : {},
1979
+ ...note ? { note } : {},
1980
+ lines: lines.map(hit)
1981
+ });
1982
+ }
1983
+ const MAX_STACK_CHARS = 1500;
1984
+ const MAX_CRASH_MESSAGE_CHARS = 500;
1985
+ function listReloads(sources, args) {
1986
+ const since = time(args.from, "from", Date.now());
1987
+ const limit = integer(args, "limit", 1, 100, 20);
1988
+ const { reloads, failures } = sources.store.snapshot();
1989
+ const recent = (items) => items.filter((item) => since === void 0 || item.at >= since);
1990
+ return compactJson({
1991
+ mode: sources.mode,
1992
+ reloads: recent(reloads).slice(0, limit).map((reload) => ({
1993
+ time: iso(reload.at),
1994
+ kind: reload.kind,
1995
+ generation: reload.generation,
1996
+ detail: reload.detail
1997
+ })),
1998
+ crashes: recent(failures.filter((failure) => failure.phase !== "request")).slice(0, limit).map((crash) => ({
1999
+ time: iso(crash.at),
2000
+ kind: crash.phase,
2001
+ code: crash.code,
2002
+ message: cut(crash.message, MAX_CRASH_MESSAGE_CHARS),
2003
+ stack: cut(crash.stack, MAX_STACK_CHARS),
2004
+ generation: crash.generation
2005
+ }))
2006
+ });
2007
+ }
2008
+ /** What the Logs view and the Reloads view list. */
2009
+ function logTools(sources) {
2010
+ return [{
2011
+ definition: {
2012
+ name: "search_logs",
2013
+ description: `Log lines written with ctx.logger or console during requests, newest first: time, level, message, trace id, endpoint and the span that wrote it. Search by text and level, then open a trace id with get_trace for the whole request. The window is on when the request started (default: the last 24 hours). Text matching ignores case, for any letters. With history it searches the newest ${MAX_SCANNED_REQUESTS} requests of the window, and for text the newest ${MAX_SCANNED_LOG_LINES} lines of them, and says when it left some out.`,
2014
+ inputSchema: {
2015
+ type: "object",
2016
+ properties: {
2017
+ query: {
2018
+ type: "string",
2019
+ description: "Text the message contains, in any case."
2020
+ },
2021
+ level: {
2022
+ type: "string",
2023
+ enum: [...LOG_LEVELS],
2024
+ description: "Only lines of this level."
2025
+ },
2026
+ service: {
2027
+ type: "string",
2028
+ description: "Only requests handled by this service."
2029
+ },
2030
+ endpoint: {
2031
+ type: "string",
2032
+ description: "Only this endpoint, as list_requests shows it: \"GET /api/pages/:id\"."
2033
+ },
2034
+ from: {
2035
+ type: "string",
2036
+ description: `Window start. ${TIME_HELP} Default: a day before \`to\`.`
2037
+ },
2038
+ to: {
2039
+ type: "string",
2040
+ description: `Window end. ${TIME_HELP} Default: now.`
2041
+ },
2042
+ limit: {
2043
+ type: "integer",
2044
+ minimum: 1,
2045
+ maximum: MAX_LOG_LIMIT,
2046
+ description: `Default ${DEFAULT_LOG_LIMIT}.`
2047
+ },
2048
+ offset: {
2049
+ type: "integer",
2050
+ minimum: 0,
2051
+ description: "Lines to skip, to page through."
2052
+ }
2053
+ },
2054
+ additionalProperties: false
2055
+ },
2056
+ annotations: READ_ONLY
2057
+ },
2058
+ run: (args) => searchLogs(sources, args)
2059
+ }, {
2060
+ definition: {
2061
+ name: "list_reloads",
2062
+ description: "What the Reloads view shows, newest first: each time the app started, restarted or exited (kind \"started\", \"restarting\", \"exited\" or \"contract-ready\"), why, and which generation of the process it was, and the crashes of the process itself with their error and stack: a failed startup, an uncaught exception, an unhandled rejection. Check it when the app seems to restart or does not come up. Under `brick start` the dashboard sees only the process it runs in, so it lists the one start of that process and no crashes.",
2063
+ inputSchema: {
2064
+ type: "object",
2065
+ properties: {
2066
+ from: {
2067
+ type: "string",
2068
+ description: `Only events after this. ${TIME_HELP}`
2069
+ },
2070
+ limit: {
2071
+ type: "integer",
2072
+ minimum: 1,
2073
+ maximum: 100,
2074
+ description: `Of each list. Default 20.`
2075
+ }
2076
+ },
2077
+ additionalProperties: false
2078
+ },
2079
+ annotations: READ_ONLY
2080
+ },
2081
+ run: (args) => listReloads(sources, args)
2082
+ }];
2083
+ }
2084
+ const LOG_TOOL_NAMES = ["search_logs", "list_reloads"];
2085
+ // src/dashboard-mcp-workflows.ts
2086
+ /** The inspector's RPC methods these tools may call. All of them read. */
2087
+ const READ_RPC = [
2088
+ "fetchRuns",
2089
+ "fetchRun",
2090
+ "fetchEvents"
2091
+ ];
2092
+ const RPC_PATH = `${ROUTES.workflows.path}/api/rpc`;
2093
+ const INSPECTOR_TIMEOUT_MS = 1e4;
2094
+ const RUN_STATUSES = [
2095
+ "pending",
2096
+ "running",
2097
+ "completed",
2098
+ "failed",
2099
+ "cancelled"
2100
+ ];
2101
+ const RUNS_PER_PAGE = 100;
2102
+ /** A run list reads at most this many pages of runs to fill its limit. */
2103
+ const MAX_RUN_PAGES = 10;
2104
+ const EVENTS_PER_PAGE = 1e3;
2105
+ const MAX_EVENT_PAGES = 5;
2106
+ const LAST_SCHEDULE_RUNS = 5;
2107
+ const MAX_ERROR_CHARS = 500;
2108
+ const MAX_ID_CHARS = 200;
2109
+ /** A `get_run` answer is cut to about this many characters of JSON. */
2110
+ const MAX_RUN_CHARS = 5e4;
2111
+ /** From mildest to harshest: the first that fits the cap is the answer. */
2112
+ const RUN_LEVELS_MILDEST_FIRST = [
2113
+ {
2114
+ value: 2e3,
2115
+ steps: 200,
2116
+ hooks: 200
2117
+ },
2118
+ {
2119
+ value: 500,
2120
+ steps: 100,
2121
+ hooks: 100
2122
+ },
2123
+ {
2124
+ value: 100,
2125
+ steps: 50,
2126
+ hooks: 50
2127
+ },
2128
+ {
2129
+ value: 0,
2130
+ steps: 20,
2131
+ hooks: 20
2132
+ }
2133
+ ];
2134
+ async function askInspector(target, path, init = {}) {
2135
+ return fetch(`http://127.0.0.1:${target.port}${path}`, {
2136
+ ...init,
2137
+ headers: {
2138
+ ...init.headers,
2139
+ [INSPECTOR_TOKEN_HEADER]: target.token,
2140
+ [INSPECTOR_READ_ONLY_HEADER]: "1"
2141
+ },
2142
+ signal: AbortSignal.timeout(INSPECTOR_TIMEOUT_MS)
2143
+ });
2144
+ }
2145
+ /**
2146
+ * A hook's token resumes it from outside the dashboard, and only a signed-in
2147
+ * user may have it. The inspector sends none to a read-only caller; this takes
2148
+ * out any that is left, wherever it sits.
2149
+ */
2150
+ function withoutHookTokens(value) {
2151
+ if (Array.isArray(value)) return value.map(withoutHookTokens);
2152
+ if (value === null || typeof value !== "object") return value;
2153
+ const row = value;
2154
+ const isHook = "hookId" in row || String(row.eventType ?? "").startsWith("hook_");
2155
+ const kept = {};
2156
+ for (const [key, entry] of Object.entries(row)) {
2157
+ if (isHook && key === "token") continue;
2158
+ kept[key] = isHook && key === "eventData" && entry && typeof entry === "object" ? withoutHookTokens(Object.fromEntries(Object.entries(entry).filter(([name]) => name !== "token"))) : withoutHookTokens(entry);
2159
+ }
2160
+ return kept;
2161
+ }
2162
+ /** One read of the inspector's RPC: its `data`, or the error it answered. */
2163
+ async function inspectorRpc(target, method, params) {
2164
+ if (!READ_RPC.includes(method)) throw new Error(`The dashboard's MCP does not call ${method}.`);
2165
+ const response = await askInspector(target, RPC_PATH, {
2166
+ method: "POST",
2167
+ headers: {
2168
+ "content-type": "application/json",
2169
+ accept: "application/json"
2170
+ },
2171
+ body: JSON.stringify({
2172
+ method,
2173
+ params
2174
+ })
2175
+ });
2176
+ const answer = await response.json().catch(() => void 0);
2177
+ if (!response.ok || !answer?.success) throw new Error(answer?.error?.message ?? `The workflow inspector answered ${response.status}.`);
2178
+ return withoutHookTokens(answer.data);
2179
+ }
2180
+ /** The last part of a workflow's machine name, `workflow//./src/orders//ship`: `ship`. */
2181
+ const shortName = (workflowName) => workflowName.split("//").pop() || workflowName;
2182
+ const dateOf = (value) => {
2183
+ const parsed = typeof value === "string" ? Date.parse(value) : NaN;
2184
+ return Number.isNaN(parsed) ? void 0 : parsed;
2185
+ };
2186
+ const durationMs = (from, to) => {
2187
+ const start = dateOf(from);
2188
+ const end = dateOf(to);
2189
+ return start === void 0 || end === void 0 ? void 0 : end - start;
2190
+ };
2191
+ function runRow(run) {
2192
+ return {
2193
+ runId: run.runId,
2194
+ workflow: shortName(String(run.workflowName)),
2195
+ status: run.status,
2196
+ createdAt: run.createdAt,
2197
+ startedAt: run.startedAt,
2198
+ completedAt: run.completedAt,
2199
+ durationMs: durationMs(run.startedAt ?? run.createdAt, run.completedAt),
2200
+ error: run.error?.message ? cut(String(run.error.message), 300) : void 0
2201
+ };
2202
+ }
2203
+ async function listRuns(target, args) {
2204
+ const status = text$1(args, "status");
2205
+ if (status && !RUN_STATUSES.includes(status)) throw new Error(`status must be one of: ${RUN_STATUSES.join(", ")}.`);
2206
+ const workflow = text$1(args, "workflow");
2207
+ const now = Date.now();
2208
+ const from = time(args.from, "from", now);
2209
+ const to = time(args.to, "to", now) ?? now;
2210
+ if (from !== void 0 && from > to) throw new Error("from must not be after to.");
2211
+ const limit = integer(args, "limit", 1, 100, 20);
2212
+ const found = [];
2213
+ let cursor;
2214
+ let more = false;
2215
+ let scanned = 0;
2216
+ for (let page = 0; page < MAX_RUN_PAGES && found.length <= limit; page++) {
2217
+ const answer = await inspectorRpc(target, "fetchRuns", {
2218
+ limit: RUNS_PER_PAGE,
2219
+ sortOrder: "desc",
2220
+ cursor,
2221
+ ...status ? { status } : {}
1594
2222
  });
2223
+ let passedWindow = false;
2224
+ scanned += answer.data.length;
2225
+ for (const run of answer.data) {
2226
+ const created = dateOf(run.createdAt) ?? 0;
2227
+ if (from !== void 0 && created < from) {
2228
+ passedWindow = true;
2229
+ break;
2230
+ }
2231
+ if (created > to) continue;
2232
+ if (workflow && run.workflowName !== workflow && shortName(String(run.workflowName)) !== workflow) continue;
2233
+ found.push(run);
2234
+ }
2235
+ more = Boolean(answer.hasMore) && !passedWindow;
2236
+ cursor = answer.cursor ?? void 0;
2237
+ if (!more || !cursor) break;
1595
2238
  }
1596
- return (extension ? Promise.all([extension.load(), options.plugins && extension.setPlugins(options.plugins)]) : Promise.resolve()).then(() => listen());
1597
- function listen() {
1598
- return new Promise((resolve, reject) => {
1599
- server.once("error", (error) => {
1600
- extension?.close();
1601
- reject(new Error(`Brick: dashboard port ${options.port} is unavailable.${options.portHint ? ` ${options.portHint}` : ""}`, { cause: error }));
1602
- });
1603
- server.listen(options.port, host, () => {
1604
- const address = server.address();
1605
- const port = typeof address === "object" && address !== null ? address.port : options.port;
1606
- allowedHosts = /* @__PURE__ */ new Set([
1607
- `127.0.0.1:${port}`,
1608
- `localhost:${port}`,
1609
- `[::1]:${port}`
1610
- ]);
1611
- if (!production) extension?.watch();
1612
- resolve({
1613
- port,
1614
- setPluginExtensions: (plugins) => extension?.setPlugins(plugins) ?? Promise.resolve(),
1615
- stop() {
1616
- extension?.close();
1617
- server.close();
1618
- server.closeAllConnections();
1619
- }
2239
+ const cutShort = more && found.length <= limit;
2240
+ return compactJson({
2241
+ runs: found.slice(0, limit).map(runRow),
2242
+ ...found.length > limit ? { hasMore: true } : {},
2243
+ ...cutShort ? {
2244
+ truncated: true,
2245
+ note: `Only the newest ${scanned} runs were looked through, and older ones may match. Narrow it with from, status or workflow.`
2246
+ } : {}
2247
+ });
2248
+ }
2249
+ /** A value as it is, or a preview of its JSON when that is longer than `limit`. */
2250
+ function bounded(value, limit) {
2251
+ if (value === void 0) return void 0;
2252
+ const json = JSON.stringify(value) ?? "";
2253
+ if (json.length <= limit) return value;
2254
+ return limit === 0 ? {
2255
+ left: "out",
2256
+ chars: json.length
2257
+ } : {
2258
+ preview: cut(json, limit),
2259
+ chars: json.length
2260
+ };
2261
+ }
2262
+ /** A run's steps, from the events that record them: a step's events share a correlation id. */
2263
+ function stepsOf(events) {
2264
+ const steps = /* @__PURE__ */ new Map();
2265
+ for (const event of events) {
2266
+ if (!String(event.eventType).startsWith("step_") || !event.correlationId) continue;
2267
+ const step = steps.get(event.correlationId) ?? {
2268
+ stepId: event.correlationId,
2269
+ status: "pending",
2270
+ attempts: 0,
2271
+ retries: []
2272
+ };
2273
+ steps.set(event.correlationId, step);
2274
+ const data = event.eventData ?? {};
2275
+ step.name ??= data.stepName;
2276
+ step.createdAt ??= event.createdAt;
2277
+ switch (event.eventType) {
2278
+ case "step_started":
2279
+ step.status = "running";
2280
+ step.attempts += 1;
2281
+ step.startedAt ??= event.createdAt;
2282
+ step.completedAt = void 0;
2283
+ if (data.input !== void 0) step.input ??= data.input;
2284
+ break;
2285
+ case "step_created":
2286
+ if (data.input !== void 0) step.input ??= data.input;
2287
+ break;
2288
+ case "step_retrying":
2289
+ step.status = "pending";
2290
+ step.retries.push({
2291
+ attempt: data.attempt,
2292
+ error: data.error,
2293
+ retryAfter: data.retryAfter
1620
2294
  });
1621
- });
1622
- });
2295
+ break;
2296
+ case "step_completed":
2297
+ step.status = "completed";
2298
+ step.completedAt = event.createdAt;
2299
+ step.output = data.result;
2300
+ break;
2301
+ case "step_failed":
2302
+ step.status = "failed";
2303
+ step.completedAt = event.createdAt;
2304
+ step.error = data.error;
2305
+ }
1623
2306
  }
2307
+ return [...steps.values()];
1624
2308
  }
1625
- /** The whole request body, or undefined when it is larger than `limit`. */
1626
- function readBytes(request, limit) {
1627
- return new Promise((resolve) => {
1628
- const chunks = [];
1629
- let size = 0;
1630
- request.on("data", (chunk) => {
1631
- size += chunk.length;
1632
- if (size > limit) {
1633
- request.removeAllListeners("data");
1634
- request.resume();
1635
- resolve(void 0);
1636
- return;
1637
- }
1638
- chunks.push(chunk);
2309
+ function hooksOf(events) {
2310
+ const hooks = /* @__PURE__ */ new Map();
2311
+ for (const event of events) {
2312
+ if (!String(event.eventType).startsWith("hook_") || !event.correlationId) continue;
2313
+ const hook = hooks.get(event.correlationId) ?? {
2314
+ hookId: event.correlationId,
2315
+ received: 0,
2316
+ disposed: false
2317
+ };
2318
+ hooks.set(event.correlationId, hook);
2319
+ if (event.eventType === "hook_created") hook.createdAt = event.createdAt;
2320
+ if (event.eventType === "hook_received") hook.received += 1;
2321
+ if (event.eventType === "hook_disposed") hook.disposed = true;
2322
+ }
2323
+ return [...hooks.values()];
2324
+ }
2325
+ function runAnswer(run, steps, hooks, eventsRead, moreEvents, level) {
2326
+ const shown = steps.slice(0, level.steps);
2327
+ const shownHooks = hooks.slice(0, level.hooks);
2328
+ return {
2329
+ runId: run.runId,
2330
+ workflow: shortName(String(run.workflowName)),
2331
+ workflowName: run.workflowName,
2332
+ status: run.status,
2333
+ createdAt: run.createdAt,
2334
+ startedAt: run.startedAt,
2335
+ completedAt: run.completedAt,
2336
+ durationMs: durationMs(run.startedAt ?? run.createdAt, run.completedAt),
2337
+ input: bounded(run.input, level.value),
2338
+ output: bounded(run.output, level.value),
2339
+ error: run.error && {
2340
+ message: cut(String(run.error.message ?? ""), MAX_ERROR_CHARS),
2341
+ stack: cut(run.error.stack, Math.max(level.value, 0))
2342
+ },
2343
+ steps: shown.map((step) => ({
2344
+ stepId: step.stepId,
2345
+ name: step.name,
2346
+ status: step.status,
2347
+ attempts: step.attempts,
2348
+ createdAt: step.createdAt,
2349
+ startedAt: step.startedAt,
2350
+ completedAt: step.completedAt,
2351
+ durationMs: durationMs(step.startedAt, step.completedAt),
2352
+ input: bounded(step.input, level.value),
2353
+ output: bounded(step.output, level.value),
2354
+ error: bounded(step.error, level.value),
2355
+ retries: bounded(step.retries.length ? step.retries : void 0, level.value)
2356
+ })),
2357
+ hooks: shownHooks,
2358
+ note: shown.length < steps.length || shownHooks.length < hooks.length || moreEvents || level !== RUN_LEVELS_MILDEST_FIRST[0] ? `Cut to fit about ${MAX_RUN_CHARS / 1e3} KB.${shown.length < steps.length ? ` ${steps.length - shown.length} steps are left out.` : ""}${shownHooks.length < hooks.length ? ` ${hooks.length - shownHooks.length} hooks are left out.` : ""}${level !== RUN_LEVELS_MILDEST_FIRST[0] ? " Long inputs, outputs and errors are shortened or left out." : ""}${moreEvents ? ` Only the first ${eventsRead} events were read, so later steps may be missing.` : ""}` : void 0
2359
+ };
2360
+ }
2361
+ async function getRun(target, args) {
2362
+ const runId = text$1(args, "run_id");
2363
+ if (!runId) throw new Error("run_id is required.");
2364
+ const run = await inspectorRpc(target, "fetchRun", { runId });
2365
+ const events = [];
2366
+ let cursor;
2367
+ let moreEvents = false;
2368
+ for (let page = 0; page < MAX_EVENT_PAGES; page++) {
2369
+ const answer = await inspectorRpc(target, "fetchEvents", {
2370
+ runId,
2371
+ withData: true,
2372
+ sortOrder: "asc",
2373
+ limit: EVENTS_PER_PAGE,
2374
+ cursor
1639
2375
  });
1640
- request.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
1641
- request.on("error", () => resolve(void 0));
2376
+ events.push(...answer.data);
2377
+ cursor = answer.cursor ?? void 0;
2378
+ moreEvents = Boolean(answer.hasMore);
2379
+ if (!moreEvents || !cursor) break;
2380
+ }
2381
+ const steps = stepsOf(events);
2382
+ const hooks = hooksOf(events);
2383
+ for (const level of RUN_LEVELS_MILDEST_FIRST) {
2384
+ const answer = compactJson(runAnswer(run, steps, hooks, events.length, moreEvents, level));
2385
+ if (answer.length <= 5e4) return answer;
2386
+ }
2387
+ return compactJson({
2388
+ runId: cut(String(run.runId), MAX_ID_CHARS),
2389
+ workflow: cut(shortName(String(run.workflowName)), MAX_ID_CHARS),
2390
+ status: run.status,
2391
+ createdAt: run.createdAt,
2392
+ completedAt: run.completedAt,
2393
+ steps: steps.length,
2394
+ hooks: hooks.length,
2395
+ note: `This run is too large to send even cut down, so its details are left out: ${steps.length} steps, ${hooks.length} hooks. Open it in the dashboard's Workflows view.`
1642
2396
  });
1643
2397
  }
1644
- function history(store, pathname, params, response) {
1645
- const queries = {
1646
- summary: (query) => store.summary(query),
1647
- traces: (query) => store.traces(query),
1648
- facets: (query) => store.facets(query),
1649
- volume: (query) => store.volume(query)
2398
+ async function listSchedules(target) {
2399
+ const response = await askInspector(target, ROUTES.schedules.path);
2400
+ if (!response.ok) throw new Error(`The schedules answered ${response.status}.`);
2401
+ const schedules = withoutHookTokens(await response.json());
2402
+ return compactJson({ schedules: schedules.map((schedule) => ({
2403
+ name: schedule.name,
2404
+ kind: schedule.kind,
2405
+ schedule: describeSchedule(schedule),
2406
+ enabled: schedule.enabled,
2407
+ running: schedule.running,
2408
+ nextRunAt: schedule.nextRunAt,
2409
+ attempts: schedule.attempts,
2410
+ lastSuccessAt: schedule.lastSuccessAt,
2411
+ lastRuns: (schedule.runs ?? []).slice(0, LAST_SCHEDULE_RUNS).map((run) => ({
2412
+ slot: run.slot,
2413
+ trigger: run.trigger,
2414
+ attempt: run.attempt,
2415
+ startedAt: run.startedAt,
2416
+ finishedAt: run.finishedAt,
2417
+ outcome: run.outcome,
2418
+ error: cut(run.error, MAX_ERROR_CHARS)
2419
+ }))
2420
+ })) });
2421
+ }
2422
+ /** The Schedules and Workflows views, while the dashboard serves the inspector. */
2423
+ function workflowTools(sources) {
2424
+ const { store } = sources;
2425
+ const served = () => sources.inspector ? store.inspectorTarget() : void 0;
2426
+ const hasSchedules = () => Boolean(served() && store.architecture()?.schema.events?.schedules?.length);
2427
+ const hasWorkflows = () => Boolean(served() && store.servesWorkflows());
2428
+ const target = () => {
2429
+ const found = served();
2430
+ if (!found) throw new Error("The workflow inspector is not being served.");
2431
+ return found;
1650
2432
  };
1651
- try {
1652
- const endpoint = pathname.slice(ROUTES.history.path.length + 1);
1653
- if (endpoint === "") return json(response, store.info());
1654
- if (endpoint === "export") return send(response, 200, store.exportCsv(decodeHistoryQuery(params)), {
1655
- "content-type": "text/csv; charset=utf-8",
1656
- "content-disposition": "attachment; filename=\"brick-requests.csv\"",
1657
- "cache-control": "no-store"
1658
- });
1659
- if (Object.hasOwn(queries, endpoint)) return json(response, queries[endpoint](decodeHistoryQuery(params)));
1660
- if (endpoint.startsWith("traces/")) {
1661
- const trace = store.trace(decodeURIComponent(endpoint.slice(7)));
1662
- if (trace) return json(response, trace);
2433
+ return [
2434
+ {
2435
+ definition: {
2436
+ name: "list_schedules",
2437
+ description: "The app's schedules, as the Schedules view shows them: each one's name, kind (handler or workflow), cron or interval, whether it is enabled and running, when it is next due, when it last succeeded, and its last five runs with their outcome (succeeded, failed or skipped) and error. Look here when something that should run on a timer did not.",
2438
+ inputSchema: {
2439
+ type: "object",
2440
+ properties: {},
2441
+ additionalProperties: false
2442
+ },
2443
+ annotations: READ_ONLY
2444
+ },
2445
+ available: hasSchedules,
2446
+ run: () => listSchedules(target())
2447
+ },
2448
+ {
2449
+ definition: {
2450
+ name: "list_runs",
2451
+ description: `Workflow runs, newest first, as the Workflows view lists them: run id, workflow, status, when it was created and finished, how long it took, and its error. Filter by status (pending, running, completed, failed or cancelled), workflow name and time window. Start with status "failed", then open one with get_run. It reads up to 1000 runs to fill the limit.`,
2452
+ inputSchema: {
2453
+ type: "object",
2454
+ properties: {
2455
+ status: {
2456
+ type: "string",
2457
+ enum: [...RUN_STATUSES],
2458
+ description: "Only runs in this state."
2459
+ },
2460
+ workflow: {
2461
+ type: "string",
2462
+ description: "Only runs of this workflow, by the name list_runs shows."
2463
+ },
2464
+ from: {
2465
+ type: "string",
2466
+ description: `Only runs created after this. ${TIME_HELP}`
2467
+ },
2468
+ to: {
2469
+ type: "string",
2470
+ description: `Only runs created before this. ${TIME_HELP} Default: now.`
2471
+ },
2472
+ limit: {
2473
+ type: "integer",
2474
+ minimum: 1,
2475
+ maximum: 100,
2476
+ description: `Default 20.`
2477
+ }
2478
+ },
2479
+ additionalProperties: false
2480
+ },
2481
+ annotations: READ_ONLY
2482
+ },
2483
+ available: hasWorkflows,
2484
+ run: (args) => listRuns(target(), args)
2485
+ },
2486
+ {
2487
+ definition: {
2488
+ name: "get_run",
2489
+ description: `One workflow run in full, by run id: its input, output and error, and each step with its status, attempts, timing, input, output, error and retries, and its hooks (by id, never their tokens). Long values are shortened and the answer is cut to about ${MAX_RUN_CHARS / 1e3} KB, and says what was left out.`,
2490
+ inputSchema: {
2491
+ type: "object",
2492
+ properties: { run_id: {
2493
+ type: "string",
2494
+ description: "From list_runs."
2495
+ } },
2496
+ required: ["run_id"],
2497
+ additionalProperties: false
2498
+ },
2499
+ annotations: READ_ONLY
2500
+ },
2501
+ available: hasWorkflows,
2502
+ run: (args) => getRun(target(), args)
1663
2503
  }
1664
- send(response, 404, "Not found");
1665
- } catch (error) {
1666
- if (error instanceof URIError) return send(response, 400, error.message);
1667
- console.error("[Brick-TS] A dashboard history query failed:", error);
1668
- send(response, 500, "History query failed");
1669
- }
2504
+ ];
1670
2505
  }
1671
- const ASSET_TYPES = {
1672
- ".js": "text/javascript; charset=utf-8",
1673
- ".css": "text/css; charset=utf-8",
1674
- ".woff2": "font/woff2"
1675
- };
1676
- const assetType = (name) => ASSET_TYPES[extname(name)] ?? "application/octet-stream";
1677
- function serveAsset(response, name) {
1678
- if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
1679
- send(response, 404, "Not found");
1680
- return;
2506
+ const WORKFLOW_TOOL_NAMES = [
2507
+ "list_schedules",
2508
+ "list_runs",
2509
+ "get_run"
2510
+ ];
2511
+ // src/dashboard-mcp.ts
2512
+ const SLOWEST_ENDPOINTS = 5;
2513
+ const MAX_TRACE_CHARS = 5e4;
2514
+ const TRACE_LEVELS_MILDEST_FIRST = [
2515
+ {
2516
+ text: 2e3,
2517
+ attributes: 40,
2518
+ events: 50,
2519
+ spans: 300
2520
+ },
2521
+ {
2522
+ text: 500,
2523
+ attributes: 20,
2524
+ events: 20,
2525
+ spans: 150
2526
+ },
2527
+ {
2528
+ text: 200,
2529
+ attributes: 10,
2530
+ events: 5,
2531
+ spans: 60
2532
+ },
2533
+ {
2534
+ text: 100,
2535
+ attributes: 5,
2536
+ events: 2,
2537
+ spans: 30
1681
2538
  }
1682
- const directory = assetsDirectory();
1683
- if (!directory) {
1684
- send(response, 503, "Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build");
1685
- return;
2539
+ ];
2540
+ function memorySource(store) {
2541
+ const rows = (query) => store.snapshot().traces.map(toRow).filter((row) => row.startMs >= query.from && row.startMs <= query.to);
2542
+ return {
2543
+ name: "memory",
2544
+ summary: (query) => summarizeRows(applyFilters(rows(query), query)),
2545
+ slowestEndpoints: (query, limit) => slowestEndpoints(rows(query), limit),
2546
+ traces(query) {
2547
+ const found = applyFilters(rows(query), query);
2548
+ const offset = query.offset ?? 0;
2549
+ return {
2550
+ total: found.length,
2551
+ traces: found.slice(offset, offset + (query.limit ?? found.length))
2552
+ };
2553
+ },
2554
+ facets: (query) => computeFacets(rows(query), query),
2555
+ trace: (traceId) => store.snapshot().traces.find((trace) => trace.traceId === traceId)
2556
+ };
2557
+ }
2558
+ function sourceOf(store, history) {
2559
+ if (!history) return memorySource(store);
2560
+ const unfinished = memorySource(store).trace;
2561
+ return {
2562
+ name: "history",
2563
+ summary: (query) => history.summary(query),
2564
+ slowestEndpoints: (query, limit) => history.slowestEndpoints(query, limit),
2565
+ traces: (query) => history.traces(query),
2566
+ facets: (query) => history.facets(query),
2567
+ trace: (traceId) => history.trace(traceId) ?? unfinished(traceId)
2568
+ };
2569
+ }
2570
+ function row(trace) {
2571
+ return {
2572
+ traceId: trace.traceId,
2573
+ time: iso(trace.startMs),
2574
+ endpoint: trace.endpoint,
2575
+ path: trace.path,
2576
+ status: trace.httpStatus,
2577
+ outcome: outcomeOf(trace),
2578
+ state: trace.status,
2579
+ durationMs: round(trace.durationMs),
2580
+ service: trace.service,
2581
+ action: trace.action,
2582
+ message: cut(trace.message, 300)
2583
+ };
2584
+ }
2585
+ function traceTree(trace, limits) {
2586
+ const cuts = {
2587
+ text: 0,
2588
+ attributes: 0,
2589
+ events: 0,
2590
+ spans: 0
2591
+ };
2592
+ const shorten = (value) => {
2593
+ const short = cut(value, limits.text);
2594
+ if (short !== value) cuts.text += 1;
2595
+ return short;
2596
+ };
2597
+ const attributes = (source) => {
2598
+ const entries = Object.entries(source).filter(([, v]) => v !== void 0);
2599
+ cuts.attributes += Math.max(entries.length - limits.attributes, 0);
2600
+ return Object.fromEntries(entries.slice(0, limits.attributes).map(([key, value]) => [key, typeof value === "string" ? shorten(value) : Array.isArray(value) ? shorten(JSON.stringify(value)) : value]));
2601
+ };
2602
+ const spans = [...trace.spans].sort((a, b) => a.startMs - b.startMs);
2603
+ cuts.spans += Math.max(spans.length - limits.spans, 0);
2604
+ const nodes = /* @__PURE__ */ new Map();
2605
+ const roots = [];
2606
+ for (const span of spans.slice(0, limits.spans)) {
2607
+ const exception = findException(span.events);
2608
+ const shown = span.events.filter((event) => event.name !== SPAN.exceptionEvent);
2609
+ cuts.events += Math.max(shown.length - limits.events, 0);
2610
+ const node = {
2611
+ spanId: span.spanId,
2612
+ name: span.name,
2613
+ startMs: Math.round(span.startMs - trace.startMs),
2614
+ durationMs: span.endMs === void 0 ? void 0 : round(span.endMs - span.startMs),
2615
+ status: span.status,
2616
+ statusMessage: shorten(span.statusMessage),
2617
+ error: exception && {
2618
+ type: stringAttribute(exception, "exception.type"),
2619
+ message: shorten(stringAttribute(exception, ATTR.exceptionMessage)),
2620
+ stack: shorten(stringAttribute(exception, ATTR.exceptionStack))
2621
+ },
2622
+ attributes: attributes(span.attributes),
2623
+ events: shown.slice(0, limits.events).map((event) => event.name === SPAN.logEvent ? {
2624
+ atMs: Math.round(event.timeMs - trace.startMs),
2625
+ name: event.name,
2626
+ level: stringAttribute(event.attributes, ATTR.logLevel),
2627
+ message: shorten(stringAttribute(event.attributes, ATTR.logMessage))
2628
+ } : {
2629
+ atMs: Math.round(event.timeMs - trace.startMs),
2630
+ name: event.name,
2631
+ attributes: attributes(event.attributes)
2632
+ }),
2633
+ children: []
2634
+ };
2635
+ nodes.set(span.spanId, node);
2636
+ const parent = span.parentSpanId && nodes.get(span.parentSpanId);
2637
+ (parent ? parent.children : roots).push(node);
1686
2638
  }
1687
- readFile(join(directory, name)).then((body) => send(response, 200, body, {
1688
- "content-type": assetType(name),
1689
- "cache-control": "no-store"
1690
- }), () => send(response, 404, "Not found"));
2639
+ return {
2640
+ roots,
2641
+ cuts
2642
+ };
1691
2643
  }
1692
- function tooLarge(response) {
1693
- send(response, 413, "Payload too large", {
1694
- "content-type": "text/plain; charset=utf-8",
1695
- connection: "close"
2644
+ function withoutSpans(answer, trace) {
2645
+ const { spans: _spans, truncated: _truncated, ...request } = JSON.parse(answer);
2646
+ return compactJson({
2647
+ ...request,
2648
+ message: cut(trace.message, 500),
2649
+ spans: [],
2650
+ truncated: { note: `This trace is too large to send even cut down, so its spans are left out. It is about ${Math.round(answer.length / 1e3)} KB; open it in the dashboard instead.` }
1696
2651
  });
1697
2652
  }
1698
- function send(response, status, body, headers = { "content-type": "text/plain; charset=utf-8" }) {
1699
- response.writeHead(status, headers);
1700
- response.end(body);
2653
+ function traceAnswer(trace) {
2654
+ let answer = "";
2655
+ for (const limits of TRACE_LEVELS_MILDEST_FIRST) {
2656
+ const { roots, cuts } = traceTree(trace, limits);
2657
+ const row = toRow(trace);
2658
+ const cutAny = () => Object.values(cuts).some((count) => count > 0);
2659
+ const body = {
2660
+ traceId: trace.traceId,
2661
+ endpoint: row.endpoint,
2662
+ path: trace.path,
2663
+ status: trace.httpStatus,
2664
+ outcome: outcomeOf(trace),
2665
+ state: trace.status,
2666
+ time: iso(trace.startMs),
2667
+ durationMs: round(trace.durationMs),
2668
+ service: trace.service,
2669
+ action: trace.action,
2670
+ message: cut(trace.message, limits.text),
2671
+ spans: roots,
2672
+ truncated: void 0
2673
+ };
2674
+ if (trace.truncated || cutAny()) body.truncated = {
2675
+ note: `Cut to fit about ${MAX_TRACE_CHARS / 1e3} KB. Left out: ${cuts.spans} spans, ${cuts.events} events, ${cuts.attributes} attributes; shortened ${cuts.text} long strings.${trace.truncated ? " The app itself also stopped recording spans of this request, which was very large." : ""}`,
2676
+ ...cuts
2677
+ };
2678
+ answer = compactJson(body);
2679
+ if (answer.length <= 5e4) return answer;
2680
+ }
2681
+ return withoutSpans(answer, trace);
1701
2682
  }
1702
- function json(response, body) {
1703
- send(response, 200, JSON.stringify(body), {
1704
- "content-type": "application/json",
1705
- "cache-control": "no-store"
2683
+ const TOOLS = [
2684
+ {
2685
+ name: "summary",
2686
+ description: "How the app is doing over a time window: request count, how many failed (client errors 4xx, server errors 5xx or thrown), the share that failed on the server, median and p95 duration, and the five endpoints with the highest average duration (with their request counts, server errors and slowest request). Start here to see whether something is wrong. Default window: the last hour.",
2687
+ inputSchema: {
2688
+ type: "object",
2689
+ properties: {
2690
+ from: {
2691
+ type: "string",
2692
+ description: `Window start. ${TIME_HELP} Default: an hour before \`to\`.`
2693
+ },
2694
+ to: {
2695
+ type: "string",
2696
+ description: `Window end. ${TIME_HELP} Default: now.`
2697
+ }
2698
+ },
2699
+ additionalProperties: false
2700
+ },
2701
+ annotations: READ_ONLY
2702
+ },
2703
+ {
2704
+ name: "list_requests",
2705
+ description: "Requests the app served, newest first (or slowest first), one row each: trace id, time, endpoint, path, HTTP status, outcome (ok, client error, server error), duration, service and action, and the failure message. Rows only; call get_trace with a trace id for the spans and log lines. Default window: the last 24 hours.",
2706
+ inputSchema: {
2707
+ type: "object",
2708
+ properties: {
2709
+ outcome: {
2710
+ type: "string",
2711
+ enum: [...OUTCOMES],
2712
+ description: "ok (below 400), client (4xx), or server (5xx or thrown)."
2713
+ },
2714
+ endpoint: {
2715
+ type: "string",
2716
+ description: "Exactly as the rows show it, such as \"GET /api/pages/:id\"."
2717
+ },
2718
+ method: {
2719
+ type: "string",
2720
+ description: "An HTTP method, such as \"POST\"."
2721
+ },
2722
+ service: {
2723
+ type: "string",
2724
+ description: "A service name."
2725
+ },
2726
+ query: {
2727
+ type: "string",
2728
+ description: "Text to look for in the endpoint, path, span name, action or failure message."
2729
+ },
2730
+ min_ms: {
2731
+ type: "integer",
2732
+ minimum: 1,
2733
+ description: "Only requests at least this slow."
2734
+ },
2735
+ sort: {
2736
+ type: "string",
2737
+ enum: ["recent", "slowest"],
2738
+ description: "Default: recent."
2739
+ },
2740
+ from: {
2741
+ type: "string",
2742
+ description: `Window start. ${TIME_HELP} Default: a day before \`to\`.`
2743
+ },
2744
+ to: {
2745
+ type: "string",
2746
+ description: `Window end. ${TIME_HELP} Default: now.`
2747
+ },
2748
+ limit: {
2749
+ type: "integer",
2750
+ minimum: 1,
2751
+ maximum: 100,
2752
+ description: `Rows to return. Default 20.`
2753
+ },
2754
+ offset: {
2755
+ type: "integer",
2756
+ minimum: 0,
2757
+ description: "Rows to skip, to page through."
2758
+ }
2759
+ },
2760
+ additionalProperties: false
2761
+ },
2762
+ annotations: READ_ONLY
2763
+ },
2764
+ {
2765
+ name: "get_trace",
2766
+ description: "One request in full, by trace id: the tree of spans with each one's name, timing (milliseconds from the start of the request), status, attributes (such as SQL text), events and any error with its stack. Log lines are events named \"log\" with a level and message. The answer is cut to about 50 KB, and says what was left out.",
2767
+ inputSchema: {
2768
+ type: "object",
2769
+ properties: { trace_id: {
2770
+ type: "string",
2771
+ description: "From list_requests or list_errors."
2772
+ } },
2773
+ required: ["trace_id"],
2774
+ additionalProperties: false
2775
+ },
2776
+ annotations: READ_ONLY
2777
+ },
2778
+ {
2779
+ name: "list_errors",
2780
+ description: "Recent failures, newest first: failed requests (server errors, 5xx or thrown) and crashes of the app process, with the message, the route, the service and action, a stack when there is one, and the trace id to open with get_trace. Covers what the dashboard has seen since it started (the last 200). For older server errors use list_requests with outcome \"server\".",
2781
+ inputSchema: {
2782
+ type: "object",
2783
+ properties: {
2784
+ from: {
2785
+ type: "string",
2786
+ description: `Only failures after this. ${TIME_HELP}`
2787
+ },
2788
+ limit: {
2789
+ type: "integer",
2790
+ minimum: 1,
2791
+ maximum: 100,
2792
+ description: `Default 20.`
2793
+ }
2794
+ },
2795
+ additionalProperties: false
2796
+ },
2797
+ annotations: READ_ONLY
2798
+ },
2799
+ {
2800
+ name: "app_overview",
2801
+ description: "How the app is built, not what it is doing: its services with their actions (and the HTTP route of each), MCP tools, sockets, events and database tables; the event listeners and schedules, with the workflows among them; and the installed plugins.",
2802
+ inputSchema: {
2803
+ type: "object",
2804
+ properties: {},
2805
+ additionalProperties: false
2806
+ },
2807
+ annotations: READ_ONLY
2808
+ }
2809
+ ];
2810
+ /** The tools of the dashboard's other views, by name, whether or not their data exists now. */
2811
+ const VIEW_TOOL_NAMES = [
2812
+ ...LOG_TOOL_NAMES,
2813
+ ...WORKFLOW_TOOL_NAMES,
2814
+ ...DOCS_TOOL_NAMES
2815
+ ];
2816
+ /** Every tool the dashboard has of its own, listed or not. */
2817
+ const DASHBOARD_TOOL_NAMES = [...TOOLS.map((tool) => tool.name), ...VIEW_TOOL_NAMES];
2818
+ function createDashboardMcpRegistry(options) {
2819
+ const { store, history } = options;
2820
+ const viewTools = [
2821
+ ...logTools(options),
2822
+ ...workflowTools(options),
2823
+ ...docsTools(options)
2824
+ ];
2825
+ const calls = {
2826
+ summary(args) {
2827
+ const { from, to } = window(args, 60 * MINUTE);
2828
+ const source = sourceOf(store, history);
2829
+ const query = {
2830
+ from,
2831
+ to
2832
+ };
2833
+ const total = source.summary(query);
2834
+ const slowest = source.slowestEndpoints(query, SLOWEST_ENDPOINTS);
2835
+ return compactJson({
2836
+ window: {
2837
+ from: iso(from),
2838
+ to: iso(to)
2839
+ },
2840
+ source: source.name,
2841
+ requests: total.total,
2842
+ clientErrors: total.clientErrors,
2843
+ serverErrors: total.serverErrors,
2844
+ errorRate: total.total ? Math.round(total.serverErrors / total.total * 1e4) / 1e4 : 0,
2845
+ medianMs: round(total.medianMs),
2846
+ p95Ms: round(total.p95Ms),
2847
+ slowestEndpoints: slowest.map((endpoint) => ({
2848
+ ...endpoint,
2849
+ avgMs: round(endpoint.avgMs),
2850
+ maxMs: round(endpoint.maxMs)
2851
+ }))
2852
+ });
2853
+ },
2854
+ list_requests(args) {
2855
+ const { from, to } = window(args, DAY);
2856
+ const outcome = text$1(args, "outcome");
2857
+ if (outcome && !OUTCOMES.includes(outcome)) throw new Error(`outcome must be one of: ${OUTCOMES.join(", ")}.`);
2858
+ const sort = text$1(args, "sort");
2859
+ if (sort && sort !== "recent" && sort !== "slowest") throw new Error("sort must be recent or slowest.");
2860
+ const one = (name) => {
2861
+ const value = text$1(args, name);
2862
+ return value ? [value] : void 0;
2863
+ };
2864
+ const limit = integer(args, "limit", 1, 100, 20);
2865
+ const offset = integer(args, "offset", 0, Number.MAX_SAFE_INTEGER, 0);
2866
+ const source = sourceOf(store, history);
2867
+ const found = source.traces({
2868
+ from,
2869
+ to,
2870
+ endpoints: one("endpoint"),
2871
+ methods: one("method")?.map((method) => method.toUpperCase()),
2872
+ services: one("service"),
2873
+ outcomes: outcome ? [outcome] : void 0,
2874
+ minMs: integer(args, "min_ms", 1, Number.MAX_SAFE_INTEGER),
2875
+ query: text$1(args, "query"),
2876
+ sort: sort === "slowest" ? "slowest" : "recent",
2877
+ limit,
2878
+ offset
2879
+ });
2880
+ return compactJson({
2881
+ window: {
2882
+ from: iso(from),
2883
+ to: iso(to)
2884
+ },
2885
+ source: source.name,
2886
+ total: found.total,
2887
+ offset,
2888
+ ...offset + found.traces.length < found.total ? { nextOffset: offset + found.traces.length } : {},
2889
+ requests: found.traces.map(row)
2890
+ });
2891
+ },
2892
+ get_trace(args) {
2893
+ const id = text$1(args, "trace_id");
2894
+ if (!id) throw new Error("trace_id is required.");
2895
+ const trace = sourceOf(store, history).trace(id);
2896
+ if (!trace) throw new Error(`No request with trace id ${id}. The dashboard keeps ${history ? `${history.days} days of requests` : "only the last 200 requests, and history is off"}.`);
2897
+ return traceAnswer(trace);
2898
+ },
2899
+ list_errors(args) {
2900
+ const since = time(args.from, "from", Date.now());
2901
+ const limit = integer(args, "limit", 1, 100, 20);
2902
+ const failures = store.snapshot().failures.filter((failure) => (since === void 0 || failure.at >= since) && (failure.status ?? 500) >= 500);
2903
+ return compactJson({
2904
+ total: failures.length,
2905
+ errors: failures.slice(0, limit).map((failure) => ({
2906
+ time: iso(failure.at),
2907
+ code: failure.code,
2908
+ kind: failure.phase,
2909
+ message: cut(failure.message, 500),
2910
+ status: failure.status,
2911
+ route: failure.route,
2912
+ service: failure.service,
2913
+ action: failure.action,
2914
+ traceId: failure.traceId,
2915
+ stack: cut(failure.stack, 1500)
2916
+ }))
2917
+ });
2918
+ },
2919
+ app_overview() {
2920
+ const { architecture } = store.snapshot();
2921
+ if (!architecture) return compactJson({ note: "The app has not reported its architecture yet. It may still be starting." });
2922
+ const { schema } = architecture;
2923
+ const events = schema.events;
2924
+ const workflows = [...(events?.listeners ?? []).filter((item) => item.kind === "workflow"), ...(events?.schedules ?? []).filter((item) => item.kind === "workflow")].map((item) => item.name);
2925
+ return compactJson({
2926
+ mode: options.mode,
2927
+ historyDays: history?.days ?? 0,
2928
+ version: schema.version,
2929
+ services: schema.services.map((service) => ({
2930
+ name: service.name,
2931
+ database: service.databaseConfig,
2932
+ actions: service.actions.map((action) => ({
2933
+ name: action.name,
2934
+ route: action.method && action.path ? `${action.method} ${action.path}` : void 0,
2935
+ description: cut(action.description, 200),
2936
+ access: action.accessPolicy,
2937
+ emits: action.emits
2938
+ })),
2939
+ tools: service.tools?.map((tool) => tool.name),
2940
+ sockets: service.sockets?.map((socket) => socket.name),
2941
+ events: service.events?.map((event) => event.name),
2942
+ resources: service.resources?.map((resource) => resource.name)
2943
+ })),
2944
+ listeners: events?.listeners,
2945
+ schedules: events?.schedules,
2946
+ workflows,
2947
+ plugins: schema.plugins?.map((plugin) => plugin.name)
2948
+ });
2949
+ }
2950
+ };
2951
+ const listed = () => viewTools.filter((tool) => tool.available?.() ?? true);
2952
+ return {
2953
+ listTools: () => [...TOOLS, ...listed().map((tool) => tool.definition)],
2954
+ async callTool(name, args = {}) {
2955
+ const call = Object.hasOwn(calls, name) ? calls[name] : void 0;
2956
+ if (call) return call(args);
2957
+ const view = listed().find((tool) => tool.definition.name === name);
2958
+ if (!view) throw new UnknownToolError(name);
2959
+ return view.run(args);
2960
+ }
2961
+ };
2962
+ }
2963
+ const LIST_TIMEOUT_MS = 5e3;
2964
+ const CALL_TIMEOUT_MS = 3e4;
2965
+ const BUILT_IN = new Set(DASHBOARD_TOOL_NAMES);
2966
+ /** MCP defaults `readOnlyHint` to false, so a tool is a write tool unless it says otherwise. */
2967
+ const writes = (tool) => tool.annotations?.readOnlyHint !== true;
2968
+ /** Signed with the MCP scope, which `/app` never signs: neither signature works on the other's route. */
2969
+ async function askApp(appUrl, caller, method, params, timeoutMs) {
2970
+ const answer = await fetch(`${new URL(appUrl).origin}${DASHBOARD_MCP_ROUTE}`, {
2971
+ method: "POST",
2972
+ headers: {
2973
+ "content-type": "application/json",
2974
+ [DASHBOARD_IDENTITY_HEADER]: signDashboardMcp(caller)
2975
+ },
2976
+ body: JSON.stringify({
2977
+ jsonrpc: "2.0",
2978
+ id: 1,
2979
+ method,
2980
+ params
2981
+ }),
2982
+ signal: AbortSignal.timeout(timeoutMs)
1706
2983
  });
2984
+ if (!answer.ok) throw new Error(`HTTP ${answer.status}`);
2985
+ return await answer.json();
1707
2986
  }
1708
- const isBodyless = (request) => request.method === "GET" || request.method === "HEAD";
2987
+ function withAppTools(base, app, caller) {
2988
+ const own = (app?.tools ?? []).filter((tool) => !BUILT_IN.has(tool.name));
2989
+ return {
2990
+ listTools: () => [...base.listTools(), ...own.filter((tool) => !writes(tool) || caller.mayChange).map((tool) => writes(tool) ? {
2991
+ ...tool,
2992
+ annotations: {
2993
+ ...tool.annotations,
2994
+ destructiveHint: tool.annotations?.destructiveHint ?? true
2995
+ }
2996
+ } : tool)],
2997
+ async callTool(name, args) {
2998
+ if (BUILT_IN.has(name)) return base.callTool(name, args);
2999
+ if (app?.failed) throw new Error(`The app did not answer (${app.failed}), so its tools are unavailable. It may be restarting.`);
3000
+ if (!caller.appUrl) throw new UnknownToolError(name);
3001
+ const listed = own.find((item) => item.name === name);
3002
+ const answer = await askApp(caller.appUrl, {
3003
+ ...caller.identity,
3004
+ write: caller.mayChange
3005
+ }, "tools/call", {
3006
+ name,
3007
+ arguments: args ?? {}
3008
+ }, CALL_TIMEOUT_MS);
3009
+ const text = answer.result?.content?.map((part) => part.text).join("\n");
3010
+ if (answer.error?.code === -32602) throw new UnknownToolError(name);
3011
+ if (answer.error || answer.result?.isError) throw new Error(answer.error?.message ?? text);
3012
+ const structured = answer.result?.structuredContent;
3013
+ if (structured === void 0) return text ?? "";
3014
+ return (listed?.outputSchema)?.[WRAP_RESULT] ? structured.result : structured;
3015
+ }
3016
+ };
3017
+ }
3018
+ function createDashboardMcp(options) {
3019
+ const base = createDashboardMcpRegistry(options);
3020
+ return async (request, identity) => {
3021
+ const rpc = await request.clone().json().catch(() => void 0);
3022
+ const appUrl = options.appUrl();
3023
+ let app;
3024
+ if (appUrl && (rpc?.method === "tools/list" || rpc?.method === "tools/call" && typeof rpc.params?.name === "string" && !BUILT_IN.has(rpc.params.name))) try {
3025
+ app = { tools: (await askApp(appUrl, {
3026
+ ...identity,
3027
+ write: options.mayChange(identity)
3028
+ }, "tools/list", void 0, LIST_TIMEOUT_MS)).result?.tools ?? [] };
3029
+ } catch (error) {
3030
+ app = {
3031
+ tools: [],
3032
+ failed: error instanceof Error ? error.message : String(error)
3033
+ };
3034
+ }
3035
+ return createMcpHandler({
3036
+ registry: withAppTools(base, app, {
3037
+ identity,
3038
+ appUrl,
3039
+ mayChange: options.mayChange(identity)
3040
+ }),
3041
+ serverInfo: {
3042
+ name: "brick-dashboard",
3043
+ title: "Brick dashboard",
3044
+ version
3045
+ }
3046
+ })(request);
3047
+ };
3048
+ }
3049
+ // src/dashboard-access.ts
3050
+ /** How long the app's `authorize` may take before the request is refused. */
3051
+ const AUTHORIZE_TIMEOUT_MS = 5e3;
3052
+ function isLoopbackHost(host) {
3053
+ const name = host.toLowerCase();
3054
+ return name === "localhost" || name === "::1" || name === "[::1]" || /^127(\.\d{1,3}){3}$/.test(name);
3055
+ }
3056
+ const MAX_DECODE_ROUNDS = 4;
1709
3057
  /**
1710
- * Whether a request comes from the dashboard's own page, as far as the browser
1711
- * says: the same site, and the same origin as the address it was sent to.
1712
- * Behind a proxy that terminates TLS that address is https.
3058
+ * Whether a path, as the app will route it, is under `/_brick/`: Brick's own
3059
+ * routes, such as the one that answers the dashboard's MCP, which the `/app`
3060
+ * proxy must never reach. It decodes percent-encoding until nothing changes
3061
+ * (`%2F`, `%5F`, `%252F`), reads `\` as `/`, drops empty and `.` segments,
3062
+ * resolves `..`, and compares without regard to case. A path it cannot decode
3063
+ * is refused too. `/_brick/files`, local file storage's signed links, passes.
1713
3064
  */
1714
- function fromOwnPage(request) {
1715
- const site = request.headers["sec-fetch-site"];
1716
- const origin = request.headers.origin;
1717
- return (site === void 0 || site === "same-origin") && (origin === void 0 || origin === `${requestProtocol(request)}://${request.headers.host}`);
3065
+ function isInternalAppPath(path) {
3066
+ let current = path;
3067
+ for (let round = 0;; round++) {
3068
+ let decoded;
3069
+ try {
3070
+ decoded = decodeURIComponent(current);
3071
+ } catch {
3072
+ return true;
3073
+ }
3074
+ if (decoded === current) break;
3075
+ if (round === MAX_DECODE_ROUNDS) return true;
3076
+ current = decoded;
3077
+ }
3078
+ const resolved = [];
3079
+ for (const segment of current.replace(/\\/g, "/").split("/")) {
3080
+ if (segment === "" || segment === ".") continue;
3081
+ if (segment === "..") resolved.pop();
3082
+ else resolved.push(segment);
3083
+ }
3084
+ if (resolved.join("/") === "_brick/files") return false;
3085
+ return resolved[0]?.toLowerCase() === "_brick";
1718
3086
  }
1719
- function frameOnlyHere(response) {
1720
- response.setHeader("content-security-policy", "frame-ancestors 'self'");
1721
- response.setHeader("x-frame-options", "SAMEORIGIN");
3087
+ const NOT_COPIED = /* @__PURE__ */ new Set([
3088
+ "set-cookie",
3089
+ "content-length",
3090
+ "content-encoding",
3091
+ "transfer-encoding",
3092
+ "connection",
3093
+ "keep-alive"
3094
+ ]);
3095
+ const digest = (value) => createHash("sha256").update(value).digest();
3096
+ /** Whether `candidate` is one of `tokens`, in the same time whichever it is. */
3097
+ function isToken(candidate, tokens) {
3098
+ if (candidate === void 0) return false;
3099
+ const given = digest(candidate);
3100
+ let match = false;
3101
+ for (const token of tokens) if (timingSafeEqual(given, digest(token))) match = true;
3102
+ return match;
1722
3103
  }
1723
- /** The request's headers to send on, without those of this hop or this page. */
1724
- function forwardedHeaders(request) {
3104
+ /** The secret in an `Authorization` header: a Bearer token, or a Basic password. */
3105
+ function credential(request) {
3106
+ const header = request.headers.authorization;
3107
+ if (!header) return void 0;
3108
+ const space = header.indexOf(" ");
3109
+ if (space < 0) return void 0;
3110
+ const scheme = header.slice(0, space).toLowerCase();
3111
+ const value = header.slice(space + 1).trim();
3112
+ if (scheme === "bearer") return value;
3113
+ if (scheme === "basic") {
3114
+ const decoded = Buffer.from(value, "base64").toString("utf8");
3115
+ const colon = decoded.indexOf(":");
3116
+ return colon < 0 ? void 0 : decoded.slice(colon + 1);
3117
+ }
3118
+ }
3119
+ /** The protocol the client used: https when a proxy in front terminated TLS and says so. */
3120
+ function requestProtocol(request) {
3121
+ const forwarded = request.headers["x-forwarded-proto"];
3122
+ return (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(",")[0]?.trim() === "https" ? "https" : "http";
3123
+ }
3124
+ /** The request as the app's `authorize` sees it: standard, with no body. */
3125
+ function webRequest(request) {
1725
3126
  const headers = new Headers();
1726
3127
  for (const [name, value] of Object.entries(request.headers)) {
1727
- if (value === void 0 || NOT_FORWARDED.has(name) || name === DASHBOARD_IDENTITY_HEADER) continue;
1728
- if (name.startsWith("sec-")) continue;
1729
- headers.set(name, Array.isArray(value) ? value.join(", ") : value);
3128
+ if (value === void 0) continue;
3129
+ try {
3130
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
3131
+ } catch {}
1730
3132
  }
1731
- return headers;
1732
- }
1733
- function returnedHeaders(upstream) {
1734
- const returned = {};
1735
- upstream.headers.forEach((value, name) => {
1736
- if (!NOT_RETURNED.has(name)) returned[name] = value;
3133
+ const protocol = requestProtocol(request);
3134
+ const host = request.headers.host ?? "localhost";
3135
+ let url;
3136
+ try {
3137
+ url = new URL(request.url ?? "/", `${protocol}://${host}`).href;
3138
+ } catch {
3139
+ url = `${protocol}://localhost${request.url ?? "/"}`;
3140
+ }
3141
+ return new Request(url, {
3142
+ method: request.method ?? "GET",
3143
+ headers
1737
3144
  });
1738
- return returned;
1739
3145
  }
1740
- // src/dev-history.ts
1741
- const DAY_MS = 864e5;
1742
- const MAX_TRACES = 1e5;
1743
- const FLUSH_MS = 250;
1744
- const PRUNE_MS = 18e5;
1745
- const VOLUME_BUCKETS = 48;
1746
- const MAX_LIMIT = 500;
1747
- const MAX_EXPORT_ROWS = 1e5;
3146
+ const isIdentity = (value) => typeof value === "object" && value !== null && !(value instanceof Response) && typeof value.user?.id === "string";
3147
+ const refusal = (status, body, headers = {}) => ({
3148
+ allowed: false,
3149
+ status,
3150
+ body,
3151
+ headers: {
3152
+ "content-type": "text/plain; charset=utf-8",
3153
+ ...headers
3154
+ }
3155
+ });
1748
3156
  /**
1749
- * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and
1750
- * `node:sqlite` under Node, which is what runs Vite's dev server. Both are
1751
- * imported by a variable name so bundlers leave them alone.
3157
+ * The check for the dashboard's requests. A request passes with a valid token,
3158
+ * or when the app's `authorize` returns `true` or an identity (`{ user }`). Anything else is answered:
3159
+ * what `authorize` returned if it returned a `Response`, else 401 (with a
3160
+ * browser sign-in prompt when tokens are in use), and 503 when `authorize`
3161
+ * threw or ran out of time, since a check that cannot answer must not let
3162
+ * anyone in.
1752
3163
  */
1753
- async function openDatabase(file) {
1754
- if (typeof Bun !== "undefined") {
1755
- const { Database } = await import("bun:sqlite");
1756
- return new Database(file, { create: true });
1757
- }
1758
- const specifier = "node:sqlite";
1759
- const emit = process.emitWarning;
1760
- process.emitWarning = ((warning, ...rest) => {
1761
- if (typeof warning === "string" && warning.includes("SQLite")) return;
1762
- return emit.call(process, warning, ...rest);
1763
- });
1764
- try {
1765
- const { DatabaseSync } = await import(specifier);
1766
- return new DatabaseSync(file);
1767
- } finally {
1768
- process.emitWarning = emit;
1769
- }
3164
+ function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS) {
3165
+ const tokens = auth.token === void 0 ? [] : typeof auth.token === "string" ? [auth.token] : [...auth.token];
3166
+ const prompt = tokens.length > 0 ? { "www-authenticate": "Basic realm=\"Brick dashboard\", charset=\"UTF-8\"" } : {};
3167
+ return async (request) => {
3168
+ if (tokens.length > 0 && isToken(credential(request), tokens)) return {
3169
+ allowed: true,
3170
+ identity: {}
3171
+ };
3172
+ if (!auth.authorize) return refusal(401, "Unauthorized", prompt);
3173
+ let decision;
3174
+ let timer;
3175
+ try {
3176
+ decision = await Promise.race([Promise.resolve(auth.authorize(webRequest(request))), new Promise((_, reject) => {
3177
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("dashboard authorize timed out")), timeoutMs);
3178
+ })]);
3179
+ } catch (error) {
3180
+ onError(error);
3181
+ return refusal(503, "Sign-in is unavailable.");
3182
+ } finally {
3183
+ clearTimeout(timer);
3184
+ }
3185
+ if (decision === true) return {
3186
+ allowed: true,
3187
+ identity: {}
3188
+ };
3189
+ if (isIdentity(decision)) return {
3190
+ allowed: true,
3191
+ identity: { user: {
3192
+ id: decision.user.id,
3193
+ ...typeof decision.user.name === "string" ? { name: decision.user.name } : {}
3194
+ } }
3195
+ };
3196
+ if (decision instanceof Response) {
3197
+ const headers = {};
3198
+ decision.headers.forEach((value, name) => {
3199
+ if (!NOT_COPIED.has(name)) headers[name] = value;
3200
+ });
3201
+ const cookies = decision.headers.getSetCookie();
3202
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
3203
+ return {
3204
+ allowed: false,
3205
+ status: decision.status,
3206
+ headers,
3207
+ body: new Uint8Array(await decision.arrayBuffer())
3208
+ };
3209
+ }
3210
+ return refusal(401, "Unauthorized", prompt);
3211
+ };
1770
3212
  }
3213
+ // src/dev-dashboard.ts
3214
+ const KEEPALIVE_MS = 15e3;
3215
+ const MAX_INGEST_BYTES = 5242880;
3216
+ const MAX_PROXY_BYTES = 10485760;
3217
+ const MAX_MCP_BYTES = 1048576;
3218
+ const NOT_FORWARDED = /* @__PURE__ */ new Set([
3219
+ "host",
3220
+ "connection",
3221
+ "keep-alive",
3222
+ "proxy-connection",
3223
+ "transfer-encoding",
3224
+ "te",
3225
+ "trailer",
3226
+ "upgrade",
3227
+ "content-length",
3228
+ "accept-encoding",
3229
+ "origin",
3230
+ "referer",
3231
+ "cookie"
3232
+ ]);
3233
+ const NOT_RETURNED = /* @__PURE__ */ new Set([
3234
+ "connection",
3235
+ "keep-alive",
3236
+ "transfer-encoding",
3237
+ "content-length",
3238
+ "content-encoding",
3239
+ "set-cookie"
3240
+ ]);
3241
+ const PRODUCTION_POLICY = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'";
3242
+ const INSPECTOR_POLICY = `${PRODUCTION_POLICY.replace("script-src 'self' 'unsafe-inline'", "script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'")}; frame-ancestors 'self'`;
3243
+ const PRODUCTION_HEADERS = {
3244
+ "x-content-type-options": "nosniff",
3245
+ "x-frame-options": "DENY",
3246
+ "referrer-policy": "no-referrer",
3247
+ "cross-origin-opener-policy": "same-origin",
3248
+ "cross-origin-resource-policy": "same-origin",
3249
+ "cache-control": "no-store",
3250
+ "content-security-policy": `${PRODUCTION_POLICY}; frame-ancestors 'none'`
3251
+ };
3252
+ /** How long `/_health` waits for the app before calling it down. */
3253
+ const PROBE_TIMEOUT_MS = 3e3;
1771
3254
  /**
1772
- * Open the request history, or return undefined when it is turned off or this
1773
- * runtime has no SQLite. Never throws: the dashboard works without history.
3255
+ * Serve the dashboard, on loopback unless told otherwise. On loopback requests
3256
+ * must name a local host (blocks DNS rebinding), and restart requires a header
3257
+ * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is
3258
+ * required and decides who gets in. Uses node:http, so it runs under Bun and
3259
+ * under Node (Vite's dev server runs under Node).
1774
3260
  */
1775
- async function openHistory(options) {
1776
- if (!(options.days > 0)) return void 0;
3261
+ function startDevDashboard(options) {
3262
+ const host = options.host ?? "127.0.0.1";
3263
+ const loopback = isLoopbackHost(host);
3264
+ const production = options.mode === "production";
3265
+ if (!loopback && !options.auth) return Promise.reject(new ConfigError(`Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`));
3266
+ let theme;
1777
3267
  try {
1778
- const folder = join(options.directory, ".brick");
1779
- mkdirSync(folder, { recursive: true });
1780
- const ignore = join(folder, ".gitignore");
1781
- if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
1782
- return new DevHistory(await openDatabase(join(folder, "telemetry.sqlite")), options.days, options.warn);
3268
+ theme = themeCss(options.dashboard?.theme);
1783
3269
  } catch (error) {
1784
- const reason = error instanceof Error ? error.message : String(error);
1785
- options.warn?.(`[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`);
1786
- return;
1787
- }
1788
- }
1789
- const text = (value) => value === null || value === void 0 ? void 0 : String(value);
1790
- const number = (value) => value === null || value === void 0 ? void 0 : Number(value);
1791
- /** Each row's outcome, by the rules of `outcomeOf`. */
1792
- const OUTCOME_CASE = `CASE
1793
- WHEN status = 'error' OR http_status >= 500 THEN 'server'
1794
- WHEN http_status >= 400 THEN 'client'
1795
- ELSE 'ok' END`;
1796
- const FACET_COLUMNS = {
1797
- outcome: OUTCOME_CASE,
1798
- method: "method",
1799
- service: "service",
1800
- endpoint: "endpoint"
1801
- };
1802
- /** The WHERE clause for a query, leaving out one filter when counting its facet. */
1803
- function filterSql(query, skip) {
1804
- const clauses = ["start_ms >= ?", "start_ms <= ?"];
1805
- const params = [query.from, query.to];
1806
- const anyOf = (column, values) => {
1807
- if (!values || values.length === 0) return;
1808
- clauses.push(`${column} IN (${values.map(() => "?").join(", ")})`);
1809
- params.push(...values);
1810
- };
1811
- if (skip !== "endpoint") anyOf("endpoint", query.endpoints);
1812
- if (skip !== "method") anyOf("method", query.methods);
1813
- if (skip !== "service") anyOf("service", query.services);
1814
- if (skip !== "outcome") anyOf(OUTCOME_CASE, query.outcomes);
1815
- if (query.minMs !== void 0 && query.minMs > 0) {
1816
- clauses.push("duration_ms >= ?");
1817
- params.push(query.minMs);
3270
+ return Promise.reject(error);
1818
3271
  }
1819
- const needle = query.query?.trim();
1820
- if (needle) {
1821
- const pattern = `%${needle.replace(/[\\%_]/g, "\\$&")}%`;
1822
- clauses.push(`(${SEARCHED.map((column) => `${column} LIKE ? ESCAPE '\\'`).join(" OR ")})`);
1823
- params.push(...SEARCHED.map(() => pattern));
3272
+ const extension = options.dashboard?.extension || !production || options.plugins?.some((plugin) => plugin.dashboard) ? new DashboardExtensions(options.dashboard?.extension, (message) => console.warn(message)) : void 0;
3273
+ const access = options.auth ? createAccess(options.auth, (error) => console.error("[Brick-TS] The dashboard sign-in check failed:", error)) : void 0;
3274
+ let allowedHosts = /* @__PURE__ */ new Set();
3275
+ const server = createServer((request, response) => {
3276
+ respond(request, response).catch((error) => {
3277
+ console.error("[Brick-TS] The dashboard failed to answer:", error);
3278
+ if (response.headersSent) response.end();
3279
+ else send(response, 500, "Server error");
3280
+ });
3281
+ });
3282
+ async function respond(request, response) {
3283
+ if (production) for (const [name, value] of Object.entries(PRODUCTION_HEADERS)) response.setHeader(name, value);
3284
+ if (loopback && !allowedHosts.has(request.headers.host ?? "")) {
3285
+ send(response, 403, "Forbidden");
3286
+ return;
3287
+ }
3288
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
3289
+ const route = matchRoute(request.method, url.pathname);
3290
+ if (route === "health") {
3291
+ await health(response);
3292
+ return;
3293
+ }
3294
+ let identity = {};
3295
+ if (access) {
3296
+ const decision = await access(request);
3297
+ if (!decision.allowed) {
3298
+ send(response, decision.status, decision.body, decision.headers);
3299
+ return;
3300
+ }
3301
+ identity = decision.identity;
3302
+ }
3303
+ if (!route || production && !servedInProduction(route)) {
3304
+ send(response, 404, "Not found");
3305
+ return;
3306
+ }
3307
+ if ("csrf" in ROUTES[route] && request.headers["x-brick-dashboard"] !== "1") {
3308
+ send(response, 403, "Forbidden");
3309
+ return;
3310
+ }
3311
+ await handlers[route](request, response, url, identity);
1824
3312
  }
1825
- return {
1826
- sql: clauses.join(" AND "),
1827
- params
1828
- };
1829
- }
1830
- const orderSql = (sort) => sort === "slowest" ? "duration_ms DESC, start_ms DESC" : "start_ms DESC";
1831
- const LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,
1832
- start_ms, end_ms, duration_ms, status, truncated, service, action, message`;
1833
- function toHistoryTrace(row) {
1834
- return {
1835
- traceId: String(row.trace_id),
1836
- name: String(row.name),
1837
- endpoint: String(row.endpoint),
1838
- method: text(row.method),
1839
- route: text(row.route),
1840
- path: text(row.path),
1841
- httpStatus: number(row.http_status),
1842
- generation: Number(row.generation),
1843
- startMs: Number(row.start_ms),
1844
- endMs: number(row.end_ms),
1845
- durationMs: number(row.duration_ms),
1846
- status: String(row.status),
1847
- truncated: Number(row.truncated) === 1,
1848
- service: text(row.service),
1849
- action: text(row.action),
1850
- message: text(row.message)
1851
- };
1852
- }
1853
- /**
1854
- * Requests kept on disk between runs, for looking back over weeks
1855
- * instead of the last few minutes. Writes are batched; reads see them.
1856
- */
1857
- var DevHistory = class {
1858
- days;
1859
- #database;
1860
- #pendingTraces = /* @__PURE__ */ new Map();
1861
- #flushTimer;
1862
- #pruneTimer;
1863
- #closed = false;
1864
- #warn;
1865
- /** Failure kinds already reported: one warning each, not one per batch. */
1866
- #warned = /* @__PURE__ */ new Set();
1867
- constructor(database, days, warn) {
1868
- this.#database = database;
1869
- this.days = days;
1870
- this.#warn = warn;
1871
- database.exec(`
1872
- PRAGMA journal_mode = WAL;
1873
- PRAGMA synchronous = NORMAL;
1874
- PRAGMA busy_timeout = 2000;
1875
- CREATE TABLE IF NOT EXISTS traces (
1876
- trace_id TEXT PRIMARY KEY,
1877
- name TEXT NOT NULL,
1878
- endpoint TEXT NOT NULL,
1879
- method TEXT,
1880
- route TEXT,
1881
- path TEXT,
1882
- http_status INTEGER,
1883
- generation INTEGER NOT NULL,
1884
- start_ms INTEGER NOT NULL,
1885
- end_ms INTEGER,
1886
- duration_ms REAL,
1887
- status TEXT NOT NULL,
1888
- truncated INTEGER NOT NULL,
1889
- spans TEXT NOT NULL,
1890
- service TEXT,
1891
- action TEXT,
1892
- message TEXT
1893
- );
1894
- CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);
1895
- CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);
1896
- -- Earlier versions kept failures here; nothing reads them now.
1897
- DROP TABLE IF EXISTS failures;
1898
- `);
1899
- this.#addMissingColumns();
1900
- this.prune();
1901
- this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);
1902
- this.#pruneTimer.unref?.();
3313
+ function servedInProduction(route) {
3314
+ const served = ROUTES[route].production;
3315
+ if (served === "extension") return Boolean(extension?.active);
3316
+ if (served === "mcp") return Boolean(options.mcp);
3317
+ return served === "inspector" ? Boolean(options.inspector && options.store.inspectorTarget()) : served;
1903
3318
  }
1904
- /** A folder from an earlier version has the table without the newer columns. */
1905
- #addMissingColumns() {
1906
- const present = new Set(this.#database.prepare("PRAGMA table_info(traces)").all().map((column) => String(column.name)));
1907
- for (const column of [
1908
- "service",
1909
- "action",
1910
- "message"
1911
- ]) if (!present.has(column)) this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);
3319
+ /** 200 while the app answers its own health check, 503 when it does not. */
3320
+ async function health(response) {
3321
+ const probe = options.probe;
3322
+ let up = true;
3323
+ if (probe) {
3324
+ let timer;
3325
+ up = await Promise.race([probe().catch(() => false), new Promise((resolve) => {
3326
+ timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);
3327
+ })]);
3328
+ clearTimeout(timer);
3329
+ }
3330
+ send(response, up ? 200 : 503, JSON.stringify({
3331
+ status: up ? "ok" : "degraded",
3332
+ ...probe ? { app: up ? "up" : "down" } : {}
3333
+ }), {
3334
+ "content-type": "application/json",
3335
+ "cache-control": "no-store"
3336
+ });
1912
3337
  }
1913
- /** Queue a finished request. A later save of the same request replaces it. */
1914
- saveTrace(trace) {
1915
- if (this.#closed) return;
1916
- this.#pendingTraces.set(trace.traceId, trace);
1917
- this.#scheduleFlush();
3338
+ const handlers = {
3339
+ shell: (_request, response) => send(response, 200, dashboardShell({
3340
+ extension: extension?.active ? {
3341
+ revision: extension.revision,
3342
+ js: Boolean(extension.built),
3343
+ css: Boolean(extension.built?.css)
3344
+ } : void 0,
3345
+ theme: theme !== "",
3346
+ mode: production ? "production" : "dev"
3347
+ }), {
3348
+ "content-type": "text/html; charset=utf-8",
3349
+ "cache-control": "no-store"
3350
+ }),
3351
+ assets(_request, response, url) {
3352
+ const name = url.pathname.slice(ROUTES.assets.path.length + 1);
3353
+ const own = name === ASSETS.theme ? theme : extension?.asset(name);
3354
+ if (own !== void 0) send(response, 200, own, {
3355
+ "content-type": assetType(name),
3356
+ "cache-control": "no-store"
3357
+ });
3358
+ else serveAsset(response, name);
3359
+ },
3360
+ app,
3361
+ state: (_request, response) => json(response, snapshot()),
3362
+ events: eventStream,
3363
+ history(_request, response, url) {
3364
+ if (options.history) history(options.history, url.pathname, url.searchParams, response);
3365
+ else send(response, 404, "Not found");
3366
+ },
3367
+ docs: (_request, response, url) => docsRoute(response, url.pathname, url.searchParams),
3368
+ openapi: (_request, response) => json(response, options.store.apiDocuments()),
3369
+ proxy,
3370
+ workflows(request, response, url, identity) {
3371
+ frameOnlyHere(response);
3372
+ if (production) response.setHeader("content-security-policy", INSPECTOR_POLICY);
3373
+ return inspector(request, response, url, identity);
3374
+ },
3375
+ schedules: inspector,
3376
+ mcp: mcpRoute,
3377
+ ingest,
3378
+ restart(request, response) {
3379
+ if (!options.restart) {
3380
+ send(response, 404, "Not found");
3381
+ return;
3382
+ }
3383
+ options.restart();
3384
+ send(response, 202, "");
3385
+ }
3386
+ };
3387
+ const mayChange = (identity) => !production || Boolean(identity.user);
3388
+ const mcp = createDashboardMcp({
3389
+ store: options.store,
3390
+ history: options.history,
3391
+ mode: production ? "production" : "dev",
3392
+ inspector: !production || Boolean(options.inspector),
3393
+ docs: options.docs,
3394
+ appUrl: () => options.appUrl ?? options.store.apiSnapshot()?.appUrl,
3395
+ mayChange
3396
+ });
3397
+ /**
3398
+ * The MCP endpoint. Browsers have no use for it, so a request from another
3399
+ * origin is refused (`fromOwnPage` accepts an `Origin` that matches the
3400
+ * `Host`, so it does not stop DNS rebinding: the `allowedHosts` check in
3401
+ * `respond` does, on loopback).
3402
+ */
3403
+ async function mcpRoute(request, response, url, identity) {
3404
+ if (!fromOwnPage(request)) {
3405
+ send(response, 403, "Forbidden");
3406
+ return;
3407
+ }
3408
+ const body = isBodyless(request) ? void 0 : await readBytes(request, MAX_MCP_BYTES);
3409
+ if (!isBodyless(request) && !body) {
3410
+ tooLarge(response);
3411
+ return;
3412
+ }
3413
+ const headers = forwardedHeaders(request);
3414
+ const answer = await mcp(new Request(`http://127.0.0.1${url.pathname}`, {
3415
+ method: request.method,
3416
+ headers,
3417
+ ...body ? { body } : {}
3418
+ }), identity);
3419
+ const returned = { "cache-control": "no-store" };
3420
+ answer.headers.forEach((value, name) => {
3421
+ returned[name] = value;
3422
+ });
3423
+ send(response, answer.status, await answer.text(), returned);
1918
3424
  }
1919
- #scheduleFlush() {
1920
- if (this.#flushTimer) return;
1921
- this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
1922
- this.#flushTimer.unref?.();
3425
+ function snapshot() {
3426
+ return {
3427
+ ...options.store.snapshot(),
3428
+ canRestart: Boolean(options.restart),
3429
+ historyDays: options.history?.days ?? 0,
3430
+ mode: production ? "production" : "dev",
3431
+ hiddenViews: production ? viewsWithout(servedInProduction) : [],
3432
+ extension: extension?.active ? {
3433
+ revision: extension.revision,
3434
+ error: extension.error
3435
+ } : null
3436
+ };
1923
3437
  }
1924
- flush() {
1925
- if (this.#flushTimer) {
1926
- clearTimeout(this.#flushTimer);
1927
- this.#flushTimer = void 0;
3438
+ /**
3439
+ * Accept telemetry from an application process that cannot share memory with
3440
+ * the dashboard, such as a dev server worker: span batches, and a notice when
3441
+ * the app loads.
3442
+ */
3443
+ async function ingest(request, response) {
3444
+ const body = await readBytes(request, MAX_INGEST_BYTES);
3445
+ if (!body) {
3446
+ tooLarge(response);
3447
+ return;
1928
3448
  }
1929
- if (this.#closed || this.#pendingTraces.size === 0) return;
1930
- const traces = [...this.#pendingTraces.values()];
1931
- this.#pendingTraces.clear();
3449
+ let payload;
1932
3450
  try {
1933
- this.#database.exec("BEGIN");
1934
- const saveTrace = this.#database.prepare(`INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,
1935
- http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,
1936
- service, action, message)
1937
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
1938
- for (const trace of traces) saveTrace.run(trace.traceId, trace.name, endpointOf(trace), trace.method ?? null, trace.route ?? null, trace.path ?? null, trace.httpStatus ?? null, trace.generation, trace.startMs, trace.endMs ?? null, trace.durationMs ?? null, trace.status, trace.truncated ? 1 : 0, JSON.stringify(trace.spans), trace.service ?? null, trace.action ?? null, trace.message ?? null);
1939
- this.#database.exec("COMMIT");
1940
- } catch (error) {
1941
- this.#warnOnce("save requests to", error);
1942
- try {
1943
- this.#database.exec("ROLLBACK");
1944
- } catch {}
3451
+ payload = JSON.parse(Buffer.from(body).toString("utf8"));
3452
+ } catch {
3453
+ payload = null;
3454
+ }
3455
+ if (payload === null || typeof payload !== "object") {
3456
+ send(response, 400, "Bad request");
3457
+ return;
1945
3458
  }
3459
+ if (Array.isArray(payload.records)) options.store.ingest(payload.records, options.store.latestGeneration);
3460
+ if (typeof payload.worker === "string") options.store.startGeneration(payload.worker);
3461
+ send(response, 204, "");
1946
3462
  }
1947
- /** Drop what is past retention, then the oldest beyond the size cap. */
1948
- prune(now = Date.now()) {
1949
- if (this.#closed) return;
3463
+ async function docsRoute(response, pathname, params) {
3464
+ const docs = options.docs?.();
3465
+ if (!docs) {
3466
+ send(response, 404, "The app has no documentation.");
3467
+ return;
3468
+ }
1950
3469
  try {
1951
- const cutoff = now - this.days * DAY_MS;
1952
- this.#database.prepare("DELETE FROM traces WHERE start_ms < ?").run(cutoff);
1953
- const count = Number(this.#database.prepare("SELECT COUNT(*) AS n FROM traces").get()?.n ?? 0);
1954
- if (count > MAX_TRACES) this.#database.prepare("DELETE FROM traces WHERE trace_id IN (SELECT trace_id FROM traces ORDER BY start_ms ASC LIMIT ?)").run(count - MAX_TRACES);
3470
+ if (pathname === DOCS_PATHS.info) return json(response, docs.info());
3471
+ if (pathname === DOCS_PATHS.search) return json(response, await docs.search(params.get("q") ?? ""));
3472
+ if (pathname === DOCS_PATHS.components) {
3473
+ const code = await docs.components();
3474
+ if (code === void 0) return send(response, 404, "No components.");
3475
+ return send(response, 200, code, {
3476
+ "content-type": "text/javascript; charset=utf-8",
3477
+ "cache-control": "no-store"
3478
+ });
3479
+ }
3480
+ const pagePrefix = DOCS_PATHS.page;
3481
+ if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {
3482
+ const slugs = pathname.slice(pagePrefix.length).split("/").filter(Boolean).map(decodeURIComponent);
3483
+ const page = await docs.page(slugs);
3484
+ return page ? json(response, page) : send(response, 404, "No such page.");
3485
+ }
3486
+ const filePrefix = `${DOCS_PATHS.files}/`;
3487
+ if (pathname.startsWith(filePrefix)) {
3488
+ const file = await docs.file(pathname.slice(filePrefix.length).split("/").map(decodeURIComponent).join("/"));
3489
+ if (!file) return send(response, 404, "No such file.");
3490
+ return send(response, 200, file.body, {
3491
+ "content-type": file.type,
3492
+ "cache-control": "no-store",
3493
+ "content-security-policy": "sandbox"
3494
+ });
3495
+ }
3496
+ send(response, 404, "Not found");
1955
3497
  } catch (error) {
1956
- this.#warnOnce("prune", error);
3498
+ send(response, error instanceof URIError ? 400 : 500, error instanceof Error ? error.message : String(error));
1957
3499
  }
1958
3500
  }
1959
- #warnOnce(action, error) {
1960
- if (this.#warned.has(action)) return;
1961
- this.#warned.add(action);
1962
- const reason = error instanceof Error ? error.message : String(error);
1963
- this.#warn?.(`[Brick-TS] Could not ${action} the request history (${reason}).`);
1964
- }
1965
- info() {
1966
- this.flush();
1967
- const row = this.#database.prepare("SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces").get();
1968
- return {
1969
- days: this.days,
1970
- count: Number(row?.n ?? 0),
1971
- oldestMs: number(row?.oldest)
1972
- };
1973
- }
1974
- /** Matching requests, without spans, and how many match in total. */
1975
- traces(query) {
1976
- this.flush();
1977
- const { sql, params } = filterSql(query);
1978
- const total = Number(this.#database.prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`).get(...params)?.n ?? 0);
1979
- const limit = Math.min(Math.max(query.limit ?? 100, 1), MAX_LIMIT);
1980
- const offset = Math.max(query.offset ?? 0, 0);
1981
- return {
1982
- total,
1983
- traces: this.#database.prepare(`SELECT ${LIST_COLUMNS}
1984
- FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ? OFFSET ?`).all(...params, limit, offset).map(toHistoryTrace)
1985
- };
3501
+ /**
3502
+ * Pass a request to the workflow inspector, which the app serves on a port of
3503
+ * its own, and stream its answer back (it follows a run's output as it
3504
+ * grows). Anyone who can open the dashboard may look, but a change must come
3505
+ * from the dashboard's own page: the inspector can cancel runs and resume
3506
+ * hooks, and a page on another site could otherwise post to it.
3507
+ */
3508
+ async function inspector(request, response, url, identity) {
3509
+ const target = options.store.inspectorTarget();
3510
+ if (!target) {
3511
+ send(response, 503, "The workflow inspector and schedules are not being served. The app may be restarting, or it may have neither workflows nor schedules.", { "content-type": "text/plain; charset=utf-8" });
3512
+ return;
3513
+ }
3514
+ if (!isBodyless(request) && !fromOwnPage(request)) {
3515
+ send(response, 403, "Forbidden");
3516
+ return;
3517
+ }
3518
+ await forward(request, response, `http://127.0.0.1:${target.port}${url.pathname}${url.search}`, (headers) => {
3519
+ headers.set(INSPECTOR_TOKEN_HEADER, target.token);
3520
+ if (!mayChange(identity)) headers.set(INSPECTOR_READ_ONLY_HEADER, "1");
3521
+ else headers.delete(INSPECTOR_READ_ONLY_HEADER);
3522
+ }, "Could not reach the workflow inspector.");
1986
3523
  }
1987
- /** Counts for each filter over the range, ignoring that filter's own choice. */
1988
- facets(query) {
1989
- this.flush();
1990
- const count = (facet) => {
1991
- const { sql, params } = filterSql(query, facet);
1992
- const column = FACET_COLUMNS[facet];
1993
- return this.#database.prepare(`SELECT ${column} AS value, COUNT(*) AS n FROM traces
1994
- WHERE ${sql} AND ${column} IS NOT NULL
1995
- GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`).all(...params, 30).map((row) => ({
1996
- value: String(row.value),
1997
- count: Number(row.n)
1998
- }));
1999
- };
2000
- return {
2001
- outcome: count("outcome"),
2002
- method: count("method"),
2003
- service: count("service"),
2004
- endpoint: count("endpoint")
2005
- };
3524
+ /**
3525
+ * Pass `/app/*` to the app, so the extension's pages read it from the
3526
+ * dashboard's own origin. Only the dashboard's page may use it, as with the
3527
+ * API proxy. A credential for the dashboard itself is not passed on; who the
3528
+ * dashboard let in is, signed, for `ctx.dashboard` and `dashboardUser()`.
3529
+ */
3530
+ async function app(request, response, url, identity) {
3531
+ if (!fromOwnPage(request)) {
3532
+ send(response, 403, "Forbidden");
3533
+ return;
3534
+ }
3535
+ if (isInternalAppPath(url.pathname.slice(ROUTES.app.path.length))) {
3536
+ send(response, 404, "Not found");
3537
+ return;
3538
+ }
3539
+ const appUrl = options.appUrl ?? options.store.apiSnapshot()?.appUrl;
3540
+ if (!appUrl) {
3541
+ send(response, 503, "The app is not running yet.");
3542
+ return;
3543
+ }
3544
+ frameOnlyHere(response);
3545
+ await forward(request, response, `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || "/"}${url.search}`, (headers) => {
3546
+ if (access) headers.delete("authorization");
3547
+ headers.set(DASHBOARD_IDENTITY_HEADER, signDashboardIdentity(identity));
3548
+ }, "Could not reach the app.");
2006
3549
  }
2007
- /** Matching requests per time bucket across the range, by outcome. */
2008
- volume(query, buckets = VOLUME_BUCKETS) {
2009
- this.flush();
2010
- const { sql, params } = filterSql(query);
2011
- const bucketMs = bucketSize(query.from, query.to, buckets);
2012
- const result = Array.from({ length: buckets }, (_, index) => ({
2013
- start: query.from + index * bucketMs,
2014
- ok: 0,
2015
- client: 0,
2016
- server: 0
2017
- }));
2018
- const rows = this.#database.prepare(`SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,
2019
- COUNT(*) AS n
2020
- FROM traces WHERE ${sql} GROUP BY bucket, outcome`).all(query.from, bucketMs, ...params);
2021
- for (const row of rows) {
2022
- const bucket = result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];
2023
- const outcome = String(row.outcome);
2024
- if (bucket) bucket[outcome] += Number(row.n);
3550
+ /**
3551
+ * Send the request on to `target` and stream its answer back. `body`: the
3552
+ * request's body when the caller already read it; else it is streamed.
3553
+ */
3554
+ async function forward(request, response, target, adjust, unreachable, body) {
3555
+ const headers = forwardedHeaders(request);
3556
+ adjust(headers);
3557
+ const abort = new AbortController();
3558
+ response.on("close", () => abort.abort());
3559
+ try {
3560
+ const upstream = await fetch(target, {
3561
+ method: request.method,
3562
+ headers,
3563
+ redirect: "manual",
3564
+ signal: abort.signal,
3565
+ ...isBodyless(request) ? {} : body ? { body } : {
3566
+ body: Readable.toWeb(request),
3567
+ duplex: "half"
3568
+ }
3569
+ });
3570
+ response.writeHead(upstream.status, returnedHeaders(upstream));
3571
+ if (!upstream.body || request.method === "HEAD") {
3572
+ response.end();
3573
+ return;
3574
+ }
3575
+ await pipeline(Readable.fromWeb(upstream.body), response);
3576
+ } catch {
3577
+ if (response.headersSent) response.destroy();
3578
+ else send(response, 502, unreachable);
2025
3579
  }
2026
- return result;
2027
3580
  }
2028
- /** Every matching request, newest first, as CSV for a spreadsheet. */
2029
- exportCsv(query) {
2030
- this.flush();
2031
- const { sql, params } = filterSql(query);
2032
- return tracesToCsv(this.#database.prepare(`SELECT ${LIST_COLUMNS}
2033
- FROM traces WHERE ${sql} ORDER BY ${orderSql(query.sort)} LIMIT ?`).all(...params, MAX_EXPORT_ROWS).map(toHistoryTrace));
3581
+ /**
3582
+ * Send a request on to the app for the APIs view, which cannot call the app
3583
+ * directly: it is another origin. Only the dashboard's own page may use this,
3584
+ * and only to reach the app being shown. The address to call is `?url=`; a
3585
+ * `?cookie=` is the cookie parameters the reader typed into Try it, and the
3586
+ * only cookie the app is sent (the dashboard's own are never forwarded).
3587
+ */
3588
+ async function proxy(request, response, url) {
3589
+ if (!fromOwnPage(request)) {
3590
+ send(response, 403, "Forbidden");
3591
+ return;
3592
+ }
3593
+ let target;
3594
+ try {
3595
+ target = new URL(url.searchParams.get("url") ?? "");
3596
+ } catch {}
3597
+ const appUrl = options.store.apiSnapshot()?.appUrl;
3598
+ if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {
3599
+ send(response, 403, "Only the app shown in the dashboard can be reached.");
3600
+ return;
3601
+ }
3602
+ const body = await readBytes(request, MAX_PROXY_BYTES);
3603
+ if (!body) {
3604
+ tooLarge(response);
3605
+ return;
3606
+ }
3607
+ const cookie = url.searchParams.get("cookie");
3608
+ await forward(request, response, target.href, (headers) => {
3609
+ if (cookie) headers.set("cookie", cookie);
3610
+ }, "Could not reach the app.", body);
2034
3611
  }
2035
- trace(traceId) {
2036
- this.flush();
2037
- const row = this.#database.prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`).get(traceId);
2038
- if (!row) return void 0;
2039
- const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);
2040
- return {
2041
- ...trace,
2042
- spans: JSON.parse(String(row.spans))
3612
+ function eventStream(request, response) {
3613
+ response.writeHead(200, {
3614
+ "content-type": "text/event-stream",
3615
+ "cache-control": "no-cache",
3616
+ connection: "keep-alive",
3617
+ "x-accel-buffering": "no"
3618
+ });
3619
+ const write = (chunk) => {
3620
+ if (response.writableEnded || response.destroyed) return;
3621
+ response.write(chunk);
2043
3622
  };
3623
+ const emit = (name, data) => write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
3624
+ emit("snapshot", snapshot());
3625
+ const unsubscribe = options.store.subscribe((event) => emit(event.type, event));
3626
+ const unwatch = extension?.onChange(() => emit("extension", snapshot().extension));
3627
+ const keepalive = setInterval(() => write(": keepalive\n\n"), KEEPALIVE_MS);
3628
+ request.on("close", () => {
3629
+ clearInterval(keepalive);
3630
+ unsubscribe();
3631
+ unwatch?.();
3632
+ });
2044
3633
  }
2045
- /** How many requests match, how many failed, and how long they took. */
2046
- summary(query) {
2047
- this.flush();
2048
- const { sql, params } = filterSql(query);
2049
- let total = 0;
2050
- let clientErrors = 0;
2051
- let serverErrors = 0;
2052
- const counts = this.#database.prepare(`SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n
2053
- FROM traces WHERE ${sql} GROUP BY outcome`).all(...params);
2054
- for (const row of counts) {
2055
- const n = Number(row.n);
2056
- total += n;
2057
- if (row.outcome === "client") clientErrors = n;
2058
- if (row.outcome === "server") serverErrors = n;
2059
- }
2060
- const durations = this.#database.prepare(`SELECT duration_ms FROM traces
2061
- WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`).all(...params).map((row) => Number(row.duration_ms));
2062
- return {
2063
- total,
2064
- clientErrors,
2065
- serverErrors,
2066
- medianMs: percentile(durations, .5),
2067
- p95Ms: percentile(durations, .95)
2068
- };
3634
+ return (extension ? Promise.all([extension.load(), options.plugins && extension.setPlugins(options.plugins)]) : Promise.resolve()).then(() => listen());
3635
+ function listen() {
3636
+ return new Promise((resolve, reject) => {
3637
+ server.once("error", (error) => {
3638
+ extension?.close();
3639
+ reject(new Error(`Brick: dashboard port ${options.port} is unavailable.${options.portHint ? ` ${options.portHint}` : ""}`, { cause: error }));
3640
+ });
3641
+ server.listen(options.port, host, () => {
3642
+ const address = server.address();
3643
+ const port = typeof address === "object" && address !== null ? address.port : options.port;
3644
+ allowedHosts = /* @__PURE__ */ new Set([
3645
+ `127.0.0.1:${port}`,
3646
+ `localhost:${port}`,
3647
+ `[::1]:${port}`
3648
+ ]);
3649
+ if (!production) extension?.watch();
3650
+ resolve({
3651
+ port,
3652
+ setPluginExtensions: (plugins) => extension?.setPlugins(plugins) ?? Promise.resolve(),
3653
+ stop() {
3654
+ extension?.close();
3655
+ server.close();
3656
+ server.closeAllConnections();
3657
+ }
3658
+ });
3659
+ });
3660
+ });
2069
3661
  }
2070
- /** Write what is queued and release the database. */
2071
- close() {
2072
- if (this.#closed) return;
2073
- this.flush();
2074
- this.#closed = true;
2075
- clearInterval(this.#pruneTimer);
2076
- try {
2077
- this.#database.close();
2078
- } catch {}
3662
+ }
3663
+ /** The whole request body, or undefined when it is larger than `limit`. */
3664
+ function readBytes(request, limit) {
3665
+ return new Promise((resolve) => {
3666
+ const chunks = [];
3667
+ let size = 0;
3668
+ request.on("data", (chunk) => {
3669
+ size += chunk.length;
3670
+ if (size > limit) {
3671
+ request.removeAllListeners("data");
3672
+ request.resume();
3673
+ resolve(void 0);
3674
+ return;
3675
+ }
3676
+ chunks.push(chunk);
3677
+ });
3678
+ request.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
3679
+ request.on("error", () => resolve(void 0));
3680
+ });
3681
+ }
3682
+ function history(store, pathname, params, response) {
3683
+ const queries = {
3684
+ summary: (query) => store.summary(query),
3685
+ traces: (query) => store.traces(query),
3686
+ facets: (query) => store.facets(query),
3687
+ volume: (query) => store.volume(query)
3688
+ };
3689
+ try {
3690
+ const endpoint = pathname.slice(ROUTES.history.path.length + 1);
3691
+ if (endpoint === "") return json(response, store.info());
3692
+ if (endpoint === "export") return send(response, 200, store.exportCsv(decodeHistoryQuery(params)), {
3693
+ "content-type": "text/csv; charset=utf-8",
3694
+ "content-disposition": "attachment; filename=\"brick-requests.csv\"",
3695
+ "cache-control": "no-store"
3696
+ });
3697
+ if (Object.hasOwn(queries, endpoint)) return json(response, queries[endpoint](decodeHistoryQuery(params)));
3698
+ if (endpoint.startsWith("traces/")) {
3699
+ const trace = store.trace(decodeURIComponent(endpoint.slice(7)));
3700
+ if (trace) return json(response, trace);
3701
+ }
3702
+ send(response, 404, "Not found");
3703
+ } catch (error) {
3704
+ if (error instanceof URIError) return send(response, 400, error.message);
3705
+ console.error("[Brick-TS] A dashboard history query failed:", error);
3706
+ send(response, 500, "History query failed");
2079
3707
  }
3708
+ }
3709
+ const ASSET_TYPES = {
3710
+ ".js": "text/javascript; charset=utf-8",
3711
+ ".css": "text/css; charset=utf-8",
3712
+ ".woff2": "font/woff2"
2080
3713
  };
3714
+ const assetType = (name) => ASSET_TYPES[extname(name)] ?? "application/octet-stream";
3715
+ function serveAsset(response, name) {
3716
+ if (!/^[\w.-]+$/.test(name) || name.startsWith(".")) {
3717
+ send(response, 404, "Not found");
3718
+ return;
3719
+ }
3720
+ const directory = assetsDirectory();
3721
+ if (!directory) {
3722
+ send(response, 503, "Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build");
3723
+ return;
3724
+ }
3725
+ readFile(join(directory, name)).then((body) => send(response, 200, body, {
3726
+ "content-type": assetType(name),
3727
+ "cache-control": "no-store"
3728
+ }), () => send(response, 404, "Not found"));
3729
+ }
3730
+ function tooLarge(response) {
3731
+ send(response, 413, "Payload too large", {
3732
+ "content-type": "text/plain; charset=utf-8",
3733
+ connection: "close"
3734
+ });
3735
+ }
3736
+ function send(response, status, body, headers = { "content-type": "text/plain; charset=utf-8" }) {
3737
+ response.writeHead(status, headers);
3738
+ response.end(body);
3739
+ }
3740
+ function json(response, body) {
3741
+ send(response, 200, JSON.stringify(body), {
3742
+ "content-type": "application/json",
3743
+ "cache-control": "no-store"
3744
+ });
3745
+ }
3746
+ const isBodyless = (request) => request.method === "GET" || request.method === "HEAD";
3747
+ /**
3748
+ * Whether a request comes from the dashboard's own page, as far as the browser
3749
+ * says: the same site, and the same origin as the address it was sent to.
3750
+ * Behind a proxy that terminates TLS that address is https.
3751
+ */
3752
+ function fromOwnPage(request) {
3753
+ const site = request.headers["sec-fetch-site"];
3754
+ const origin = request.headers.origin;
3755
+ return (site === void 0 || site === "same-origin") && (origin === void 0 || origin === `${requestProtocol(request)}://${request.headers.host}`);
3756
+ }
3757
+ function frameOnlyHere(response) {
3758
+ response.setHeader("content-security-policy", "frame-ancestors 'self'");
3759
+ response.setHeader("x-frame-options", "SAMEORIGIN");
3760
+ }
3761
+ /** The request's headers to send on, without those of this hop or this page. */
3762
+ function forwardedHeaders(request) {
3763
+ const headers = new Headers();
3764
+ for (const [name, value] of Object.entries(request.headers)) {
3765
+ if (value === void 0 || NOT_FORWARDED.has(name) || name === DASHBOARD_IDENTITY_HEADER) continue;
3766
+ if (name.startsWith("sec-")) continue;
3767
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
3768
+ }
3769
+ return headers;
3770
+ }
3771
+ function returnedHeaders(upstream) {
3772
+ const returned = {};
3773
+ upstream.headers.forEach((value, name) => {
3774
+ if (!NOT_RETURNED.has(name)) returned[name] = value;
3775
+ });
3776
+ return returned;
3777
+ }
2081
3778
  // src/dev-telemetry-store.ts
2082
3779
  const LIMITS = {
2083
3780
  ...LIVE_LIMITS,
@@ -2225,6 +3922,14 @@ var DevTelemetryStore = class {
2225
3922
  inspector: Boolean(target?.workflows)
2226
3923
  });
2227
3924
  }
3925
+ /** The architecture as the app last reported it, without building the whole snapshot. */
3926
+ architecture() {
3927
+ return this.#architecture;
3928
+ }
3929
+ /** Whether the app serves the workflow inspector, not only the schedules. */
3930
+ servesWorkflows() {
3931
+ return Boolean(this.#inspector?.workflows);
3932
+ }
2228
3933
  /** Where the dashboard proxies the workflow inspector and schedules, when the app serves them. */
2229
3934
  inspectorTarget() {
2230
3935
  return this.#inspector;