constructor-research-mcp 0.6.4 → 0.6.7-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import { randomUUID, createHash } from "node:crypto";
2
2
  import { setTimeout as delay } from "node:timers/promises";
3
3
  import { ToolError, segment as e } from "./api.js";
4
+ import { classify, diagnostics, steps } from "./diagnose.js";
4
5
  import { deployInput, updateInput, buildInput, listInput, lifecycleInput, getInput, deleteInput, } from "./schemas.js";
5
6
  const NOTICE = "Start requested; application readiness is unverified. Initial small deployments usually take 1–2 minutes; updates often take tens of seconds. These are estimates.";
6
7
  export const terminal = new Set([
@@ -236,8 +237,32 @@ export class DeploymentEngine {
236
237
  op.errorSeen[key] = image.id;
237
238
  return "wait";
238
239
  }
239
- if (op.retried[key])
240
+ // Confirmed: read what the build printed to its end before deciding anything.
241
+ const log = await this.logs?.settle(image.id, "build");
242
+ const cause = classify(log?.lines ?? []);
243
+ op.attempts ??= {};
244
+ const attempts = (op.attempts[key] ??= []);
245
+ let attempt = attempts.find((a) => a.image_id === image.id);
246
+ if (!attempt) {
247
+ attempt = {
248
+ image_id: image.id,
249
+ image_name: image.name,
250
+ result: "error",
251
+ cause: cause.kind,
252
+ reason: cause.reason,
253
+ };
254
+ attempts.push(attempt);
255
+ }
256
+ if (op.retried[key]) {
257
+ attempt.next = "not rebuilt again: one automatic rebuild per service";
258
+ return "fail";
259
+ }
260
+ // The same sources fail the same way: a second identical build only costs minutes.
261
+ if (cause.kind === "compile") {
262
+ attempt.next =
263
+ "not rebuilt automatically: the sources do not compile, and an identical rebuild fails the same way";
240
264
  return "fail";
265
+ }
241
266
  op.retried[key] = image.name ?? image.id;
242
267
  delete op.errorSeen[key];
243
268
  if (this.files && source.local_path)
@@ -257,16 +282,36 @@ export class DeploymentEngine {
257
282
  const pre = await this.files.preflight(op.project_id, [
258
283
  { service: key, ...source, ports: [] },
259
284
  ]);
260
- if (pre.missing.length)
285
+ if (pre.missing.length) {
286
+ attempt.next = "not rebuilt: the Dockerfile is no longer on the disk";
261
287
  return "fail";
288
+ }
262
289
  }
263
290
  delete op.images[key];
264
- op.message = `Build for ${key} failed; the MCP re-checked the source files and is rebuilding once under a new name.`;
291
+ attempt.next =
292
+ cause.kind === "transient"
293
+ ? "rebuilt once under a new name after re-checking the source files (likely transient)"
294
+ : "rebuilt once under a new name after re-checking the source files (cause uncertain)";
295
+ op.message = `Build for ${key} failed (${cause.kind === "transient" ? "likely transient" : "cause uncertain"}); the MCP re-checked the source files and is rebuilding once under a new name.`;
265
296
  return "retry";
266
297
  }
267
298
  async buildFailed(op, key, image, deskId, dockerfile, service) {
268
299
  const link = this.deskLink(op.project_id, deskId);
269
300
  const first = op.retried?.[key];
301
+ const log = await this.logs?.settle(image.id, "build");
302
+ const lines = log?.lines ?? [];
303
+ const found = diagnostics(lines);
304
+ const attempt = op.attempts?.[key]?.find((a) => a.image_id === image.id);
305
+ const cause = attempt
306
+ ? { kind: attempt.cause, reason: attempt.reason }
307
+ : classify(lines);
308
+ const coverage = !log
309
+ ? "none"
310
+ : log.complete
311
+ ? "complete"
312
+ : log.state === "live"
313
+ ? "live"
314
+ : "partial";
270
315
  op.status = "failed";
271
316
  op.failure = {
272
317
  stage: "build",
@@ -276,13 +321,45 @@ export class DeploymentEngine {
276
321
  image_name: image.name,
277
322
  first_image_name: first,
278
323
  desk_link: link,
324
+ ...(lines.length ? { log_tail: lines.slice(-20) } : {}),
325
+ ...(found.lines.length
326
+ ? {
327
+ diagnostics: found.lines,
328
+ diagnostics_found: found.found,
329
+ diagnostics_omitted: found.omitted,
330
+ }
331
+ : {}),
332
+ log_coverage: coverage,
333
+ log_lines_kept: lines.length,
334
+ cause: cause.kind,
335
+ cause_reason: cause.reason,
336
+ ...(lines.length
337
+ ? {
338
+ logs_hint: `get_logs with image_id ${image.id} shows up to 500 of the ${lines.length} kept lines.`,
339
+ }
340
+ : {}),
279
341
  };
280
- const log = await this.logs?.peek(image.id, "build", 20);
281
- if (log)
282
- op.failure.log_tail = log.lines;
283
- op.message = `Image build${service ? ` for ${service}` : ""} failed${first ? ` twice (${first}, then ${image.name} after re-checking the files)` : ` (${image.name})`}. ${log
284
- ? "The last build log lines are in failure.log_tail (get_logs with the image ID shows up to 500)."
285
- : `No build log was captured. To see the error, open the desk (${link}), rebuild ${dockerfile} from the UI and watch the live log.`} Fix the Dockerfile or source, then deploy again.`;
342
+ const tries = first
343
+ ? ` twice (${first}, then ${image.name} after re-checking the files)`
344
+ : ` (${image.name})`;
345
+ const covered = coverage === "complete"
346
+ ? "The MCP followed the build log to its end."
347
+ : coverage === "partial"
348
+ ? "The kept build log may be incomplete (the connection broke or the MCP joined late)."
349
+ : coverage === "live"
350
+ ? "The build log was still streaming when this was written; it may be incomplete."
351
+ : `No build log was captured: Constructor serves build logs only while the build runs. To see the error, open the desk (${link}), rebuild ${dockerfile} from the UI and watch the live log.`;
352
+ const why = cause.kind === "compile"
353
+ ? `Cause: the sources do not compile${attempt?.next?.startsWith("not rebuilt automatically") ? "; not rebuilt automatically, because an identical rebuild fails the same way" : ""}.`
354
+ : cause.kind === "transient"
355
+ ? `Likely cause: ${cause.reason}.`
356
+ : `Cause unknown: ${cause.reason}.`;
357
+ const errors = found.lines.length
358
+ ? ` failure.diagnostics has ${found.found} error${found.found === 1 ? "" : "s"} from the build log${found.omitted ? ` (${found.omitted} left out)` : ""}; failure.log_tail has its last lines.`
359
+ : lines.length
360
+ ? " The log shows no error the MCP recognises; failure.log_tail has its last lines."
361
+ : "";
362
+ op.message = `Image build${service ? ` for ${service}` : ""} failed${tries}. ${why}${errors} ${covered} Fix the Dockerfile or source, then repeat the call with deployment_id and this service with its build (builds that succeeded are kept).`;
286
363
  }
287
364
  /** Poll public URLs after start until they answer or readinessSeconds pass. */
288
365
  async ready(op, appId) {
@@ -864,6 +941,49 @@ export class DeploymentEngine {
864
941
  bad("Deployment ID not found.");
865
942
  return this.view(op, false);
866
943
  }
944
+ /**
945
+ * The project of an application, for an update that names only application_id. Earlier
946
+ * deployments on this machine are asked first, then every project with deployment on; the
947
+ * answer is used only when exactly one project has the application. Never by name.
948
+ */
949
+ async locateApplication(applicationId) {
950
+ const check = async (project) => {
951
+ try {
952
+ return (await this.apps(project)).some((a) => a.id === applicationId);
953
+ }
954
+ catch (err) {
955
+ if (err instanceof ToolError && err.code === "needs_key")
956
+ throw err;
957
+ return false;
958
+ }
959
+ };
960
+ const known = new Set();
961
+ for (const id of await this.store.ids()) {
962
+ const op = await this.store.load(id).catch(() => undefined);
963
+ if (op?.application_id === applicationId &&
964
+ op.project_id &&
965
+ op.endpoint === this.store.endpoint)
966
+ known.add(op.project_id);
967
+ }
968
+ for (const p of known)
969
+ if (await check(p))
970
+ return p;
971
+ const projects = (await this.rows("/projects")).filter((p) => p.deployment_enabled);
972
+ const found = [];
973
+ let next = 0;
974
+ await Promise.all(Array.from({ length: Math.min(6, projects.length) }, async () => {
975
+ while (next < projects.length) {
976
+ const p = projects[next++];
977
+ if (await check(p.id))
978
+ found.push({ id: p.id, name: p.name });
979
+ }
980
+ }));
981
+ if (found.length === 1)
982
+ return found[0].id;
983
+ bad(found.length
984
+ ? `Application ${applicationId} is in several projects (${found.map((p) => `${p.name}: ${p.id}`).join(", ")}). Repeat update_app with the right project_id.`
985
+ : `Application ${applicationId} was not found in any project with deployment on. Call get_deployment with no arguments: it lists every application with its project_id and service IDs. Then repeat update_app with project_id (or desk_url), application_id and the services.`);
986
+ }
867
987
  /** Map of every deployment-enabled project with its applications and services. */
868
988
  async overview() {
869
989
  const all = await this.rows("/projects");
@@ -886,6 +1006,11 @@ export class DeploymentEngine {
886
1006
  status: v.status,
887
1007
  image_id: v.image_id,
888
1008
  public_url: v.public_url,
1009
+ volumes: (v.volumes ?? []).map((x) => ({
1010
+ name: x.name,
1011
+ mount_point: x.mount_point,
1012
+ size_gb: x.size_gb,
1013
+ })),
889
1014
  ports: (v.ports ?? []).map((x) => ({
890
1015
  number: x.number,
891
1016
  public: !!x.expose_to_internet,
@@ -1062,9 +1187,21 @@ export class DeploymentEngine {
1062
1187
  };
1063
1188
  op.message = `${op.failure.stage} failed${op.failure.service ? ` for ${op.failure.service}` : ""}. Please check the logs in Constructor.`;
1064
1189
  const id = op.failure.service && op.services[op.failure.service];
1065
- const log = id && (await this.logs?.peek(id, "service", 20));
1190
+ const log = id && (await this.logs?.peek(id, "service", 200));
1066
1191
  if (log) {
1067
- op.failure = { ...op.failure, log_tail: log.lines };
1192
+ const found = diagnostics(log.lines);
1193
+ op.failure = {
1194
+ ...op.failure,
1195
+ log_tail: log.lines.slice(-20),
1196
+ ...(found.lines.length
1197
+ ? {
1198
+ diagnostics: found.lines,
1199
+ diagnostics_found: found.found,
1200
+ diagnostics_omitted: found.omitted,
1201
+ }
1202
+ : {}),
1203
+ logs_hint: `get_logs with service_id ${id} shows up to 500 lines.`,
1204
+ };
1068
1205
  op.message = `${op.failure.stage} failed for ${op.failure.service}. The last service log lines are in failure.log_tail (get_logs with the service ID shows up to 500).`;
1069
1206
  }
1070
1207
  }
@@ -1540,43 +1677,94 @@ export class DeploymentEngine {
1540
1677
  readiness_checks: names.length ? checks : undefined,
1541
1678
  message: op.message ??
1542
1679
  (readiness === "http_ok"
1543
- ? `Started; the public URL answers (${names.map((n) => `${n}: HTTP ${checks[n].status}`).join(", ")}).`
1680
+ ? `Started; the public URL answers (${names.map((n) => `${n} ${checks[n].url}: HTTP ${checks[n].status}`).join(", ")}).`
1544
1681
  : readiness === "no_public_url"
1545
1682
  ? "Started. No public port, so readiness was not checked over HTTP."
1546
1683
  : `Started, but ${failing.map((n) => `${n} (${checks[n].url}: ${checks[n].status === null ? "no answer" : `HTTP ${checks[n].status}`})`).join(", ")} did not answer within ${this.api.config.readinessSeconds ?? 60} s. ${silentHint(op.readiness.silent)}`),
1547
1684
  };
1548
1685
  }
1686
+ /**
1687
+ * The builds of this operation: each service's current image with its status, name and
1688
+ * age, plus what the kept build log shows (coverage, steps with their durations, the step
1689
+ * running now). Constructor reports only build_status; the rest comes from the log stamps.
1690
+ */
1691
+ async buildViews(op, all) {
1692
+ const views = [];
1693
+ for (const [service, id] of Object.entries(op.images)) {
1694
+ const im = all.find((x) => x.id === id);
1695
+ const log = await this.logs
1696
+ ?.peek(id, "build", 2000)
1697
+ .catch(() => undefined);
1698
+ const lines = log?.lines ?? [];
1699
+ const st = steps(lines);
1700
+ views.push({
1701
+ service,
1702
+ id,
1703
+ name: im?.name,
1704
+ build_status: im?.build_status ?? "unknown",
1705
+ ...(im?.created_at ? { requested_at: im.created_at } : {}),
1706
+ log: {
1707
+ coverage: !log
1708
+ ? "none"
1709
+ : log.complete
1710
+ ? "complete"
1711
+ : log.state === "live"
1712
+ ? "live"
1713
+ : "partial",
1714
+ lines_kept: lines.length,
1715
+ ...(log?.last_received_at
1716
+ ? { last_line_at: log.last_received_at }
1717
+ : {}),
1718
+ ...(st.length ? { steps: st } : {}),
1719
+ },
1720
+ });
1721
+ }
1722
+ return views;
1723
+ }
1549
1724
  async view(op, cache = true) {
1550
1725
  let services = [];
1551
1726
  let images = [];
1552
1727
  try {
1553
- if (op.project_id && Object.keys(op.images).length) {
1554
- const all = await this.images(op.project_id);
1555
- images = Object.entries(op.images).map(([service, id]) => ({
1556
- service,
1557
- id,
1558
- build_status: all.find((x) => x.id === id)?.build_status ?? "unknown",
1559
- }));
1560
- }
1728
+ if (op.project_id && Object.keys(op.images).length)
1729
+ images = await this.buildViews(op, await this.images(op.project_id));
1561
1730
  if (op.application_id && op.project_id) {
1562
1731
  const a = await this.app(op.project_id, op.application_id);
1563
- services = a.services.map((s) => this.observed(publicService(s, op.project_id, op.application_id)));
1732
+ services = a.services.map((s) => {
1733
+ const v = this.observed(publicService(s, op.project_id, op.application_id));
1734
+ const failed = op.failure?.service === s.name;
1735
+ const attempted = (failed && op.failure?.image_id) || op.images[s.name];
1736
+ // Whether the service runs what this operation built: never assume it does.
1737
+ return attempted
1738
+ ? {
1739
+ ...v,
1740
+ attempted_image_id: attempted,
1741
+ runs_attempted_image: v.image_id === attempted,
1742
+ }
1743
+ : v;
1744
+ });
1564
1745
  }
1565
1746
  }
1566
1747
  catch (err) {
1567
1748
  if (!(err instanceof ToolError))
1568
1749
  throw err;
1569
1750
  }
1751
+ const end = terminal.has(op.status)
1752
+ ? Date.parse(op.updated_at)
1753
+ : Date.now();
1570
1754
  const result = {
1571
1755
  deployment_id: op.id,
1572
1756
  operation: op.kind,
1573
1757
  status: op.status,
1574
1758
  project_id: op.project_id,
1575
1759
  application_id: op.application_id,
1760
+ application_name: op.input?.application_name,
1761
+ created_at: op.created_at,
1762
+ elapsed_seconds: Math.max(0, Math.round((end - Date.parse(op.created_at)) / 1000)),
1576
1763
  images,
1577
1764
  services,
1578
1765
  failure: op.failure,
1579
1766
  build_retried: op.retried,
1767
+ ...(op.attempts ? { build_attempts: op.attempts } : {}),
1580
1768
  replaced: op.replaced,
1581
1769
  volumes_to_wipe: op.volumes_to_wipe,
1582
1770
  ...this.readinessView(op),
@@ -1591,7 +1779,7 @@ export class DeploymentEngine {
1591
1779
  }
1592
1780
  : {}),
1593
1781
  next_action: op.status === "failed"
1594
- ? "Tell the user which stage/service failed and pass on the message. failure.log_tail has the last log lines when the MCP captured them; get_logs shows more. Do not use browser or other tools to investigate."
1782
+ ? "Tell the user which stage/service failed and pass on the message. The text lists the errors found in the log (failure.diagnostics) or its last lines (failure.log_tail), with how much of the log was captured; get_logs with the image or service ID shows more. Do not use browser or other tools to investigate."
1595
1783
  : terminal.has(op.status)
1596
1784
  ? undefined
1597
1785
  : op.status === "needs_key"
package/dist/desk.d.ts CHANGED
@@ -11,6 +11,12 @@ export interface LocalDesk {
11
11
  /** The Constructor the desk belongs to. */
12
12
  server?: string;
13
13
  }
14
+ /**
15
+ * What Constructor sets in a desk that the MCP reads: the desk, its server, and the access key
16
+ * the desk provides. Agents that start the MCP with a reduced environment (Codex) are told to
17
+ * pass these on.
18
+ */
19
+ export declare const DESK_ENV: string[];
14
20
  export declare function localDeskFromEnv(env: NodeJS.ProcessEnv, origin: (link: string) => string): LocalDesk | undefined;
15
21
  /**
16
22
  * Disk path ("/a/Dockerfile") of a local path inside the desk's project folder, or undefined
package/dist/desk.js CHANGED
@@ -2,6 +2,20 @@ import { realpathSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
  const ID = /^[a-zA-Z0-9_-]{4,128}$/;
5
+ /**
6
+ * What Constructor sets in a desk that the MCP reads: the desk, its server, and the access key
7
+ * the desk provides. Agents that start the MCP with a reduced environment (Codex) are told to
8
+ * pass these on.
9
+ */
10
+ export const DESK_ENV = [
11
+ "ROLOS_PROJECT_ID",
12
+ "ROLOS_DESK_ID",
13
+ "ROLOS_API_SERVER",
14
+ "RESEARCH_PROJECT_ID",
15
+ "RESEARCH_DESK_ID",
16
+ "RESEARCH_API_SERVER",
17
+ "RESEARCH_ACCESS_KEY",
18
+ ];
5
19
  export function localDeskFromEnv(env, origin) {
6
20
  if (["0", "false", "off"].includes((env.CONSTRUCTOR_LOCAL_DESK ?? "").toLowerCase()))
7
21
  return undefined;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Masks what looks like a secret in a log line: access keys, bearer tokens, credentials in
3
+ * URLs and NAME=value pairs whose name says token, secret, password or key. Applied to every
4
+ * line the MCP keeps, so neither tool output nor the files in the state directory carry them.
5
+ */
6
+ export declare function redact(line: string): string;
7
+ /** The time of a kept line, if stamped. */
8
+ export declare const stampOf: (line: string) => string | undefined;
9
+ /** A kept line without its time stamp. */
10
+ export declare const text: (line: string) => string;
11
+ export interface Diagnostics {
12
+ /** Error excerpts, oldest first, at most `blocks` blocks and `chars` characters. */
13
+ lines: string[];
14
+ /** Error blocks found, and how many were left out to keep the excerpt short. */
15
+ found: number;
16
+ omitted: number;
17
+ }
18
+ /**
19
+ * Every error the log shows, not only the last lines: compiler errors with their location
20
+ * lines, failed Dockerfile steps, tracebacks. Bounded, so a long log cannot flood the reply;
21
+ * when blocks are left out, the first and the last ones are kept (the first error is usually
22
+ * the cause, the last says which step failed).
23
+ */
24
+ export declare function diagnostics(lines: string[], { blocks, perBlock, chars }?: {
25
+ blocks?: number | undefined;
26
+ chars?: number | undefined;
27
+ perBlock?: number | undefined;
28
+ }): Diagnostics;
29
+ /**
30
+ * Why a build failed, as far as its log tells:
31
+ * - compile: the sources do not build (compiler errors). A rebuild of the same sources fails
32
+ * the same way, so the MCP does not rebuild on its own.
33
+ * - transient: pulling, network or builder trouble, or files that had not reached the
34
+ * builder yet. One automatic rebuild may help.
35
+ * - unknown: no log, or nothing in it the MCP recognises.
36
+ */
37
+ export type FailureKind = "compile" | "transient" | "unknown";
38
+ export declare function classify(lines: string[]): {
39
+ kind: FailureKind;
40
+ reason: string;
41
+ };
42
+ export interface Step {
43
+ step: string;
44
+ at: string;
45
+ /** Seconds until the next step started, or until the last line for the last step. */
46
+ seconds: number;
47
+ /** The last step ran until the log ended (its duration may be cut short). */
48
+ last?: boolean;
49
+ }
50
+ /**
51
+ * Build steps and how long each took, from the stamps of the kept lines: "STEP 2/9: RUN …"
52
+ * (buildah), "Step 2/9 : RUN …" (docker) and "#7 [2/9] RUN …" (BuildKit). An estimate:
53
+ * Constructor reports no build stages, and a step's time includes pulling its base image.
54
+ */
55
+ export declare function steps(lines: string[], max?: number): Step[];
56
+ /** "5m 11s", "42s", "1h 3m". */
57
+ export declare function duration(seconds: number): string;
@@ -0,0 +1,183 @@
1
+ // What a build or service log says, for an agent that reads only text: the errors in it, how
2
+ // long each build step took, and whether a rebuild could help. Everything here works on the
3
+ // lines the MCP kept (LogFollower); Constructor itself reports no stages, timings or causes.
4
+ const STAMP = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z) ?/;
5
+ /**
6
+ * Masks what looks like a secret in a log line: access keys, bearer tokens, credentials in
7
+ * URLs and NAME=value pairs whose name says token, secret, password or key. Applied to every
8
+ * line the MCP keeps, so neither tool output nor the files in the state directory carry them.
9
+ */
10
+ export function redact(line) {
11
+ return line
12
+ .replace(/\brk-[A-Za-z0-9_-]{6,}/g, "rk-…")
13
+ .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 …")
14
+ .replace(/(:\/\/[^\s/:@]+):[^\s/@]+@/g, "$1:…@")
15
+ .replace(/\b([A-Za-z0-9_.-]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PWD|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIALS?)[A-Za-z0-9_.-]*)(\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, "$1$2…");
16
+ }
17
+ /** The time of a kept line, if stamped. */
18
+ export const stampOf = (line) => STAMP.exec(line)?.[1];
19
+ /** A kept line without its time stamp. */
20
+ export const text = (line) => line.replace(STAMP, "").replace(/^#\d+ \d+(\.\d+)? /, "");
21
+ /** Where an error block starts; the lines after it, up to a blank one or the next block, belong to it. */
22
+ const START = [
23
+ /^error(\[E\d+\])?: /, // rustc, cargo
24
+ /^error: could not compile/,
25
+ /\berror TS\d+:/, // tsc
26
+ /^(npm (ERR!|error)|ERR_PNPM_|error Command failed|yarn error)/i,
27
+ /^Traceback \(most recent call last\):/,
28
+ /^(SyntaxError|TypeError|ReferenceError|ModuleNotFoundError|ImportError|NameError): /,
29
+ /^[\w./-]+\.(go|py|ts|tsx|js|java|kt|c|cc|cpp|h|cs|rb|php):\d+(:\d+)?: (fatal )?error/i,
30
+ /^\S+\.java:\d+: error:/,
31
+ /\b(FATAL|ERROR)\b[: ]/,
32
+ /\b(failed to solve|did not complete successfully|returned a non-zero code|exit code: [1-9]\d*|exit status [1-9]\d*|executor failed running)/i,
33
+ /^Error: /,
34
+ /^(COPY|ADD) failed|failed to compute cache key|no such file or directory/i,
35
+ ];
36
+ /** Lines that continue a block: compiler context, code frames and notes. */
37
+ const CONTINUE = /^(\s+|-->|\s*\||\s*= (note|help)|\s*\^|\s*at\s|\d+ \|)/;
38
+ const NOISE = /^(warning(\[\w+\])?: |\s*Compiling |\s*Downloaded |\s*Downloading )/;
39
+ /**
40
+ * Every error the log shows, not only the last lines: compiler errors with their location
41
+ * lines, failed Dockerfile steps, tracebacks. Bounded, so a long log cannot flood the reply;
42
+ * when blocks are left out, the first and the last ones are kept (the first error is usually
43
+ * the cause, the last says which step failed).
44
+ */
45
+ export function diagnostics(lines, { blocks = 12, perBlock = 8, chars = 4000 } = {}) {
46
+ const all = [];
47
+ let current;
48
+ const seen = new Set();
49
+ for (const raw of lines) {
50
+ const line = text(raw).trimEnd();
51
+ if (!line.trim()) {
52
+ current = undefined;
53
+ continue;
54
+ }
55
+ if (NOISE.test(line)) {
56
+ current = undefined;
57
+ continue;
58
+ }
59
+ if (START.some((r) => r.test(line))) {
60
+ const key = line.replace(/\s+/g, " ");
61
+ if (seen.has(key)) {
62
+ current = undefined;
63
+ continue;
64
+ }
65
+ seen.add(key);
66
+ current = [line];
67
+ all.push(current);
68
+ continue;
69
+ }
70
+ if (current && CONTINUE.test(line) && current.length < perBlock)
71
+ current.push(line);
72
+ else if (current && !CONTINUE.test(line))
73
+ current = undefined;
74
+ }
75
+ // Keep the first blocks and the last two when there are too many.
76
+ let kept = all;
77
+ if (all.length > blocks)
78
+ kept = [...all.slice(0, blocks - 2), ...all.slice(-2)];
79
+ const out = [];
80
+ let size = 0;
81
+ let used = 0;
82
+ for (const block of kept) {
83
+ const cost = block.reduce((n, l) => n + l.length + 1, 0);
84
+ if (size + cost > chars && used)
85
+ break;
86
+ out.push(...block.map((l) => (l.length > 400 ? l.slice(0, 400) + "…" : l)));
87
+ size += cost;
88
+ used++;
89
+ }
90
+ return { lines: out, found: all.length, omitted: all.length - used };
91
+ }
92
+ const TRANSIENT = [
93
+ /spurious network error|failed to (download|fetch)|could ?n[o']t resolve host|ETIMEDOUT|ECONNRESET|EAI_AGAIN/i,
94
+ /i\/o timeout|connection (reset|refused)|TLS handshake timeout|context deadline exceeded|temporary failure in name resolution|no such host/i,
95
+ /toomanyrequests|rate limit|\b50[234]\b.*(Service Unavailable|Bad Gateway|Gateway Time-?out)|unexpected EOF/i,
96
+ /registries\.conf|error (pulling|initializing) image|failed to pull|pull access denied|manifest unknown|error creating overlay mount|no space left on device/i,
97
+ /(COPY|ADD) failed|failed to compute cache key|"\/[^"]+": not found|stat .*: no such file or directory/i,
98
+ ];
99
+ const COMPILE = [
100
+ /^error\[E\d+\]: /, // rustc; a bare "error:" is also cargo's network trouble
101
+ /\berror TS\d+:/,
102
+ /^[\w./-]+\.(go|java|kt|c|cc|cpp|h|cs|ts|tsx|js):\d+(:\d+)?: (fatal )?error/i,
103
+ /^\S+\.java:\d+: error:/,
104
+ /^(SyntaxError|TypeError|ReferenceError): /,
105
+ /Failed to compile|Build failed with \d+ errors?|error: could not compile/i,
106
+ ];
107
+ export function classify(lines) {
108
+ if (!lines.length)
109
+ return {
110
+ kind: "unknown",
111
+ reason: "no build log was captured, so the cause is unknown",
112
+ };
113
+ const plain = lines.map(text);
114
+ const hit = (patterns) => plain.find((l) => patterns.some((r) => r.test(l)));
115
+ const compile = hit(COMPILE);
116
+ if (compile)
117
+ return {
118
+ kind: "compile",
119
+ reason: `the log shows a compile error (${compile.trim().slice(0, 160)})`,
120
+ };
121
+ const transient = hit(TRANSIENT);
122
+ if (transient)
123
+ return {
124
+ kind: "transient",
125
+ reason: `the log points to a pull, network, builder or file-transfer problem (${transient.trim().slice(0, 160)})`,
126
+ };
127
+ return {
128
+ kind: "unknown",
129
+ reason: plain.some((l) => START.some((r) => r.test(l)))
130
+ ? "the log shows errors, but not whether a rebuild could help"
131
+ : "the log shows no error the MCP recognises",
132
+ };
133
+ }
134
+ /**
135
+ * Build steps and how long each took, from the stamps of the kept lines: "STEP 2/9: RUN …"
136
+ * (buildah), "Step 2/9 : RUN …" (docker) and "#7 [2/9] RUN …" (BuildKit). An estimate:
137
+ * Constructor reports no build stages, and a step's time includes pulling its base image.
138
+ */
139
+ export function steps(lines, max = 15) {
140
+ const found = [];
141
+ const header = /^(STEP \d+\/\d+: .*|Step \d+\/\d+ : .*|#\d+ \[(?:[\w-]+ )?\d+\/\d+\] .*)$/;
142
+ let lastStamp;
143
+ for (const raw of lines) {
144
+ const at = stampOf(raw);
145
+ if (at)
146
+ lastStamp = at;
147
+ const line = text(raw).trim();
148
+ if (!at || !header.test(line))
149
+ continue;
150
+ const step = line.replace(/^#\d+ /, "");
151
+ if (found.some((f) => f.step === step))
152
+ continue;
153
+ found.push({
154
+ step: step.length > 120 ? step.slice(0, 120) + "…" : step,
155
+ at,
156
+ });
157
+ }
158
+ const out = found.map((f, n) => {
159
+ const end = found[n + 1]?.at ?? lastStamp ?? f.at;
160
+ return {
161
+ ...f,
162
+ seconds: Math.max(0, Math.round((Date.parse(end) - Date.parse(f.at)) / 1000)),
163
+ ...(n === found.length - 1 ? { last: true } : {}),
164
+ };
165
+ });
166
+ // The longest steps matter most when there are many.
167
+ if (out.length <= max)
168
+ return out;
169
+ const keep = new Set([...out]
170
+ .sort((a, b) => b.seconds - a.seconds)
171
+ .slice(0, max)
172
+ .map((s) => s.at + s.step));
173
+ return out.filter((s) => keep.has(s.at + s.step));
174
+ }
175
+ /** "5m 11s", "42s", "1h 3m". */
176
+ export function duration(seconds) {
177
+ const s = Math.max(0, Math.round(seconds));
178
+ if (s < 60)
179
+ return `${s}s`;
180
+ if (s < 3600)
181
+ return `${Math.floor(s / 60)}m ${s % 60}s`;
182
+ return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
183
+ }