@jmanuelcorral/bond-app 0.3.0 → 0.3.2

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,73 @@ 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
+ this.runInSpace("bond-app update", updateCommand(), "Actualizando bond-app: al terminar, el orquestador se reinicia.");
403
+ }
404
+
405
+ /**
406
+ * A bond-app command in a space of its own on this computer. Ajustes closes first: the space
407
+ * would open behind the dialog (and `diagnose --issue` asks there before sending anything).
408
+ */
409
+ runInSpace(name, argv, message) {
410
+ const overlay = props()?.overlay;
411
+ try {
412
+ if (overlay) closeOverlay(overlay);
413
+ run("space.new", { name, machine: "", argv, focus: true });
414
+ notify({ title: name, body: message, level: "info" });
415
+ } catch (e) {
416
+ notify({ title: `No se pudo abrir «${name}»`, body: String(e?.message ?? e), level: "error" });
417
+ }
418
+ }
419
+
420
+ /** «Exportar diagnóstico» / «Abrir issue»: bond-app diagnose in a space of its own (works with the orchestrator down). */
421
+ runDiagnose(issue) {
422
+ this.runInSpace(issue ? "bond-app issue" : "bond-app diagnose", diagnoseCommand(issue), issue
423
+ ? "Revisa lo que se va a enviar y contesta en ese espacio si abre la issue."
424
+ : "El zip queda en la carpeta de datos de bond-app; la ruta sale en ese espacio.");
425
+ }
426
+
427
+ diagnoseBlock() {
428
+ const t = theme();
429
+ return v_flex().id("diagnose-block").gap(8)
430
+ .child(h_flex().gap(8).items_center()
431
+ .child(div().flex_1().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Informar de un problema"))
432
+ .child(this.button("diagnose-zip", "Exportar diagnóstico", false, () => this.runDiagnose(false)))
433
+ .child(this.button("diagnose-issue", "Abrir issue en GitHub", false, () => this.runDiagnose(true))))
434
+ .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."));
435
+ }
436
+
437
+ versionsBlock() {
438
+ const t = theme();
439
+ const u = this.updates;
440
+ const row = (id, name, p) => h_flex().id(id).gap(8).items_center()
441
+ .child(div().w(90).flex_none().text_size(UI.text.small).font_semibold().text_color(t.foreground).child(name))
442
+ .child(div().flex_1().text_size(UI.text.small).text_color(p?.update ? this.tone(t, "waiting") : t.muted)
443
+ .child(p ? `${p.installed ?? "?"}${p.latest ? (p.update ? ` → ${p.latest} disponible` : " (la última)") : ""}` : "…"));
444
+ return v_flex().id("versions-block").gap(8)
445
+ .child(h_flex().gap(8).items_center()
446
+ .child(div().flex_1().text_size(UI.text.body).font_semibold().text_color(t.foreground).child("Versiones"))
447
+ .child(this.button("updates-check", this.updatesBusy ? "Comprobando…" : "Comprobar ahora", false, (cx) => this.loadUpdates(cx, true)))
448
+ .when(Boolean(u?.available), (el) => el.child(this.button("updates-run", "Actualizar", true, () => this.runUpdate()))))
449
+ .child(row("version-bond-app", "bond-app", u?.bond_app))
450
+ .child(row("version-bond", "bond", u?.bond))
451
+ .when(Boolean(u?.error), (el) => el.child(this.note(`No se pudo consultar npm: ${u.error}`)))
452
+ .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."));
453
+ }
454
+
387
455
  loadDoctor(cx) {
388
456
  if (this.doctorBusy) return;
389
457
  this.doctorBusy = true;
@@ -1370,7 +1438,9 @@ export default class BondSettings extends View {
1370
1438
  .child(row("API", apiUrl()))
1371
1439
  .child(row("Asistente", s ? (s.setup_done ? "terminado" : "sin terminar") : "—"))
1372
1440
  .child(row("Credenciales", "En el orquestador, 0600; llegan a cada run por stdin.")))
1441
+ .child(this.versionsBlock())
1373
1442
  .child(this.doctorBlock())
1443
+ .child(this.diagnoseBlock())
1374
1444
  .child(this.loopBlock())
1375
1445
  .child(this.favoritesBlock())
1376
1446
  .child(h_flex().child(this.button("wiz-reopen", "Abrir el asistente", false, (cx) => {
@@ -1425,7 +1495,7 @@ export default class BondSettings extends View {
1425
1495
  return v_flex().id("doctor-block").gap(8)
1426
1496
  .child(h_flex().gap(8).items_center()
1427
1497
  .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))))
1498
+ .child(this.button("doctor-refresh", this.doctorBusy ? "Comprobando…" : "Volver a comprobar", false, (cx) => this.loadDoctor(cx))))
1429
1499
  .when(Boolean(summaryText), (el) => el.child(div().id("doctor-summary").text_size(UI.text.small).text_color(t.muted).child(summaryText)))
1430
1500
  .when(Boolean(this.doctorError), (el) => el.child(div().id("doctor-error").text_size(UI.text.small).text_color(t.blocked).child(this.doctorError)))
1431
1501
  .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.2",
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,
@@ -277,9 +278,15 @@ export async function handleStart(
277
278
  setupDeps?: SetupDeps
278
279
  ): Promise<number> {
279
280
  const overrides: Record<string, any> = {};
281
+ // Started by the user service itself (its unit/plist/task passes --as-service; launchd also
282
+ // names the job in XPC_SERVICE_NAME, for plists from before the flag): the service being
283
+ // «active» is this very process, not another one on the port (issue #5).
284
+ let asService = /(^|\.)bond-app\./.test(process.env.XPC_SERVICE_NAME ?? '');
280
285
  for (let i = 0; i < args.length; i++) {
281
286
  const arg = args[i];
282
- if (arg === '--port') {
287
+ if (arg === '--as-service') {
288
+ asService = true;
289
+ } else if (arg === '--port') {
283
290
  const v = args[++i];
284
291
  if (!v || v.startsWith('--')) throw new Error('--port requires a value');
285
292
  overrides.port = parseInt(v, 10);
@@ -325,7 +332,7 @@ export async function handleStart(
325
332
  dataDir: startDataDir,
326
333
  deps: setupDeps?.serviceDeps,
327
334
  });
328
- if (svcStatus.active) {
335
+ if (svcStatus.active && !asService) {
329
336
  console.error(
330
337
  `bond-app: port ${startPort} is already in use by the bond-app user service (${svcStatus.serviceName}).`
331
338
  );
@@ -549,6 +556,103 @@ export async function handleStatus(args: string[]): Promise<number> {
549
556
  return res.running ? 0 : 1;
550
557
  }
551
558
 
559
+ /**
560
+ * `bond-app diagnose [--out <file.zip>] [--issue [--yes]]`: the logs, doctor, versions, the
561
+ * service and the last runs in a zip without secrets (works with the orchestrator down).
562
+ * `--issue` shows what it will send and, once confirmed, opens an issue in jmanuelcorral/bond-app
563
+ * with gh; the zip is attached by the person (GitHub's API cannot attach files).
564
+ */
565
+ export async function handleDiagnose(args: string[]): Promise<number> {
566
+ let dataDir = defaultDataDir();
567
+ let home = defaultHerdrAppHome();
568
+ let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
569
+ let host = process.env.BOND_APP_HOST || '127.0.0.1';
570
+ let out: string | null = null;
571
+ let issue = false;
572
+ let yes = false;
573
+ for (let i = 0; i < args.length; i++) {
574
+ const arg = args[i];
575
+ const value = () => {
576
+ const v = args[++i];
577
+ if (!v || v.startsWith('--')) throw new Error(`${arg} requires a value`);
578
+ return v;
579
+ };
580
+ if (arg === '--data-dir') dataDir = path.resolve(value());
581
+ else if (arg === '--home') home = path.resolve(value());
582
+ else if (arg === '--port') port = parseInt(value(), 10);
583
+ else if (arg === '--host') host = value();
584
+ else if (arg === '--out') out = path.resolve(value());
585
+ else if (arg === '--issue') issue = true;
586
+ else if (arg === '--yes' || arg === '-y') yes = true;
587
+ else if (arg === '-h' || arg === '--help') {
588
+ console.log(`Usage: bond-app diagnose [--out <file.zip>] [--issue [--yes]] [--data-dir <dir>] [--home <dir>]
589
+
590
+ Zips the orchestrator and herdr-app logs, bond-app doctor, versions (bond, hc, herdr-app,
591
+ docker), the user service and the last runs, with tokens and credentials replaced by ***.
592
+ --issue shows the summary it will send and opens an issue in ${ISSUE_REPO} with gh; then
593
+ drag the zip into the issue.`);
594
+ return 0;
595
+ } else throw new Error(`unknown option '${arg}' for diagnose`);
596
+ }
597
+
598
+ console.log('Recogiendo el diagnóstico (doctor, versiones, logs)…');
599
+ const report = await runDoctor({ port, host, dataDir, home });
600
+ let service: { status: string; unitPath: string | null } | undefined;
601
+ try {
602
+ const st = await getServiceStatus({ dataDir });
603
+ service = { status: JSON.stringify(st, null, 2), unitPath: st.unitPath };
604
+ } catch {}
605
+ const d = await collectDiagnosis({ dataDir, herdrAppHome: home, doctorJson: JSON.stringify(report, null, 2), service, version: VERSION });
606
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
607
+ const zipPath = out ?? path.join(dataDir, 'diagnostics', `bond-app-diagnose-${stamp}.zip`);
608
+ fs.mkdirSync(path.dirname(zipPath), { recursive: true, mode: 0o700 });
609
+ fs.writeFileSync(zipPath, d.zip, { mode: 0o600 });
610
+ console.log(`\nZip: ${zipPath}`);
611
+ console.log(`Contiene: ${d.files.join(', ')}`);
612
+ console.log('Tokens y credenciales sustituidos por ***. Revísalo antes de compartirlo si quieres.');
613
+ if (!issue) return 0;
614
+
615
+ const auth = await new Promise<boolean>((resolve) => {
616
+ const child = spawn('gh', ['auth', 'status'], { stdio: 'ignore', shell: process.platform === 'win32' });
617
+ child.on('error', () => resolve(false));
618
+ child.on('exit', (code) => resolve(code === 0));
619
+ });
620
+ if (!auth) {
621
+ 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.`);
622
+ return 1;
623
+ }
624
+ const firstFail = report.checks.find((c) => c.status === 'fail') ?? report.checks.find((c) => c.status === 'warn');
625
+ const title = `Diagnóstico: ${firstFail ? `${firstFail.name} — ${firstFail.detail}`.slice(0, 90) : 'informe'} (bond-app ${VERSION}, ${report.platform})`;
626
+ console.log(`\n--- Se abrirá esta issue en ${ISSUE_REPO} ---\nTítulo: ${title}\n\n${d.summary}\n--- fin ---\n`);
627
+ if (!yes) {
628
+ process.stdout.write('¿La abro? [s/N] ');
629
+ const answer = await new Promise<string>((resolve) => {
630
+ process.stdin.resume();
631
+ process.stdin.once('data', (b) => { process.stdin.pause(); resolve(String(b).trim().toLowerCase()); });
632
+ });
633
+ if (!['s', 'si', 'sí', 'y', 'yes'].includes(answer)) {
634
+ console.log('No se ha abierto nada. El zip queda en', zipPath);
635
+ return 0;
636
+ }
637
+ }
638
+ const bodyFile = path.join(path.dirname(zipPath), `issue-${stamp}.md`);
639
+ fs.writeFileSync(bodyFile, d.summary, { mode: 0o600 });
640
+ const url = await new Promise<string | null>((resolve) => {
641
+ let outText = '';
642
+ const child = spawn('gh', ['issue', 'create', '-R', ISSUE_REPO, '--title', title, '--body-file', bodyFile], { stdio: ['ignore', 'pipe', 'inherit'], shell: process.platform === 'win32' });
643
+ child.stdout.on('data', (b) => { outText += String(b); });
644
+ child.on('error', () => resolve(null));
645
+ child.on('exit', (code) => resolve(code === 0 ? (/https:\/\/\S+/.exec(outText)?.[0] ?? outText.trim()) : null));
646
+ });
647
+ if (!url) {
648
+ console.error('gh no pudo abrir la issue. El zip queda en', zipPath);
649
+ return 1;
650
+ }
651
+ console.log(`\nIssue abierta: ${url}`);
652
+ console.log(`Ahora arrastra el zip a un comentario de la issue (GitHub no deja adjuntarlo por API):\n ${zipPath}`);
653
+ return 0;
654
+ }
655
+
552
656
  export async function handleDoctor(args: string[], deps?: DoctorDeps): Promise<number> {
553
657
  let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
554
658
  let host = process.env.BOND_APP_HOST || '127.0.0.1';
@@ -859,6 +963,7 @@ Commands:
859
963
  open Open herdr-app and switch to the bond layout
860
964
  status Check the status of the orchestrator and herdr-app integration
861
965
  doctor Diagnose requirements, binaries, mods, data dir, orchestrator and image
966
+ diagnose Zip logs and diagnostics (no secrets) to report a problem; --issue opens a GitHub issue
862
967
 
863
968
  Options:
864
969
  -v, --version Show version number
@@ -875,6 +980,7 @@ Options:
875
980
  --port <port> HTTP port to listen on (default: 3000 or $BOND_APP_PORT)
876
981
  --host <host> Loopback interface to bind to (default: 127.0.0.1 or $BOND_APP_HOST)
877
982
  --data-dir <path> Data directory for database and token (default: ~/.bond-app or $BOND_APP_DATA_DIR)
983
+ --as-service Started by the user service itself (its unit, plist or task passes it)
878
984
  -h, --help Show this help
879
985
  `);
880
986
  }
@@ -1057,6 +1163,8 @@ export async function runCli(argv: string[], setupDeps?: SetupDeps): Promise<num
1057
1163
  return await handleStatus(rest);
1058
1164
  case 'doctor':
1059
1165
  return await handleDoctor(rest);
1166
+ case 'diagnose':
1167
+ return await handleDiagnose(rest);
1060
1168
  default:
1061
1169
  console.error(`bond-app: unknown command '${cmd}'\n`);
1062
1170
  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,