@jmanuelcorral/bond-app 0.3.0 → 0.3.1

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.
@@ -99,6 +99,33 @@ export function startCommand() {
99
99
  return Array.isArray(CONFIG.start) && CONFIG.start.length ? CONFIG.start : ["bond-app", "start"];
100
100
  }
101
101
 
102
+ /**
103
+ * `bond-app update` with the same bond-app that starts the orchestrator (CONFIG.start up to
104
+ * «start»), in a shell that stays open so the person reads how it went.
105
+ */
106
+ export function updateCommand() {
107
+ return bondAppCommand(["update"], "bond-app update ha terminado: ya puedes cerrar esta pestaña.");
108
+ }
109
+
110
+ /**
111
+ * `bond-app diagnose` (with --issue: it shows what it will send and asks before opening the
112
+ * issue), with the same data dir the orchestrator uses.
113
+ */
114
+ export function diagnoseCommand(issue = false) {
115
+ const start = startCommand();
116
+ const d = start.indexOf("--data-dir");
117
+ const dataDir = d >= 0 && start[d + 1] ? ["--data-dir", start[d + 1]] : [];
118
+ return bondAppCommand(["diagnose", ...dataDir, ...(issue ? ["--issue"] : [])], "Listo: ya puedes cerrar esta pestaña.");
119
+ }
120
+
121
+ /** A bond-app subcommand with the bond-app that starts the orchestrator, in a shell that stays open. */
122
+ function bondAppCommand(args, done) {
123
+ const start = startCommand();
124
+ const i = start.indexOf("start");
125
+ const cmd = [...(i > 0 ? start.slice(0, i) : ["bond-app"]), ...args];
126
+ return ["sh", "-c", `"$@"; echo; echo "${done}"; exec sh`, `bond-app-${args[0]}`, ...cmd];
127
+ }
128
+
102
129
  /** The API's base URL, for messages. */
103
130
  export function apiUrl() {
104
131
  return CONFIG.api;
@@ -531,6 +531,9 @@ export function initTabToClose(space, paneList, machine, agentAddrs = [], leader
531
531
 
532
532
  /** Is this row the run's orchestrator (gru / the hub leader)? */
533
533
  export function isLeaderRow(row) {
534
+ // A delegate (another agent's terminal in the run, e.g. gru's kevin) is never the leader,
535
+ // even working at the hub's root.
536
+ if (row?.isDelegate) return false;
534
537
  const pane = String(row?.pane ?? row?.agent?.pane ?? "");
535
538
  return row?.repo === "orquestador" || row?.repoLabel === "orquestador" || row?.agent?.name === "hub leader"
536
539
  || row?.path === "/workspace/hub" || pane.endsWith("/t1");
@@ -99,6 +99,33 @@ export function startCommand() {
99
99
  return Array.isArray(CONFIG.start) && CONFIG.start.length ? CONFIG.start : ["bond-app", "start"];
100
100
  }
101
101
 
102
+ /**
103
+ * `bond-app update` with the same bond-app that starts the orchestrator (CONFIG.start up to
104
+ * «start»), in a shell that stays open so the person reads how it went.
105
+ */
106
+ export function updateCommand() {
107
+ return bondAppCommand(["update"], "bond-app update ha terminado: ya puedes cerrar esta pestaña.");
108
+ }
109
+
110
+ /**
111
+ * `bond-app diagnose` (with --issue: it shows what it will send and asks before opening the
112
+ * issue), with the same data dir the orchestrator uses.
113
+ */
114
+ export function diagnoseCommand(issue = false) {
115
+ const start = startCommand();
116
+ const d = start.indexOf("--data-dir");
117
+ const dataDir = d >= 0 && start[d + 1] ? ["--data-dir", start[d + 1]] : [];
118
+ return bondAppCommand(["diagnose", ...dataDir, ...(issue ? ["--issue"] : [])], "Listo: ya puedes cerrar esta pestaña.");
119
+ }
120
+
121
+ /** A bond-app subcommand with the bond-app that starts the orchestrator, in a shell that stays open. */
122
+ function bondAppCommand(args, done) {
123
+ const start = startCommand();
124
+ const i = start.indexOf("start");
125
+ const cmd = [...(i > 0 ? start.slice(0, i) : ["bond-app"]), ...args];
126
+ return ["sh", "-c", `"$@"; echo; echo "${done}"; exec sh`, `bond-app-${args[0]}`, ...cmd];
127
+ }
128
+
102
129
  /** The API's base URL, for messages. */
103
130
  export function apiUrl() {
104
131
  return CONFIG.api;
@@ -99,6 +99,33 @@ export function startCommand() {
99
99
  return Array.isArray(CONFIG.start) && CONFIG.start.length ? CONFIG.start : ["bond-app", "start"];
100
100
  }
101
101
 
102
+ /**
103
+ * `bond-app update` with the same bond-app that starts the orchestrator (CONFIG.start up to
104
+ * «start»), in a shell that stays open so the person reads how it went.
105
+ */
106
+ export function updateCommand() {
107
+ return bondAppCommand(["update"], "bond-app update ha terminado: ya puedes cerrar esta pestaña.");
108
+ }
109
+
110
+ /**
111
+ * `bond-app diagnose` (with --issue: it shows what it will send and asks before opening the
112
+ * issue), with the same data dir the orchestrator uses.
113
+ */
114
+ export function diagnoseCommand(issue = false) {
115
+ const start = startCommand();
116
+ const d = start.indexOf("--data-dir");
117
+ const dataDir = d >= 0 && start[d + 1] ? ["--data-dir", start[d + 1]] : [];
118
+ return bondAppCommand(["diagnose", ...dataDir, ...(issue ? ["--issue"] : [])], "Listo: ya puedes cerrar esta pestaña.");
119
+ }
120
+
121
+ /** A bond-app subcommand with the bond-app that starts the orchestrator, in a shell that stays open. */
122
+ function bondAppCommand(args, done) {
123
+ const start = startCommand();
124
+ const i = start.indexOf("start");
125
+ const cmd = [...(i > 0 ? start.slice(0, i) : ["bond-app"]), ...args];
126
+ return ["sh", "-c", `"$@"; echo; echo "${done}"; exec sh`, `bond-app-${args[0]}`, ...cmd];
127
+ }
128
+
102
129
  /** The API's base URL, for messages. */
103
130
  export function apiUrl() {
104
131
  return CONFIG.api;
@@ -33,7 +33,7 @@
33
33
  import { View, div, svg, image } from "gpui-kit";
34
34
  import { v_flex, h_flex, InputState, Input, TextareaState, Textarea } from "gpui-base";
35
35
  import { props, theme, openOverlay, closeOverlay, notify, shared, setShared, exec, run } from "herdr";
36
- import { api, diagnose, health, resetToken, startCommand, apiUrl } from "./api.js";
36
+ import { api, diagnose, health, resetToken, startCommand, updateCommand, diagnoseCommand, apiUrl } from "./api.js";
37
37
  import { UI, stateColor } from "./brand.js";
38
38
  import { buildPiModelsDoc, validateConfigJson, normalizeBaseUrl, parseModelIds, suggestSuggestionModel, suggestDefaultModel, toggleModelLine } from "./pi-models.js";
39
39
 
@@ -335,6 +335,7 @@ export default class BondSettings extends View {
335
335
  if (!this.doctorLoaded) {
336
336
  this.doctorLoaded = true;
337
337
  this.loadDoctor(cx);
338
+ this.loadUpdates(cx);
338
339
  }
339
340
  if (!this.loopLoaded) {
340
341
  this.loopLoaded = true;
@@ -384,6 +385,65 @@ export default class BondSettings extends View {
384
385
  });
385
386
  }
386
387
 
388
+ /** «Hay versión nueva»: what the orchestrator learnt from npm; «Comprobar ahora» asks again. */
389
+ loadUpdates(cx, force = false) {
390
+ this.updatesBusy = force;
391
+ cx.spawn(async (cx) => {
392
+ try {
393
+ this.updates = await api("/system/updates", force ? { method: "POST", body: {} } : undefined);
394
+ } catch {}
395
+ this.updatesBusy = false;
396
+ cx.notify();
397
+ });
398
+ }
399
+
400
+ /** `bond-app update` in a space of its own on this computer: bond-app, bond, mods and service. */
401
+ runUpdate() {
402
+ try {
403
+ run("space.new", { name: "bond-app update", machine: "", argv: updateCommand() });
404
+ notify({ title: "Actualizando bond-app", body: "Mira el espacio «bond-app update»: al terminar, el orquestador se reinicia.", level: "info" });
405
+ } catch (e) {
406
+ this.error = `Actualizar: ${String(e?.message ?? e)}`;
407
+ }
408
+ }
409
+
410
+ /** «Exportar diagnóstico» / «Abrir issue»: bond-app diagnose in a space of its own (works with the orchestrator down). */
411
+ runDiagnose(issue) {
412
+ try {
413
+ run("space.new", { name: issue ? "bond-app issue" : "bond-app diagnose", machine: "", argv: diagnoseCommand(issue) });
414
+ } catch (e) {
415
+ this.error = `Diagnóstico: ${String(e?.message ?? e)}`;
416
+ }
417
+ }
418
+
419
+ diagnoseBlock() {
420
+ const t = theme();
421
+ return v_flex().id("diagnose-block").gap(8)
422
+ .child(h_flex().gap(8).items_center()
423
+ .child(div().flex_1().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Informar de un problema"))
424
+ .child(this.button("diagnose-zip", "Exportar diagnóstico", false, () => this.runDiagnose(false)))
425
+ .child(this.button("diagnose-issue", "Abrir issue en GitHub", false, () => this.runDiagnose(true))))
426
+ .child(this.note("Un zip con los logs del orquestador y de herdr-app, el estado de la instalación, las versiones, el servicio y los últimos runs, sin tokens ni credenciales. «Abrir issue» te enseña lo que va a enviar y te pregunta antes; el zip lo adjuntas tú a la issue."));
427
+ }
428
+
429
+ versionsBlock() {
430
+ const t = theme();
431
+ const u = this.updates;
432
+ const row = (id, name, p) => h_flex().id(id).gap(8).items_center()
433
+ .child(div().w(90).flex_none().text_size(UI.text.small).font_semibold().text_color(t.foreground).child(name))
434
+ .child(div().flex_1().text_size(UI.text.small).text_color(p?.update ? this.tone(t, "waiting") : t.muted)
435
+ .child(p ? `${p.installed ?? "?"}${p.latest ? (p.update ? ` → ${p.latest} disponible` : " (la última)") : ""}` : "…"));
436
+ return v_flex().id("versions-block").gap(8)
437
+ .child(h_flex().gap(8).items_center()
438
+ .child(div().flex_1().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Versiones"))
439
+ .child(this.button("updates-check", this.updatesBusy ? "Comprobando…" : "Comprobar ahora", false, (cx) => this.loadUpdates(cx, true)))
440
+ .when(Boolean(u?.available), (el) => el.child(this.button("updates-run", "Actualizar", true, () => this.runUpdate()))))
441
+ .child(row("version-bond-app", "bond-app", u?.bond_app))
442
+ .child(row("version-bond", "bond", u?.bond))
443
+ .when(Boolean(u?.error), (el) => el.child(this.note(`No se pudo consultar npm: ${u.error}`)))
444
+ .child(this.note("Se comprueba al arrancar el orquestador y una vez al día. «Actualizar» ejecuta bond-app update (bond-app, bond, mods y servicio); si la imagen del runner queda vieja, te avisa para reconstruirla."));
445
+ }
446
+
387
447
  loadDoctor(cx) {
388
448
  if (this.doctorBusy) return;
389
449
  this.doctorBusy = true;
@@ -1370,7 +1430,9 @@ export default class BondSettings extends View {
1370
1430
  .child(row("API", apiUrl()))
1371
1431
  .child(row("Asistente", s ? (s.setup_done ? "terminado" : "sin terminar") : "—"))
1372
1432
  .child(row("Credenciales", "En el orquestador, 0600; llegan a cada run por stdin.")))
1433
+ .child(this.versionsBlock())
1373
1434
  .child(this.doctorBlock())
1435
+ .child(this.diagnoseBlock())
1374
1436
  .child(this.loopBlock())
1375
1437
  .child(this.favoritesBlock())
1376
1438
  .child(h_flex().child(this.button("wiz-reopen", "Abrir el asistente", false, (cx) => {
@@ -1425,7 +1487,7 @@ export default class BondSettings extends View {
1425
1487
  return v_flex().id("doctor-block").gap(8)
1426
1488
  .child(h_flex().gap(8).items_center()
1427
1489
  .child(div().flex_1().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Estado de la instalación"))
1428
- .child(this.button("doctor-refresh", this.doctorBusy ? "Actualizando…" : "Actualizar", false, (cx) => this.loadDoctor(cx))))
1490
+ .child(this.button("doctor-refresh", this.doctorBusy ? "Comprobando…" : "Volver a comprobar", false, (cx) => this.loadDoctor(cx))))
1429
1491
  .when(Boolean(summaryText), (el) => el.child(div().id("doctor-summary").text_size(UI.text.small).text_color(t.muted).child(summaryText)))
1430
1492
  .when(Boolean(this.doctorError), (el) => el.child(div().id("doctor-error").text_size(UI.text.small).text_color(t.blocked).child(this.doctorError)))
1431
1493
  .when(!d && !this.doctorError, (el) => el.child(this.note(this.doctorBusy ? "Comprobando…" : "Sin datos de diagnóstico.")))
@@ -99,6 +99,33 @@ export function startCommand() {
99
99
  return Array.isArray(CONFIG.start) && CONFIG.start.length ? CONFIG.start : ["bond-app", "start"];
100
100
  }
101
101
 
102
+ /**
103
+ * `bond-app update` with the same bond-app that starts the orchestrator (CONFIG.start up to
104
+ * «start»), in a shell that stays open so the person reads how it went.
105
+ */
106
+ export function updateCommand() {
107
+ return bondAppCommand(["update"], "bond-app update ha terminado: ya puedes cerrar esta pestaña.");
108
+ }
109
+
110
+ /**
111
+ * `bond-app diagnose` (with --issue: it shows what it will send and asks before opening the
112
+ * issue), with the same data dir the orchestrator uses.
113
+ */
114
+ export function diagnoseCommand(issue = false) {
115
+ const start = startCommand();
116
+ const d = start.indexOf("--data-dir");
117
+ const dataDir = d >= 0 && start[d + 1] ? ["--data-dir", start[d + 1]] : [];
118
+ return bondAppCommand(["diagnose", ...dataDir, ...(issue ? ["--issue"] : [])], "Listo: ya puedes cerrar esta pestaña.");
119
+ }
120
+
121
+ /** A bond-app subcommand with the bond-app that starts the orchestrator, in a shell that stays open. */
122
+ function bondAppCommand(args, done) {
123
+ const start = startCommand();
124
+ const i = start.indexOf("start");
125
+ const cmd = [...(i > 0 ? start.slice(0, i) : ["bond-app"]), ...args];
126
+ return ["sh", "-c", `"$@"; echo; echo "${done}"; exec sh`, `bond-app-${args[0]}`, ...cmd];
127
+ }
128
+
102
129
  /** The API's base URL, for messages. */
103
130
  export function apiUrl() {
104
131
  return CONFIG.api;
@@ -9,9 +9,9 @@
9
9
  import { View, div } from "gpui-kit";
10
10
  import { h_flex } from "gpui-base";
11
11
  import { theme, updates, openOverlay, run, exec, checking } from "herdr";
12
- import { api, health } from "./api.js";
12
+ import { api, health, updateCommand } from "./api.js";
13
13
  import { UI, settingsOverlay, stateColor } from "./brand.js";
14
- import { statusSummary, compareVersions, MIN_HERDR_APP, MIN_HC, POLL_MS } from "./model.js";
14
+ import { statusSummary, updateNotice, compareVersions, MIN_HERDR_APP, MIN_HC, POLL_MS } from "./model.js";
15
15
 
16
16
  export default class BondStatus extends View {
17
17
  init(_props, cx) {
@@ -39,10 +39,12 @@ export default class BondStatus extends View {
39
39
  await health();
40
40
  next.api = { ok: true };
41
41
  try {
42
- const [github, runs, azure, jira] = await Promise.all([
42
+ const [github, runs, azure, jira, updates] = await Promise.all([
43
43
  api("/settings/github"), api("/runs"),
44
44
  api("/settings/azure-devops").catch(() => null), api("/settings/jira").catch(() => null),
45
+ api("/system/updates").catch(() => null),
45
46
  ]);
47
+ next.updates = updates;
46
48
  next.github = github ?? { configured: false };
47
49
  next.runs = runs ?? [];
48
50
  next.azure = azure;
@@ -60,6 +62,13 @@ export default class BondStatus extends View {
60
62
  });
61
63
  }
62
64
 
65
+ /** «Actualizar»: `bond-app update` in a space of its own on this computer (never a run's). */
66
+ runUpdate() {
67
+ try {
68
+ run("space.new", { name: "bond-app update", machine: "", argv: updateCommand() });
69
+ } catch {}
70
+ }
71
+
63
72
  openSettings(section) {
64
73
  openOverlay(settingsOverlay(section ? { section } : {}));
65
74
  }
@@ -77,6 +86,7 @@ export default class BondStatus extends View {
77
86
  const t = theme();
78
87
  const u = updates();
79
88
  const s = statusSummary(this.state, { app: u?.app?.version ?? null, core: u?.core?.version ?? null, appReady: u?.app?.ready ?? null, appInstalled: this.appInstalled });
89
+ const upd = updateNotice(this.state.updates);
80
90
  const tone = { ok: stateColor(t, "running"), warn: t.bond_blocked ?? t.blocked, bad: t.blocked, unknown: t.dim };
81
91
  const version = (name, have, min) => {
82
92
  const ok = have && compareVersions(have, min) >= 0;
@@ -90,6 +100,7 @@ export default class BondStatus extends View {
90
100
  .when(Boolean(s.jira), (el) => el.child(this.item("st-jira", tone[s.jira.tone], s.jira.text, null, () => this.openSettings("jira"))))
91
101
  .child(this.item("st-runs", s.runs.active > 0 ? stateColor(t, "running") : t.dim, s.runs.text, null, null))
92
102
  .child(div().flex_1())
103
+ .when(Boolean(upd), (el) => el.child(this.item("st-bond-update", t.accent, upd.text, t.accent, () => this.runUpdate())))
93
104
  .when(Boolean(s.versions.appNewer), (el) => el.child(this.item("st-app-update", t.accent,
94
105
  s.versions.appRestart ? `herdr-app ${s.versions.appNewer}: reiniciar` : `herdr-app ${s.versions.appNewer} instalado: reinicia la app`,
95
106
  t.accent, s.versions.appRestart ? () => run("app.update") : null)))
@@ -91,3 +91,16 @@ export function statusSummary(state, versions) {
91
91
  },
92
92
  };
93
93
  }
94
+
95
+ /**
96
+ * «Hay versión nueva» in the status bar: what is newer (bond-app first, then bond), from the
97
+ * orchestrator's GET /system/updates. Null when everything is up to date or not known yet.
98
+ */
99
+ export function updateNotice(u) {
100
+ if (!u || !u.available) return null;
101
+ const parts = [];
102
+ if (u.bond_app?.update) parts.push(`bond-app ${u.bond_app.latest}`);
103
+ if (u.bond?.update) parts.push(`bond ${u.bond.latest}`);
104
+ if (!parts.length) return null;
105
+ return { text: `${parts.join(" y ")} disponible${parts.length > 1 ? "s" : ""}: actualizar` };
106
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jmanuelcorral/bond-app",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Local orchestrator and hub-container runner for multi-agent tickets",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/src/cli.ts CHANGED
@@ -18,6 +18,7 @@ import type { ServerHooks } from './server/app.ts';
18
18
  import { MIN_HC_VERSION, MIN_HERDR_APP_VERSION } from './runner/hc-client.ts';
19
19
  import { install, parseInstallArgs, removeLauncher } from '../scripts/app-install.ts';
20
20
  import { runDoctor, type DoctorDeps, type DoctorReport } from './core/doctor.ts';
21
+ import { collectDiagnosis, ISSUE_REPO } from './core/diagnose.ts';
21
22
  import {
22
23
  maybeHandleFirstRun,
23
24
  runSetup,
@@ -549,6 +550,103 @@ export async function handleStatus(args: string[]): Promise<number> {
549
550
  return res.running ? 0 : 1;
550
551
  }
551
552
 
553
+ /**
554
+ * `bond-app diagnose [--out <file.zip>] [--issue [--yes]]`: the logs, doctor, versions, the
555
+ * service and the last runs in a zip without secrets (works with the orchestrator down).
556
+ * `--issue` shows what it will send and, once confirmed, opens an issue in jmanuelcorral/bond-app
557
+ * with gh; the zip is attached by the person (GitHub's API cannot attach files).
558
+ */
559
+ export async function handleDiagnose(args: string[]): Promise<number> {
560
+ let dataDir = defaultDataDir();
561
+ let home = defaultHerdrAppHome();
562
+ let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
563
+ let host = process.env.BOND_APP_HOST || '127.0.0.1';
564
+ let out: string | null = null;
565
+ let issue = false;
566
+ let yes = false;
567
+ for (let i = 0; i < args.length; i++) {
568
+ const arg = args[i];
569
+ const value = () => {
570
+ const v = args[++i];
571
+ if (!v || v.startsWith('--')) throw new Error(`${arg} requires a value`);
572
+ return v;
573
+ };
574
+ if (arg === '--data-dir') dataDir = path.resolve(value());
575
+ else if (arg === '--home') home = path.resolve(value());
576
+ else if (arg === '--port') port = parseInt(value(), 10);
577
+ else if (arg === '--host') host = value();
578
+ else if (arg === '--out') out = path.resolve(value());
579
+ else if (arg === '--issue') issue = true;
580
+ else if (arg === '--yes' || arg === '-y') yes = true;
581
+ else if (arg === '-h' || arg === '--help') {
582
+ console.log(`Usage: bond-app diagnose [--out <file.zip>] [--issue [--yes]] [--data-dir <dir>] [--home <dir>]
583
+
584
+ Zips the orchestrator and herdr-app logs, bond-app doctor, versions (bond, hc, herdr-app,
585
+ docker), the user service and the last runs, with tokens and credentials replaced by ***.
586
+ --issue shows the summary it will send and opens an issue in ${ISSUE_REPO} with gh; then
587
+ drag the zip into the issue.`);
588
+ return 0;
589
+ } else throw new Error(`unknown option '${arg}' for diagnose`);
590
+ }
591
+
592
+ console.log('Recogiendo el diagnóstico (doctor, versiones, logs)…');
593
+ const report = await runDoctor({ port, host, dataDir, home });
594
+ let service: { status: string; unitPath: string | null } | undefined;
595
+ try {
596
+ const st = await getServiceStatus({ dataDir });
597
+ service = { status: JSON.stringify(st, null, 2), unitPath: st.unitPath };
598
+ } catch {}
599
+ const d = await collectDiagnosis({ dataDir, herdrAppHome: home, doctorJson: JSON.stringify(report, null, 2), service, version: VERSION });
600
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
601
+ const zipPath = out ?? path.join(dataDir, 'diagnostics', `bond-app-diagnose-${stamp}.zip`);
602
+ fs.mkdirSync(path.dirname(zipPath), { recursive: true, mode: 0o700 });
603
+ fs.writeFileSync(zipPath, d.zip, { mode: 0o600 });
604
+ console.log(`\nZip: ${zipPath}`);
605
+ console.log(`Contiene: ${d.files.join(', ')}`);
606
+ console.log('Tokens y credenciales sustituidos por ***. Revísalo antes de compartirlo si quieres.');
607
+ if (!issue) return 0;
608
+
609
+ const auth = await new Promise<boolean>((resolve) => {
610
+ const child = spawn('gh', ['auth', 'status'], { stdio: 'ignore', shell: process.platform === 'win32' });
611
+ child.on('error', () => resolve(false));
612
+ child.on('exit', (code) => resolve(code === 0));
613
+ });
614
+ if (!auth) {
615
+ console.error(`\nPara abrir la issue hace falta gh con sesión (gh auth login). Mientras, abre una a mano en https://github.com/${ISSUE_REPO}/issues/new y adjunta el zip.`);
616
+ return 1;
617
+ }
618
+ const firstFail = report.checks.find((c) => c.status === 'fail') ?? report.checks.find((c) => c.status === 'warn');
619
+ const title = `Diagnóstico: ${firstFail ? `${firstFail.name} — ${firstFail.detail}`.slice(0, 90) : 'informe'} (bond-app ${VERSION}, ${report.platform})`;
620
+ console.log(`\n--- Se abrirá esta issue en ${ISSUE_REPO} ---\nTítulo: ${title}\n\n${d.summary}\n--- fin ---\n`);
621
+ if (!yes) {
622
+ process.stdout.write('¿La abro? [s/N] ');
623
+ const answer = await new Promise<string>((resolve) => {
624
+ process.stdin.resume();
625
+ process.stdin.once('data', (b) => { process.stdin.pause(); resolve(String(b).trim().toLowerCase()); });
626
+ });
627
+ if (!['s', 'si', 'sí', 'y', 'yes'].includes(answer)) {
628
+ console.log('No se ha abierto nada. El zip queda en', zipPath);
629
+ return 0;
630
+ }
631
+ }
632
+ const bodyFile = path.join(path.dirname(zipPath), `issue-${stamp}.md`);
633
+ fs.writeFileSync(bodyFile, d.summary, { mode: 0o600 });
634
+ const url = await new Promise<string | null>((resolve) => {
635
+ let outText = '';
636
+ const child = spawn('gh', ['issue', 'create', '-R', ISSUE_REPO, '--title', title, '--body-file', bodyFile], { stdio: ['ignore', 'pipe', 'inherit'], shell: process.platform === 'win32' });
637
+ child.stdout.on('data', (b) => { outText += String(b); });
638
+ child.on('error', () => resolve(null));
639
+ child.on('exit', (code) => resolve(code === 0 ? (/https:\/\/\S+/.exec(outText)?.[0] ?? outText.trim()) : null));
640
+ });
641
+ if (!url) {
642
+ console.error('gh no pudo abrir la issue. El zip queda en', zipPath);
643
+ return 1;
644
+ }
645
+ console.log(`\nIssue abierta: ${url}`);
646
+ console.log(`Ahora arrastra el zip a un comentario de la issue (GitHub no deja adjuntarlo por API):\n ${zipPath}`);
647
+ return 0;
648
+ }
649
+
552
650
  export async function handleDoctor(args: string[], deps?: DoctorDeps): Promise<number> {
553
651
  let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
554
652
  let host = process.env.BOND_APP_HOST || '127.0.0.1';
@@ -859,6 +957,7 @@ Commands:
859
957
  open Open herdr-app and switch to the bond layout
860
958
  status Check the status of the orchestrator and herdr-app integration
861
959
  doctor Diagnose requirements, binaries, mods, data dir, orchestrator and image
960
+ diagnose Zip logs and diagnostics (no secrets) to report a problem; --issue opens a GitHub issue
862
961
 
863
962
  Options:
864
963
  -v, --version Show version number
@@ -1057,6 +1156,8 @@ export async function runCli(argv: string[], setupDeps?: SetupDeps): Promise<num
1057
1156
  return await handleStatus(rest);
1058
1157
  case 'doctor':
1059
1158
  return await handleDoctor(rest);
1159
+ case 'diagnose':
1160
+ return await handleDiagnose(rest);
1060
1161
  default:
1061
1162
  console.error(`bond-app: unknown command '${cmd}'\n`);
1062
1163
  printHelp();
package/src/config.ts CHANGED
@@ -39,6 +39,10 @@ export interface AppConfig {
39
39
  maxVerifyFailures: number;
40
40
  /** Issue #3 P3: how often the stuck-agent check runs (full context, exhausted budget); 0 = off. */
41
41
  stuckCheckIntervalMs: number;
42
+ /** A pi agent with a full context (or a failed compaction) is relaunched with a handoff on its own; BOND_APP_AUTO_RELAUNCH=0 turns it off. */
43
+ autoRelaunchContext: boolean;
44
+ /** Ask npm at start and once a day whether bond-app or bond have a newer version; BOND_APP_UPDATE_CHECK=0 turns it off. */
45
+ updateCheck: boolean;
42
46
  /** P4: time limit of each verify command. */
43
47
  verifyTimeoutMs: number;
44
48
  /**
@@ -157,6 +161,8 @@ export function loadConfig(overrides: Partial<AppConfig> = {}): AppConfig {
157
161
  runnerLauncher: process.env.RUNNER_LAUNCHER === 'pi' ? 'pi' : 'bond',
158
162
  maxVerifyFailures: Math.max(1, parseInt(process.env.BOND_APP_MAX_VERIFY_FAILURES || '3', 10) || 3),
159
163
  stuckCheckIntervalMs: Math.max(0, parseInt(process.env.BOND_APP_STUCK_CHECK_MS || '60000', 10) || 0),
164
+ autoRelaunchContext: process.env.BOND_APP_AUTO_RELAUNCH !== '0',
165
+ updateCheck: process.env.BOND_APP_UPDATE_CHECK !== '0',
160
166
  verifyTimeoutMs: 10 * 60 * 1000,
161
167
  analysisCommand: parseAnalysisCommand(process.env.BOND_APP_ANALYSIS_COMMAND),
162
168
  analysisTimeoutMs: 5 * 60 * 1000,
@@ -0,0 +1,279 @@
1
+ /**
2
+ * `bond-app diagnose`: everything needed to understand why bond-app misbehaves on a machine,
3
+ * in one zip, without secrets. Works with the orchestrator down (it reads files and runs the
4
+ * same checks as doctor). `--issue` opens a GitHub issue with the summary (gh) and leaves the
5
+ * zip for the person to attach: GitHub's API cannot attach files to an issue.
6
+ *
7
+ * Everything that goes in passes through redactSecrets: the API token, the stored credentials
8
+ * (the values the DB keeps) and the usual token shapes become `***`.
9
+ */
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import zlib from 'node:zlib';
14
+ import { execFile } from 'node:child_process';
15
+ import { promisify } from 'node:util';
16
+ import { DatabaseSync } from 'node:sqlite';
17
+ import { redactSecrets } from './handoff.ts';
18
+
19
+ const execFileAsync = promisify(execFile);
20
+
21
+ export const ISSUE_REPO = 'jmanuelcorral/bond-app';
22
+ /** How much of each log goes in (its end). */
23
+ export const LOG_TAIL_BYTES = 1024 * 1024;
24
+
25
+ // --- zip (store + deflate, no dependency) ------------------------------------------------
26
+
27
+ const CRC_TABLE = (() => {
28
+ const t = new Uint32Array(256);
29
+ for (let n = 0; n < 256; n++) {
30
+ let c = n;
31
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
32
+ t[n] = c >>> 0;
33
+ }
34
+ return t;
35
+ })();
36
+
37
+ export function crc32(buf: Buffer): number {
38
+ let c = 0xffffffff;
39
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
40
+ return (c ^ 0xffffffff) >>> 0;
41
+ }
42
+
43
+ /** A zip of text files (deflated), readable by any unzip. */
44
+ export function zipFiles(files: Array<{ name: string; content: string | Buffer }>, date = new Date()): Buffer {
45
+ const dosTime = ((date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2)) & 0xffff;
46
+ const dosDate = (((date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()) & 0xffff;
47
+ const locals: Buffer[] = [];
48
+ const centrals: Buffer[] = [];
49
+ let offset = 0;
50
+ for (const f of files) {
51
+ const name = Buffer.from(f.name, 'utf8');
52
+ const data = Buffer.isBuffer(f.content) ? f.content : Buffer.from(f.content, 'utf8');
53
+ const packed = zlib.deflateRawSync(data);
54
+ const crc = crc32(data);
55
+ const local = Buffer.alloc(30);
56
+ local.writeUInt32LE(0x04034b50, 0);
57
+ local.writeUInt16LE(20, 4);
58
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names
59
+ local.writeUInt16LE(8, 8); // deflate
60
+ local.writeUInt16LE(dosTime, 10);
61
+ local.writeUInt16LE(dosDate, 12);
62
+ local.writeUInt32LE(crc, 14);
63
+ local.writeUInt32LE(packed.length, 18);
64
+ local.writeUInt32LE(data.length, 22);
65
+ local.writeUInt16LE(name.length, 26);
66
+ local.writeUInt16LE(0, 28);
67
+ locals.push(local, name, packed);
68
+ const central = Buffer.alloc(46);
69
+ central.writeUInt32LE(0x02014b50, 0);
70
+ central.writeUInt16LE(20, 4);
71
+ central.writeUInt16LE(20, 6);
72
+ central.writeUInt16LE(0x0800, 8);
73
+ central.writeUInt16LE(8, 10);
74
+ central.writeUInt16LE(dosTime, 12);
75
+ central.writeUInt16LE(dosDate, 14);
76
+ central.writeUInt32LE(crc, 16);
77
+ central.writeUInt32LE(packed.length, 20);
78
+ central.writeUInt32LE(data.length, 24);
79
+ central.writeUInt16LE(name.length, 28);
80
+ central.writeUInt32LE(offset, 42);
81
+ centrals.push(central, name);
82
+ offset += local.length + name.length + packed.length;
83
+ }
84
+ const centralSize = centrals.reduce((n, b) => n + b.length, 0);
85
+ const end = Buffer.alloc(22);
86
+ end.writeUInt32LE(0x06054b50, 0);
87
+ end.writeUInt16LE(files.length, 8);
88
+ end.writeUInt16LE(files.length, 10);
89
+ end.writeUInt32LE(centralSize, 12);
90
+ end.writeUInt32LE(offset, 16);
91
+ return Buffer.concat([...locals, ...centrals, end]);
92
+ }
93
+
94
+ // --- what goes in ------------------------------------------------------------------------
95
+
96
+ /** The end of a file (logs grow): at most `max` bytes, from a line start. */
97
+ export function tailFile(file: string, max = LOG_TAIL_BYTES): string | null {
98
+ try {
99
+ const size = fs.statSync(file).size;
100
+ const fd = fs.openSync(file, 'r');
101
+ try {
102
+ const len = Math.min(size, max);
103
+ const buf = Buffer.alloc(len);
104
+ fs.readSync(fd, buf, 0, len, size - len);
105
+ let text = buf.toString('utf8');
106
+ if (size > max) text = `[… ${size - max} bytes anteriores omitidos]\n${text.slice(text.indexOf('\n') + 1)}`;
107
+ return text;
108
+ } finally {
109
+ fs.closeSync(fd);
110
+ }
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
115
+
116
+ /** Every value worth hiding that bond-app keeps: the API token and the stored credentials. */
117
+ export function knownSecrets(dataDir: string): string[] {
118
+ const out: string[] = [];
119
+ try {
120
+ out.push(fs.readFileSync(path.join(dataDir, 'token'), 'utf8').trim());
121
+ } catch {}
122
+ const db = path.join(dataDir, 'bond-app.sqlite');
123
+ if (!fs.existsSync(db)) return out;
124
+ try {
125
+ const conn = new DatabaseSync(db, { readOnly: true });
126
+ try {
127
+ // Every string inside, also inside JSON kept as a string (az's MSAL cache in the Azure login).
128
+ const strings = (v: unknown, acc: string[], depth = 0) => {
129
+ if (depth > 6) return;
130
+ if (typeof v === 'string') {
131
+ acc.push(v);
132
+ if (/^\s*[[{]/.test(v)) {
133
+ try {
134
+ strings(JSON.parse(v), acc, depth + 1);
135
+ } catch {}
136
+ }
137
+ } else if (v && typeof v === 'object') for (const x of Object.values(v)) strings(x, acc, depth + 1);
138
+ };
139
+ for (const table of ['agent_credentials', 'github_credential', 'azure_devops_credential', 'jira_credential']) {
140
+ let rows: Array<Record<string, unknown>> = [];
141
+ try {
142
+ rows = conn.prepare(`SELECT * FROM ${table}`).all() as Array<Record<string, unknown>>;
143
+ } catch {
144
+ continue;
145
+ }
146
+ for (const row of rows) {
147
+ for (const [k, v] of Object.entries(row)) {
148
+ if (typeof v !== 'string' || ['agent', 'provider', 'updated_at', 'created_at', 'login', 'site', 'email', 'org_url'].includes(k)) continue;
149
+ strings(v, out);
150
+ }
151
+ }
152
+ }
153
+ } finally {
154
+ conn.close();
155
+ }
156
+ } catch {}
157
+ // Only what looks like a secret (long, no spaces): not every word of a JSON config.
158
+ return [...new Set(out.map((s) => s.trim()).filter((s) => s.length >= 12 && !/\s/.test(s) && !/^https?:\/\//.test(s)))];
159
+ }
160
+
161
+ async function cmd(bin: string, args: string[]): Promise<string> {
162
+ try {
163
+ const { stdout, stderr } = await execFileAsync(bin, args, { timeout: 15_000, shell: process.platform === 'win32' });
164
+ return `${stdout}${stderr}`.trim();
165
+ } catch (err) {
166
+ const e = err as { stdout?: string; stderr?: string; message?: string };
167
+ return `(falló: ${(e.stderr || e.stdout || e.message || String(err)).trim().slice(0, 500)})`;
168
+ }
169
+ }
170
+
171
+ /** The last runs, without titles or stories (they may be private): state and why. */
172
+ export function runsSummary(dataDir: string): string {
173
+ const db = path.join(dataDir, 'bond-app.sqlite');
174
+ if (!fs.existsSync(db)) return 'sin base de datos';
175
+ try {
176
+ const conn = new DatabaseSync(db, { readOnly: true });
177
+ try {
178
+ const runs = conn.prepare(
179
+ `SELECT r.id, r.state, r.failure_reason, r.loop_state, r.created_at, r.updated_at, t.agent, t.hub_url IS NOT NULL AS hub
180
+ FROM runs r LEFT JOIN tickets t ON t.id = r.ticket_id ORDER BY r.created_at DESC LIMIT 20`
181
+ ).all();
182
+ const events = conn.prepare(
183
+ `SELECT run_id, type, created_at, substr(payload, 1, 400) AS payload FROM events ORDER BY rowid DESC LIMIT 200`
184
+ ).all();
185
+ return JSON.stringify({ runs, events }, null, 2);
186
+ } finally {
187
+ conn.close();
188
+ }
189
+ } catch (err) {
190
+ return `no se pudo leer: ${(err as Error).message}`;
191
+ }
192
+ }
193
+
194
+ export interface DiagnoseOptions {
195
+ dataDir: string;
196
+ herdrAppHome: string;
197
+ /** doctor's report as JSON (the caller runs it: it needs the same options as doctor). */
198
+ doctorJson: string;
199
+ /** The service's status and its unit/plist path. */
200
+ service?: { status: string; unitPath: string | null };
201
+ version: string;
202
+ }
203
+
204
+ export interface Diagnosis {
205
+ zip: Buffer;
206
+ files: string[];
207
+ /** The text for the issue: versions, doctor's failures and the end of the orchestrator log. */
208
+ summary: string;
209
+ }
210
+
211
+ export async function collectDiagnosis(o: DiagnoseOptions): Promise<Diagnosis> {
212
+ const secrets = knownSecrets(o.dataDir);
213
+ const clean = (s: string) => redactSecrets(s, secrets);
214
+ const files: Array<{ name: string; content: string }> = [];
215
+ const add = (name: string, content: string | null) => {
216
+ if (content !== null && content !== undefined) files.push({ name, content: clean(content) });
217
+ };
218
+
219
+ const info = [
220
+ `bond-app ${o.version}`,
221
+ `fecha ${new Date().toISOString()}`,
222
+ `sistema ${os.platform()} ${os.release()} ${os.arch()} (${os.type()})`,
223
+ `node ${process.version}`,
224
+ `bond ${await cmd('bond', ['--version'])}`,
225
+ `hc ${await cmd('hc', ['--version'])}`,
226
+ `herdr-app ${await cmd('herdr-app', ['--version'])}`,
227
+ '',
228
+ '## docker version',
229
+ await cmd('docker', ['version']),
230
+ '',
231
+ '## docker context ls',
232
+ await cmd('docker', ['context', 'ls']),
233
+ '',
234
+ '## Entorno',
235
+ `PATH=${process.env.PATH ?? ''}`,
236
+ ...Object.entries(process.env)
237
+ .filter(([k]) => /^(BOND_APP_|RUNNER_IMAGE$|DOCKER_HOST$|DOCKER_CONTEXT$|HERDR_APP_HOME$|XDG_)/.test(k) && !/TOKEN|SECRET|PASS|KEY/i.test(k))
238
+ .map(([k, v]) => `${k}=${v}`),
239
+ ].join('\n');
240
+ add('info.txt', info);
241
+ add('doctor.json', o.doctorJson);
242
+ add('orchestrator.log', tailFile(path.join(o.dataDir, 'orchestrator.log')));
243
+ add('app.log', tailFile(path.join(o.dataDir, 'app.log')));
244
+ for (const f of ['/tmp/herdr-app.log', path.join(o.herdrAppHome, 'herdr-app.log')]) add(`herdr-app/${path.basename(f)}`, tailFile(f, 512 * 1024));
245
+ if (o.service) {
246
+ add('service/status.txt', o.service.status);
247
+ if (o.service.unitPath) add(`service/${path.basename(o.service.unitPath)}`, tailFile(o.service.unitPath, 64 * 1024));
248
+ }
249
+ add('runs.json', runsSummary(o.dataDir));
250
+ const installed = path.join(o.herdrAppHome, 'installed.json');
251
+ add('herdr-app/installed.json', tailFile(installed, 64 * 1024));
252
+
253
+ let failing: string[] = [];
254
+ try {
255
+ const d = JSON.parse(o.doctorJson) as { checks?: Array<{ status: string; name: string; detail: string; fix?: string }> };
256
+ failing = (d.checks ?? []).filter((c) => c.status !== 'ok').map((c) => `- ${c.status === 'fail' ? '✗' : '!'} **${c.name}**: ${c.detail}${c.fix ? ` (arreglo: ${c.fix})` : ''}`);
257
+ } catch {}
258
+ const logTail = (tailFile(path.join(o.dataDir, 'orchestrator.log'), 8 * 1024) ?? 'sin log').split('\n').slice(-40).join('\n');
259
+ const summary = clean([
260
+ '## Entorno',
261
+ '',
262
+ '```',
263
+ info.split('\n## Entorno')[0].trim(),
264
+ '```',
265
+ '',
266
+ '## bond-app doctor',
267
+ '',
268
+ failing.length ? failing.join('\n') : 'Todo en orden.',
269
+ '',
270
+ '## Final del log del orquestador',
271
+ '',
272
+ '```',
273
+ logTail,
274
+ '```',
275
+ '',
276
+ 'El zip con los logs completos (sin secretos) va adjunto.',
277
+ ].join('\n'));
278
+ return { zip: zipFiles(files), files: files.map((f) => f.name), summary };
279
+ }
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import { piCompactionCommand, piCompactionOverrides } from './pi-compaction.ts';
3
3
  import { promptArgs, unattendedFlags } from './agent-flags.ts';
4
4
  import { isHerdrAgentWaiting, isLeaderHerdrAgent, isLeaderTerminal, isTerminalWaiting } from './agent-waiting.ts';
5
- import { PI_SESSION_TAIL_SCRIPT, budgetExhaustedIn, piContextStuck, resumeTimeFrom, stuckReason, type PiSessionTail, type StuckKind } from './stuck.ts';
5
+ import { PI_SESSION_TAIL_SCRIPT, budgetExhaustedIn, compactionFailedIn, piContextStuck, resumeTimeFrom, stuckReason, type PiSessionTail, type StuckKind } from './stuck.ts';
6
6
  import { BOND_APP_LOOP_CLI, LOOP_ENV_OFF_COMMAND, LOOP_ENV_ON_COMMAND, LOOP_LOG_APPEND_SCRIPT, LOOP_PLANS_SCRIPT, LOOP_SKILLS_SCRIPT, LOOP_TEXT_MAX, PLAN_PATH_RE, askMessage, loopEnv, loopLogMessage, loopLogPath, loopLogStart, loopMessageText, loopStartMessage, nextRound, sortPlans, type LoopState } from './loop.ts';
7
7
  import { HANDOFF_GATHER_SCRIPT, buildHandoff, decisionsBy, parseGather, redactSecrets } from './handoff.ts';
8
8
  import os from 'node:os';
@@ -40,6 +40,7 @@ import { HubMountError, HubSession, proposeUrls } from './hub-session.ts';
40
40
  import { AzureDevOpsApiError, AzureDevOpsClient } from '../runner/azure-devops-client.ts';
41
41
  import { azureRepoUrl, parseAzureRepoUrl, repoHostOf, repoLabel, validateRepoUrl } from './repo-host.ts';
42
42
  import { parseSourceUrl, type PullRequestHit, type SourceHubInfo, type SourceHubRef, type SourceHubRepoStatus, type SourceInfo, type SourceRef } from './pr-source.ts';
43
+ import { UpdateChecker } from './updates.ts';
43
44
  import { AgyLoginManager, AZURE_LOGIN_SPEC, CLAUDE_LOGIN_SPEC, CODEX_LOGIN_SPEC, COPILOT_LOGIN_SPEC, type AgyLoginDriver } from './agy-login.ts';
44
45
  import { buildSetupState, parseRunnerManifest } from './setup.ts';
45
46
  import { HUB_DIR, NAME_RE, agentGaps, analysisPrompt, buildAnalysis, fixedGaps, parseAgentAnswer, parseHubToml, repoNameFromUrl, teamAgentFor, teamAgents, type HubToml } from './hub.ts';
@@ -72,6 +73,9 @@ import type { AppConfig } from '../config.ts';
72
73
  /** Gaps that are the hub agent's opinion, which a person may overrule («Seguir sin ellos»). */
73
74
  const HUB_OPINION_GAPS = new Set(['missing_repo', 'agent_not_ready']);
74
75
 
76
+ /** A full context is relaunched on its own once in this window per agent; a second time waits for the person. */
77
+ export const AUTO_RELAUNCH_WINDOW_MS = 30 * 60 * 1000;
78
+
75
79
  /** az's config in a run: no prompts about subscriptions, no telemetry. */
76
80
  const AZURE_RUN_CONFIG = '[core]\nlogin_experience_v2 = off\ncollect_telemetry = false\n';
77
81
 
@@ -312,6 +316,8 @@ export class Orchestrator {
312
316
  private deliveries = new Map<string, Promise<Run>>();
313
317
  /** Issue #3: runs with an agent relaunch in progress (one at a time per run). */
314
318
  private relaunching = new Set<string>();
319
+ /** When each run agent (`<run>/<name>`) was last relaunched on its own for a full context. */
320
+ private autoRelaunchedAt = new Map<string, number>();
315
321
  // P4: a token given explicitly at start (not stored); delivery falls back to the stored one.
316
322
  private runTokens = new Map<string, string>();
317
323
  // P5: hub analyses in progress (fixed checks, hub agent, then the team), one per run.
@@ -331,6 +337,8 @@ export class Orchestrator {
331
337
  public codexLoginManager: AgyLoginManager;
332
338
  public copilotLoginManager: AgyLoginManager;
333
339
  public azureLoginManager: AgyLoginManager;
340
+ /** «Hay versión nueva» (bond-app, bond): started by the real process (index.ts), not by tests. */
341
+ public updates = new UpdateChecker();
334
342
  public jira: JiraClient;
335
343
 
336
344
  constructor(
@@ -438,6 +446,7 @@ export class Orchestrator {
438
446
  await this.codexLoginManager.cancel();
439
447
  await this.copilotLoginManager.cancel();
440
448
  await this.azureLoginManager.cancel();
449
+ this.updates.stop();
441
450
  for (const [, w] of this.runPrWatchers.entries()) {
442
451
  try { w.stop(); } catch {}
443
452
  }
@@ -1863,7 +1872,7 @@ export class Orchestrator {
1863
1872
  } catch {
1864
1873
  screen = '';
1865
1874
  }
1866
- let finding = budgetExhaustedIn(screen);
1875
+ let finding = budgetExhaustedIn(screen) ?? compactionFailedIn(screen);
1867
1876
  if (!finding) {
1868
1877
  let argv: string[] | undefined;
1869
1878
  try {
@@ -1908,6 +1917,23 @@ export class Orchestrator {
1908
1917
  changed.push(r.id);
1909
1918
  }
1910
1919
  if (previous?.reason !== found.reason) this.agentEvent(latest, 'agent.stuck', { agent: found.name, kind: found.kind, reason: found.reason });
1920
+ // A full context (or a compaction that failed) is relaunched with a handoff on its own,
1921
+ // with the same kind; twice in AUTO_RELAUNCH_WINDOW_MS for the same agent waits for the person.
1922
+ if (found.kind === 'context' && this.config.autoRelaunchContext !== false) {
1923
+ const key = `${r.id}/${found.name}`;
1924
+ const last = this.autoRelaunchedAt.get(key) ?? 0;
1925
+ if (Date.now() - last >= AUTO_RELAUNCH_WINDOW_MS) {
1926
+ this.autoRelaunchedAt.set(key, Date.now());
1927
+ try {
1928
+ const from = (await this.relaunchOptions(r.id, found.name)).from;
1929
+ await this.relaunchAgent(r.id, found.name, { agent: from, reason: `automático: ${found.reason}` });
1930
+ this.agentEvent(this.runRepo.get(r.id) ?? latest, 'agent.auto_relaunched', { agent: found.name, kind: from, reason: found.reason });
1931
+ changed.push(r.id);
1932
+ } catch (err) {
1933
+ this.agentEvent(latest, 'agent.auto_relaunch_failed', { agent: found.name, error: String((err as Error).message || err).slice(0, 300) });
1934
+ }
1935
+ }
1936
+ }
1911
1937
  }
1912
1938
  } finally {
1913
1939
  this.checkingStuck = false;
@@ -126,6 +126,7 @@ function resolveServiceContext(options: ServiceOptions = {}) {
126
126
  const dataDir = path.resolve(options.dataDir ?? env.BOND_APP_DATA_DIR ?? path.join(homeDir, '.bond-app'));
127
127
  const runnerImage = options.runnerImage ?? (env.RUNNER_IMAGE || undefined);
128
128
  const nodePath = deps.nodePath ?? process.execPath;
129
+ const servicePath = servicePathFor(env.PATH, nodePath, homeDir, platform);
129
130
  const binPath = path.resolve(deps.binPath ?? stableBinPath(path.join(repoRoot, 'bin', 'bond-app.js'), deps.npmGlobalRoot));
130
131
  const runCommand = deps.runCommand ?? defaultRunCommand;
131
132
  const uid = deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 501);
@@ -153,6 +154,7 @@ function resolveServiceContext(options: ServiceOptions = {}) {
153
154
  dataDir,
154
155
  runnerImage,
155
156
  nodePath,
157
+ servicePath,
156
158
  binPath,
157
159
  runCommand,
158
160
  uid,
@@ -182,6 +184,8 @@ export function renderSystemdUnit(params: {
182
184
  host?: string;
183
185
  dataDir: string;
184
186
  runnerImage?: string;
187
+ /** PATH for the service (launchd and systemd start it with a minimal one). */
188
+ servicePath?: string;
185
189
  }): string {
186
190
  const execParts = [
187
191
  quoteSystemdArg(params.nodePath),
@@ -197,6 +201,7 @@ export function renderSystemdUnit(params: {
197
201
  }
198
202
 
199
203
  const envLines = [`Environment=${quoteSystemdEnv('BOND_APP_DATA_DIR', params.dataDir)}`];
204
+ if (params.servicePath) envLines.push(`Environment=${quoteSystemdEnv('PATH', params.servicePath)}`);
200
205
  if (params.runnerImage) {
201
206
  envLines.push(`Environment=${quoteSystemdEnv('RUNNER_IMAGE', params.runnerImage)}`);
202
207
  }
@@ -241,6 +246,8 @@ export function renderLaunchdPlist(params: {
241
246
  host?: string;
242
247
  dataDir: string;
243
248
  runnerImage?: string;
249
+ /** PATH for the service: launchd starts it with /usr/bin:/bin:/usr/sbin:/sbin only. */
250
+ servicePath?: string;
244
251
  }): string {
245
252
  const args = [
246
253
  params.nodePath,
@@ -256,6 +263,7 @@ export function renderLaunchdPlist(params: {
256
263
  }
257
264
 
258
265
  const envEntries = [` <key>BOND_APP_DATA_DIR</key>`, ` <string>${escapeXml(params.dataDir)}</string>`];
266
+ if (params.servicePath) envEntries.push(` <key>PATH</key>`, ` <string>${escapeXml(params.servicePath)}</string>`);
259
267
  if (params.runnerImage) {
260
268
  envEntries.push(` <key>RUNNER_IMAGE</key>`, ` <string>${escapeXml(params.runnerImage)}</string>`);
261
269
  }
@@ -417,6 +425,7 @@ export async function installService(options: ServiceOptions = {}): Promise<Serv
417
425
  host: ctx.host,
418
426
  dataDir: ctx.dataDir,
419
427
  runnerImage: ctx.runnerImage,
428
+ servicePath: ctx.servicePath,
420
429
  });
421
430
  fs.writeFileSync(ctx.unitPath!, unitContent, { encoding: 'utf8', mode: 0o644 });
422
431
 
@@ -479,6 +488,7 @@ export async function installService(options: ServiceOptions = {}): Promise<Serv
479
488
  host: ctx.host,
480
489
  dataDir: ctx.dataDir,
481
490
  runnerImage: ctx.runnerImage,
491
+ servicePath: ctx.servicePath,
482
492
  });
483
493
  fs.writeFileSync(ctx.unitPath!, plistContent, { encoding: 'utf8', mode: 0o644 });
484
494
 
@@ -859,3 +869,27 @@ async function windowsAction(action: ServiceAction, ctx: ServiceCtx): Promise<Se
859
869
  detail: details.join('; '),
860
870
  };
861
871
  }
872
+
873
+ /**
874
+ * The PATH the orchestrator service runs with. launchd (and systemd --user) start it with a
875
+ * minimal PATH, without the folders where docker (OrbStack, Docker Desktop), hc, bond and
876
+ * herdr-app live: the orchestrator could not find them and did not start. The service keeps
877
+ * the PATH of whoever installs it, plus node's folder and the usual install folders.
878
+ */
879
+ export function servicePathFor(current: string | undefined, nodePath: string, homeDir: string, platform: NodeJS.Platform): string | undefined {
880
+ if (platform === 'win32') return undefined;
881
+ const extra = [
882
+ path.dirname(nodePath),
883
+ path.join(homeDir, '.local', 'bin'),
884
+ ...(platform === 'darwin' ? ['/opt/homebrew/bin', path.join(homeDir, '.orbstack', 'bin'), '/Applications/Docker.app/Contents/Resources/bin'] : []),
885
+ '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin',
886
+ ];
887
+ const seen = new Set<string>();
888
+ const out: string[] = [];
889
+ for (const dir of [...String(current ?? '').split(':'), ...extra]) {
890
+ if (!dir || !path.isAbsolute(dir) || seen.has(dir)) continue;
891
+ seen.add(dir);
892
+ out.push(dir);
893
+ }
894
+ return out.join(':');
895
+ }
@@ -1178,7 +1178,8 @@ export async function runUpdate(options: UpdateOptions = {}): Promise<UpdateResu
1178
1178
  }
1179
1179
  }
1180
1180
 
1181
- // 4. Restart user service if installed
1181
+ // 4. Rewrite the user service (if installed) with this version's unit/plist, then restart it:
1182
+ // fixes to the service itself (macOS PATH, 0.3.1) reach existing installs this way.
1182
1183
  const serviceDeps: ServiceDeps = {
1183
1184
  runCommand,
1184
1185
  platform,
@@ -1188,10 +1189,12 @@ export async function runUpdate(options: UpdateOptions = {}): Promise<UpdateResu
1188
1189
  const svcStatus = await getServiceStatus({ port, host, dataDir, deps: serviceDeps });
1189
1190
  if (svcStatus.supported && svcStatus.installed) {
1190
1191
  if (dryRun) {
1191
- const detail = `would restart user service (${svcStatus.serviceName})`;
1192
+ const detail = `would rewrite and restart user service (${svcStatus.serviceName})`;
1192
1193
  logStep('✓', 'User service', detail);
1193
1194
  steps.push({ id: 'service', ok: true, skipped: true, detail });
1194
1195
  } else {
1196
+ const reinstall = await (deps.installService ?? installService)({ port, host, dataDir, runnerImage: options.runnerImage, deps: serviceDeps });
1197
+ if (!reinstall.ok) logStep('!', 'User service', `could not rewrite it: ${reinstall.detail}`);
1195
1198
  const svcRes = await restartSvcFn({
1196
1199
  port,
1197
1200
  host,
package/src/core/stuck.ts CHANGED
@@ -42,6 +42,18 @@ const RESET_PATTERNS: RegExp[] = [
42
42
  /try again (?:in|at)\s+([^.\n]{1,30})/i,
43
43
  ];
44
44
 
45
+ /**
46
+ * pi says on its screen that compaction failed (the summary did not fit the model's output
47
+ * cap, NAV-5109): it goes on with a context it can no longer free, and stops when it is full.
48
+ * Only the bottom of the screen counts, like the budget notice.
49
+ */
50
+ export function compactionFailedIn(screen: string): StuckFinding | null {
51
+ const tail = screen.split('\n').slice(-25).join('\n');
52
+ return /Auto-compaction failed|Context overflow recovery failed|Truncated response recovery failed/.test(tail)
53
+ ? { kind: 'context', detail: 'la compactación falló' }
54
+ : null;
55
+ }
56
+
45
57
  /** The last lines of an agent's screen tell an exhausted budget, and when it resets. */
46
58
  export function budgetExhaustedIn(screen: string): StuckFinding | null {
47
59
  // The bottom of the screen only: the notice is the agent's last word, and a limit mentioned
@@ -0,0 +1,155 @@
1
+ /**
2
+ * «Hay versión nueva»: the orchestrator asks npm, at start and then once a day, for the latest
3
+ * bond-app and bond, and compares them with what is installed. The app shows it in the status
4
+ * bar and Ajustes → Avanzado, whose «Actualizar» runs `bond-app update`. The only network call
5
+ * is to registry.npmjs.org; without network it says nothing (no error to the person).
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { execFile } from 'node:child_process';
10
+ import { promisify } from 'node:util';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ const execFileAsync = promisify(execFile);
14
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
15
+
16
+ export const UPDATE_PACKAGES = { bond_app: '@jmanuelcorral/bond-app', bond: '@jmanuelcorral/bond' } as const;
17
+ export const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
18
+
19
+ export interface PackageUpdate {
20
+ installed: string | null;
21
+ latest: string | null;
22
+ update: boolean;
23
+ }
24
+
25
+ export interface UpdateStatus {
26
+ bond_app: PackageUpdate;
27
+ bond: PackageUpdate;
28
+ /** Something to update. */
29
+ available: boolean;
30
+ checked_at: string | null;
31
+ /** Why the last check could not ask npm (no network...): for Ajustes, not an alarm. */
32
+ error: string | null;
33
+ }
34
+
35
+ /** a < b for plain x.y.z versions (pre-releases count as lower). */
36
+ export function isNewer(latest: string | null, installed: string | null): boolean {
37
+ if (!latest || !installed) return false;
38
+ const parse = (v: string) => {
39
+ const [core, pre] = v.replace(/^v/, '').split('-', 2);
40
+ return { nums: core.split('.').map((n) => Number.parseInt(n, 10) || 0), pre: pre ?? null };
41
+ };
42
+ const a = parse(latest);
43
+ const b = parse(installed);
44
+ for (let i = 0; i < 3; i++) {
45
+ if ((a.nums[i] ?? 0) !== (b.nums[i] ?? 0)) return (a.nums[i] ?? 0) > (b.nums[i] ?? 0);
46
+ }
47
+ return a.pre === null && b.pre !== null;
48
+ }
49
+
50
+ export interface UpdateDeps {
51
+ /** The latest version npm has for a package (registry.npmjs.org/<pkg>/latest). */
52
+ latestVersion?: (pkg: string) => Promise<string | null>;
53
+ /** The installed bond (`bond --version`). */
54
+ bondVersion?: () => Promise<string | null>;
55
+ /** This bond-app's version. */
56
+ appVersion?: string;
57
+ now?: () => number;
58
+ }
59
+
60
+ async function npmLatest(pkg: string): Promise<string | null> {
61
+ const ctrl = new AbortController();
62
+ const timer = setTimeout(() => ctrl.abort(), 8000);
63
+ try {
64
+ const res = await fetch(`https://registry.npmjs.org/${pkg.replace('/', '%2F')}/latest`, {
65
+ signal: ctrl.signal,
66
+ headers: { Accept: 'application/json' },
67
+ });
68
+ if (!res.ok) throw new Error(`npm respondió ${res.status}`);
69
+ const body = (await res.json()) as { version?: unknown };
70
+ return typeof body.version === 'string' ? body.version : null;
71
+ } finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }
75
+
76
+ async function installedBond(): Promise<string | null> {
77
+ try {
78
+ const { stdout } = await execFileAsync('bond', ['--version'], { timeout: 10_000, shell: process.platform === 'win32' });
79
+ return /(\d+\.\d+\.\d+(?:-[\w.]+)?)/.exec(stdout)?.[1] ?? null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function ownVersion(): string {
86
+ try {
87
+ return (JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')) as { version: string }).version;
88
+ } catch {
89
+ return '0.0.0';
90
+ }
91
+ }
92
+
93
+ export class UpdateChecker {
94
+ private status: UpdateStatus;
95
+ private timer: NodeJS.Timeout | null = null;
96
+ private inFlight: Promise<UpdateStatus> | null = null;
97
+ private deps: Required<UpdateDeps>;
98
+
99
+ constructor(deps: UpdateDeps = {}) {
100
+ this.deps = {
101
+ latestVersion: deps.latestVersion ?? npmLatest,
102
+ bondVersion: deps.bondVersion ?? installedBond,
103
+ appVersion: deps.appVersion ?? ownVersion(),
104
+ now: deps.now ?? Date.now,
105
+ };
106
+ const empty = (installed: string | null): PackageUpdate => ({ installed, latest: null, update: false });
107
+ this.status = { bond_app: empty(this.deps.appVersion), bond: empty(null), available: false, checked_at: null, error: null };
108
+ }
109
+
110
+ get(): UpdateStatus {
111
+ return { ...this.status, bond_app: { ...this.status.bond_app }, bond: { ...this.status.bond } };
112
+ }
113
+
114
+ /** Ask npm now (one request at a time). Never throws: a failure is kept in `error`. */
115
+ check(): Promise<UpdateStatus> {
116
+ if (this.inFlight) return this.inFlight;
117
+ this.inFlight = (async () => {
118
+ const bondInstalled = await this.deps.bondVersion().catch(() => null);
119
+ try {
120
+ const [appLatest, bondLatest] = await Promise.all([
121
+ this.deps.latestVersion(UPDATE_PACKAGES.bond_app),
122
+ this.deps.latestVersion(UPDATE_PACKAGES.bond),
123
+ ]);
124
+ const app: PackageUpdate = { installed: this.deps.appVersion, latest: appLatest, update: isNewer(appLatest, this.deps.appVersion) };
125
+ const bond: PackageUpdate = { installed: bondInstalled, latest: bondLatest, update: isNewer(bondLatest, bondInstalled) };
126
+ this.status = { bond_app: app, bond, available: app.update || bond.update, checked_at: new Date(this.deps.now()).toISOString(), error: null };
127
+ } catch (err) {
128
+ this.status = {
129
+ ...this.status,
130
+ bond: { ...this.status.bond, installed: bondInstalled },
131
+ checked_at: new Date(this.deps.now()).toISOString(),
132
+ error: String((err as Error).message || err).slice(0, 200),
133
+ };
134
+ }
135
+ return this.get();
136
+ })().finally(() => {
137
+ this.inFlight = null;
138
+ });
139
+ return this.inFlight;
140
+ }
141
+
142
+ /** Check now and then every `intervalMs` (0: only now). */
143
+ start(intervalMs = UPDATE_CHECK_INTERVAL_MS): void {
144
+ void this.check();
145
+ if (intervalMs > 0) {
146
+ this.timer = setInterval(() => void this.check(), intervalMs);
147
+ this.timer.unref?.();
148
+ }
149
+ }
150
+
151
+ stop(): void {
152
+ if (this.timer) clearInterval(this.timer);
153
+ this.timer = null;
154
+ }
155
+ }
package/src/index.ts CHANGED
@@ -30,6 +30,8 @@ export async function bootstrap(configOverrides = {}, hooks: ServerHooks = {}) {
30
30
  );
31
31
 
32
32
  await orchestrator.start();
33
+ // «Hay versión nueva»: ask npm now and once a day (BOND_APP_UPDATE_CHECK=0 turns it off).
34
+ if (config.updateCheck) orchestrator.updates.start();
33
35
 
34
36
  const server = createServer(orchestrator, hooks);
35
37
 
package/src/server/app.ts CHANGED
@@ -1358,6 +1358,12 @@ export function createServer(orchestrator: Orchestrator, hooks: ServerHooks = {}
1358
1358
  return;
1359
1359
  }
1360
1360
 
1361
+ // «Hay versión nueva»: the last check of bond-app and bond against npm; POST asks again now.
1362
+ if (pathname === '/api/v1/system/updates' && (method === 'GET' || method === 'POST')) {
1363
+ sendJson(200, method === 'POST' ? await orchestrator.updates.check() : orchestrator.updates.get());
1364
+ return;
1365
+ }
1366
+
1361
1367
  // Progress of the image build in flight, or how the last one ended (Ajustes → Imagen).
1362
1368
  if (pathname === '/api/v1/system/rebuild' && method === 'GET') {
1363
1369
  sendJson(200, orchestrator.getRebuildStatus());