@brickkit/cli 0.16.0-beta.2 → 0.16.0-beta.4

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