@jmanuelcorral/bond-app 0.2.2 → 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.
@@ -345,6 +345,19 @@ export const HIDDEN_KEY = "bond.agents.hidden";
345
345
  * run's orchestrator has its own tab in the space. */
346
346
  export const INIT_TAB = "bond-init";
347
347
 
348
+ /**
349
+ * What the run's first tab (INIT_TAB) runs: a note saying the run is being prepared (an
350
+ * analysed hub can take minutes before gru starts), then a shell. The tab closes on its own
351
+ * once the run's leader has its own (initTabToClose). Same text in bond-board.
352
+ */
353
+ export const INIT_ARGV = ["sh", "-c", [
354
+ "printf '\\n bond-app · preparando el run\\n\\n'",
355
+ "printf ' Se clona el código y, en un hub, un agente de solo lectura revisa si al hub le falta\\n'",
356
+ "printf ' algo para la historia (hasta 5 minutos). Después arranca gru, el agente principal,\\n'",
357
+ "printf ' y esta pestaña se cierra sola. El estado está en el panel Agentes.\\n\\n'",
358
+ "exec sh",
359
+ ].join("; ")];
360
+
348
361
  /** "bond-run-x/t3" -> "bond-run-x"; null for a terminal of this computer. */
349
362
  export function machineOf(addr) {
350
363
  const s = String(addr ?? "");
@@ -459,6 +472,42 @@ export function panelBuildSteps(build, baseShown = false) {
459
472
  return steps;
460
473
  }
461
474
 
475
+ /**
476
+ * The run's space when its machine has more than one. The board may open the run's space
477
+ * (a bond-init shell) while the hub is still being analysed, and bond then starts gru in a
478
+ * space of its own (labels herdr.space/herdr.tab from the container): the run's space is the
479
+ * one showing its agents, the leader's first; else the shown one, else the first.
480
+ */
481
+ export function runSpaceOf(spaceList, paneList, machine, agentAddrs = []) {
482
+ const mine = (spaceList ?? []).filter((s) => s && s.machine === machine);
483
+ if (mine.length <= 1) return mine[0] ?? null;
484
+ const spaceOfTab = new Map();
485
+ for (const sp of mine) for (const t of sp.tabs ?? []) spaceOfTab.set(t.id, sp);
486
+ for (const addr of agentAddrs ?? []) {
487
+ const pane = (paneList ?? []).find((p) => p && p.terminal === addr && spaceOfTab.has(p.tab));
488
+ if (pane) return spaceOfTab.get(pane.tab);
489
+ }
490
+ return mine.find((sp) => sp.active) ?? mine[0];
491
+ }
492
+
493
+ /**
494
+ * Other spaces of the run's machine holding only the bond-init shell, once the run's space
495
+ * shows an agent: they are left over from opening the run early, and can be closed.
496
+ */
497
+ export function strayInitSpaces(spaceList, paneList, machine, runSpace, agentAddrs = []) {
498
+ if (!runSpace) return [];
499
+ const agents = new Set(agentAddrs ?? []);
500
+ const showsAgent = (sp) => {
501
+ const tabs = new Set((sp.tabs ?? []).map((t) => t.id));
502
+ return (paneList ?? []).some((p) => p && agents.has(p.terminal) && tabs.has(p.tab));
503
+ };
504
+ if (!showsAgent(runSpace)) return [];
505
+ return (spaceList ?? [])
506
+ .filter((sp) => sp && sp.machine === machine && sp.id !== runSpace.id)
507
+ .filter((sp) => (sp.tabs ?? []).length > 0 && sp.tabs.every((t) => t.name === INIT_TAB) && !showsAgent(sp))
508
+ .map((sp) => sp.id);
509
+ }
510
+
462
511
  /**
463
512
  * The INIT_TAB of the run's space to close once the orchestrator shows in another tab of
464
513
  * that space (its shell was made by space.new, not by the person), else null. Never a tab
@@ -482,6 +531,9 @@ export function initTabToClose(space, paneList, machine, agentAddrs = [], leader
482
531
 
483
532
  /** Is this row the run's orchestrator (gru / the hub leader)? */
484
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;
485
537
  const pane = String(row?.pane ?? row?.agent?.pane ?? "");
486
538
  return row?.repo === "orquestador" || row?.repoLabel === "orquestador" || row?.agent?.name === "hub leader"
487
539
  || row?.path === "/workspace/hub" || pane.endsWith("/t1");
@@ -535,3 +587,190 @@ export function attentionOf(rows, runReason = null) {
535
587
  return null;
536
588
  }
537
589
 
590
+
591
+ // ---- issue #3: «Relanzar con resumen» ----
592
+
593
+ /** Why an agent is relaunched: the chip and the text the run records (and the handoff says). */
594
+ export const RELAUNCH_REASONS = [
595
+ { id: "contexto", label: "Contexto lleno", text: "contexto lleno (la compactación falló)" },
596
+ { id: "presupuesto", label: "Presupuesto agotado", text: "presupuesto agotado" },
597
+ { id: "rinde", label: "No rinde", text: "el modelo no rinde" },
598
+ { id: "otro", label: "Otro", text: "relanzado a mano" },
599
+ ];
600
+
601
+ const reasonText = (id) => (RELAUNCH_REASONS.find((r) => r.id === id) ?? RELAUNCH_REASONS[RELAUNCH_REASONS.length - 1]).text;
602
+
603
+ /** The API path for one agent's relaunch; with agent/reason, the preview's query. */
604
+ export function relaunchPath(runId, name, agent = null, reason = null) {
605
+ const base = `/runs/${encodeURIComponent(String(runId))}/agents/${encodeURIComponent(String(name))}/relaunch`;
606
+ const q = [];
607
+ if (agent) q.push(`agent=${encodeURIComponent(agent)}`);
608
+ if (reason) q.push(`reason=${encodeURIComponent(reasonText(reason))}`);
609
+ return q.length ? `${base}?${q.join("&")}` : base;
610
+ }
611
+
612
+ /** The POST body: the model only for pi and only when given; the handoff as shown. */
613
+ export function relaunchBody({ agent, model, reason, handoff }) {
614
+ const body = { agent, reason: reasonText(reason) };
615
+ const m = String(model ?? "").trim();
616
+ if (agent === "pi" && m) body.model = m;
617
+ const h = String(handoff ?? "");
618
+ if (h.trim()) body.handoff = h;
619
+ return body;
620
+ }
621
+
622
+ const AGENT_NAME_RE = /^[a-z][a-z0-9_-]{0,31}$/;
623
+
624
+ /**
625
+ * The terminal name to relaunch for a panel row: the live terminal's name, else a closed agent
626
+ * at that address (NAV-4588: the dead gru still shows as the run's «pi» row from team-status),
627
+ * else gru when the row is the run's main terminal. null when none is a valid name.
628
+ */
629
+ export function relaunchNameOf(row, terminals, closed, run) {
630
+ const pane = row?.pane;
631
+ const live = (terminals ?? []).find((x) => x.address === pane)?.name;
632
+ const dead = (closed ?? []).find((x) => x.address === pane)?.name;
633
+ const main = pane && run?.hc_terminal === pane ? "gru" : null;
634
+ for (const candidate of [live, dead, row?.minion, main]) {
635
+ const name = String(candidate ?? "").trim();
636
+ if (AGENT_NAME_RE.test(name)) return name;
637
+ }
638
+ return null;
639
+ }
640
+
641
+ /** Closed agents whose terminal is not already a row of the panel. */
642
+ export function closedNotShown(closed, rows) {
643
+ const panes = new Set((rows ?? []).map((r) => r?.pane).filter(Boolean));
644
+ return (closed ?? []).filter((c) => !panes.has(c.address));
645
+ }
646
+
647
+ /**
648
+ * Issue #3 P3: the stuck agent a run's waiting reason names («gru: contexto lleno…»,
649
+ * «kevin: presupuesto agotado…», as the orchestrator writes it), with the dialog's reason id.
650
+ */
651
+ export function stuckAgentOf(reason) {
652
+ const text = String(reason ?? "");
653
+ const m = /^([a-z][a-z0-9_-]{0,31}): (contexto lleno|presupuesto agotado)/.exec(text);
654
+ if (!m) return null;
655
+ const budget = m[2] === "presupuesto agotado";
656
+ // P4: when the budget comes back (as the screen said it), and whether a resume is set.
657
+ const resets = budget ? (/se restablece a las ([^()]+?)\s*[()]/.exec(text)?.[1] ?? null) : null;
658
+ return { name: m[1], reason: budget ? "presupuesto" : "contexto", resets, scheduled: /Se reanudará a las/.test(text) };
659
+ }
660
+
661
+ /** P4: the API path that schedules «Reanudar al restablecerse» for one agent. */
662
+ export function resumePath(runId, name) {
663
+ return `/runs/${encodeURIComponent(String(runId))}/agents/${encodeURIComponent(String(name))}/resume`;
664
+ }
665
+
666
+ // ---- LOOP P3 (issue #2): the run's loop strip ----
667
+
668
+ /**
669
+ * What the Agents panel shows of a run's loop: null when the ticket has no loop; else a label
670
+ * («Loop · iteración 3 de 10») and the actions the person can take now.
671
+ */
672
+ export function loopStripOf(run, ticket) {
673
+ const loop = ticket?.loop;
674
+ if (!run || !loop?.enabled) return null;
675
+ // The limit chosen at «Iniciar loop» (run.loop_config) wins over the ticket's.
676
+ const cfg = run.loop_config;
677
+ const max = cfg && cfg.max_iterations !== undefined ? cfg.max_iterations : (loop.max_iterations ?? null);
678
+ const n = Number(run.loop_iteration ?? 0);
679
+ const of = max === null ? " (sin límite)" : ` de ${max}`;
680
+ const live = run.state === "running" || run.state === "waiting";
681
+ switch (run.loop_state ?? null) {
682
+ case null:
683
+ return { label: `Loop · sin iniciar${max === null ? " · sin límite" : ` · máx. ${max}`}`, tone: "dim", actions: live ? ["start"] : [], max };
684
+ case "running":
685
+ return { label: `Loop · iteración ${n}${of}`, tone: "working", actions: ["message", "pause", "stop"], max };
686
+ case "finishing":
687
+ return { label: `Loop · evaluando · iteración ${n}${of}`, tone: "working", actions: ["message", "stop"], max };
688
+ case "paused":
689
+ return { label: `Loop · en pausa · iteración ${n}${of}`, tone: "waiting", actions: ["message", "resume", "stop"], max };
690
+ case "finished":
691
+ return { label: `Loop · terminado tras ${n} ${n === 1 ? "vuelta" : "vueltas"}`, tone: "dim", actions: [] };
692
+ case "stopped":
693
+ return { label: `Loop · parado tras ${n} ${n === 1 ? "vuelta" : "vueltas"}`, tone: "blocked", actions: live ? ["start"] : [], max };
694
+ default:
695
+ return null;
696
+ }
697
+ }
698
+
699
+ /** The label of each loop action, and its API path. */
700
+ export const LOOP_ACTIONS = { start: "Iniciar loop", message: "Mensaje a gru", pause: "Pausar", resume: "Reanudar", stop: "Parar" };
701
+ export const loopActionPath = (runId, action) => `/runs/${encodeURIComponent(String(runId))}/loop/${action}`;
702
+
703
+ /** The longest instructions or message the orchestrator takes (LOOP_TEXT_MAX). */
704
+ export const LOOP_TEXT_MAX = 2000;
705
+
706
+ /**
707
+ * «Iniciar loop» dialog → the request body, or the error to show. `maxText` is the iterations
708
+ * field; `unlimited` the «sin límite» box.
709
+ */
710
+ export function loopStartBody({ plan, instructions, maxText, unlimited }) {
711
+ // plan "" (or null): the plan is the ticket's story.
712
+ const text = String(instructions ?? "").trim();
713
+ if (text.length > LOOP_TEXT_MAX) return { error: `Las instrucciones pasan de ${LOOP_TEXT_MAX} caracteres (${text.length})` };
714
+ let max = null;
715
+ if (!unlimited) {
716
+ max = Number(String(maxText ?? "").trim());
717
+ if (!Number.isInteger(max) || max < 1 || max > 1000) return { error: "Iteraciones: un entero de 1 a 1000, o «sin límite»" };
718
+ }
719
+ return { body: { plan: plan || "", instructions: text, max_iterations: max } };
720
+ }
721
+
722
+ /** «Mensaje a gru» → the request body, or the error to show. */
723
+ export function loopMessageBody(textIn) {
724
+ const text = String(textIn ?? "").trim();
725
+ if (!text) return { error: "Escribe la instrucción para gru" };
726
+ if (text.length > LOOP_TEXT_MAX) return { error: `El mensaje pasa de ${LOOP_TEXT_MAX} caracteres (${text.length})` };
727
+ return { body: { text } };
728
+ }
729
+
730
+ /**
731
+ * The hub analysis of a run as warnings: null when there is nothing to say (ready, no
732
+ * warnings). `blocking`: the run is stopped by the gaps; else they are notices (the person
733
+ * went on without them, or bond hub check warnings). The detail goes in a dialog.
734
+ */
735
+ export function analysisWarnings(run, ticket) {
736
+ const a = run?.hub_analysis || ticket?.analysis;
737
+ if (!a || typeof a !== "object") return null;
738
+ const gaps = (Array.isArray(a.gaps) ? a.gaps : []).map((g) => ({
739
+ id: String(g?.id ?? ""),
740
+ repo: g?.repo ? String(g.repo) : null,
741
+ message: String(g?.message || g?.id || "hueco detectado"),
742
+ fixable: Boolean(g?.fix || g?.fixable),
743
+ }));
744
+ const warnings = (Array.isArray(a.warnings) ? a.warnings : []).map((w) => String(w));
745
+ const summary = a.summary ?? a.agent_summary ?? null;
746
+ const ready = a.status === "ready";
747
+ const blocking = !ready && gaps.length > 0 && Boolean(run) && ["analyzing", "blocked"].includes(run.state);
748
+ const count = gaps.length + warnings.length;
749
+ if (count === 0) return null;
750
+ const parts = [];
751
+ if (gaps.length) parts.push(`${gaps.length} ${gaps.length === 1 ? "hueco" : "huecos"}${blocking ? "" : " (seguido sin ellos)"}`);
752
+ if (warnings.length) parts.push(`${warnings.length} ${warnings.length === 1 ? "aviso" : "avisos"}`);
753
+ return { blocking, count, label: `Análisis del hub · ${parts.join(" · ")}`, gaps, warnings, summary: summary ? String(summary) : null, checkedAt: a.checked_at ?? null };
754
+ }
755
+
756
+ /**
757
+ * While the run has no agents yet: what bond-app is doing and for how long («m:ss»), so a
758
+ * hub analysis (minutes) does not look like a hung run. Null once the run is past it.
759
+ * The start is the run's last change (updated_at): the analysis changes nothing while it runs.
760
+ */
761
+ export function preparingNotice(run, now = Date.now()) {
762
+ if (!run) return null;
763
+ const since = Date.parse(run.updated_at ?? run.started_at ?? run.created_at ?? "");
764
+ const secs = Number.isFinite(since) ? Math.max(0, Math.floor((now - since) / 1000)) : null;
765
+ const clock = secs === null ? "" : ` · ${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, "0")}`;
766
+ if (run.state === "queued") {
767
+ return { title: `Preparando el contenedor${clock}`, detail: "Se crea el contenedor del run y se clona el código. Después arrancan los agentes." };
768
+ }
769
+ if (run.state === "analyzing") {
770
+ return {
771
+ title: `Analizando el hub${clock} · hasta 5 min`,
772
+ detail: "Un agente de solo lectura revisa si al hub le falta algo para la historia. Al terminar arranca gru (o, si falta algo, el run te lo pide aquí).",
773
+ };
774
+ }
775
+ return null;
776
+ }
@@ -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;
@@ -24,10 +24,10 @@ import { api, hcGet, apiUrl } from "./api.js";
24
24
  import { CONFIG } from "./config.js";
25
25
  import {
26
26
  COLUMNS, POLL_MS, buildCards, groupByColumn, loadBoard, launchTicket, cancelRun, launchSummary,
27
- deliverRun, nudgeRun, finishRun, approveHubFixes, deleteTicket, getDeletePreview,
27
+ deliverRun, nudgeRun, finishRun, approveHubFixes, proceedHub, deleteTicket, getDeletePreview,
28
28
  columnCounts, filterOptions, filterCards, issueChip, validateNewTicket, createTicket, AGENTS, TICKET_MODES, TEAM_ENGINES,
29
29
  cleanRepoChips, listAssignedIssues, issueTicketId, searchRepos, listRepoIssues, searchJiraIssues, resetIssueProviderState, needsWizard, timeoutLabel,
30
- searchPullRequests, resolvePullRequest, parsePrSearchInput, formatSourceError,
30
+ searchPullRequests, resolvePullRequest, parsePrSearchInput, formatSourceError, INIT_ARGV, repoCheckQuery,
31
31
  } from "./model.js";
32
32
  import { stateColor, UI, settingsOverlay, createOverlay, markColor } from "./brand.js";
33
33
 
@@ -134,11 +134,22 @@ export default class BondBoard extends View {
134
134
  issue: InputState.new({ placeholder: "https://github.com/org/repo/issues/123 (o pulsa Buscar)" }),
135
135
  repo: InputState.new({ placeholder: "https://github.com/org/repo o https://dev.azure.com/org/proyecto/_git/repo" }),
136
136
  repos: TextareaState.new({ placeholder: "un repo por línea: https://github.com/org/repo [agente]" }),
137
- hub: InputState.new({ placeholder: "https://github.com/org/hub" }),
137
+ hub: InputState.new({ placeholder: "https://github.com/org/hub o https://dev.azure.com/org/proyecto/_git/hub" }),
138
138
  base: InputState.new({ placeholder: "rama base (opcional: main)" }),
139
139
  budget: InputState.new({ value: "2" }),
140
140
  timeout: InputState.new({ value: "0", placeholder: "0 = sin timeout" }),
141
+ loopMax: InputState.new({ value: "10", placeholder: "iteraciones" }),
141
142
  };
143
+ // LOOP P1: «Modo loop» (hub only): off; iterations from Ajustes, or «sin límite».
144
+ this.loop = false;
145
+ this.loopUnlimited = false;
146
+ cx.spawn(async (cx) => {
147
+ try {
148
+ const d = await api("/settings/loop");
149
+ if (Number.isInteger(d?.max_iterations)) this.fields.loopMax.set_value(String(d.max_iterations));
150
+ } catch {}
151
+ cx.notify();
152
+ });
142
153
  // Plan bond-app-nuevo-ticket (P2): la issue se busca, no se pega (D2/D4). Jira hasta P3.
143
154
  this.issueProvider = "github";
144
155
  this.pickedIssue = null;
@@ -148,6 +159,21 @@ export default class BondBoard extends View {
148
159
  // con devcontainers); la persona lo desmarca para un ticket concreto.
149
160
  this.docker = true;
150
161
  this.dockerTouched = false;
162
+ // Issue #4 (P2): «Login de Azure», ticked by default when bond-app has a usable Azure session
163
+ // (decision 2026-11-27, replaces D2); the person unticks it for a ticket.
164
+ this.azureLoginOn = false;
165
+ this.azureTouched = false;
166
+ this.azureSub = null; // null = the default subscription of Ajustes (D4)
167
+ this.azureSession = null;
168
+ cx.spawn(async (cx) => {
169
+ try {
170
+ this.azureSession = (await api("/settings/azure-login")) ?? { configured: false };
171
+ if (!this.azureTouched) this.azureLoginOn = Boolean(this.azureSession.configured) && !this.azureSession.expired;
172
+ } catch {
173
+ this.azureSession = { configured: false };
174
+ }
175
+ cx.notify();
176
+ });
151
177
  this.devcontainerRepo = null; // "owner/repo" con devcontainer detectado
152
178
  this.devcontainerChecked = null; // último "owner/repo@base" consultado
153
179
  // Dónde: el repo elegido es un hub (hub.toml) → el ticket va en modo hub, salvo que
@@ -330,8 +356,8 @@ export default class BondBoard extends View {
330
356
  if (p.machine) {
331
357
  try {
332
358
  const list = spaces() ?? [];
333
- const sp = list.find((s) => s.machine === p.machine);
334
- if (sp) run("space.close", { id: sp.id, confirmed: true });
359
+ // Every space of the run's machine (an early bond-init one and gru's).
360
+ for (const sp of list.filter((s) => s.machine === p.machine)) run("space.close", { id: sp.id, confirmed: true });
335
361
  } catch {}
336
362
  }
337
363
  await cancelRun(api, p.runId);
@@ -407,6 +433,26 @@ export default class BondBoard extends View {
407
433
  });
408
434
  }
409
435
 
436
+ proceed(cx) {
437
+ if (this.busy) return;
438
+ const p = props();
439
+ this.busy = true;
440
+ this.error = null;
441
+ cx.notify();
442
+ cx.spawn(async (cx) => {
443
+ try {
444
+ await proceedHub(api, p.runId);
445
+ notify({ title: "Equipo en marcha", body: `${p.title}: sigue sin los repos que pedía el análisis`, level: "success" });
446
+ setShared(REFRESH_KEY, Date.now());
447
+ closeOverlay(p.overlay);
448
+ } catch (e) {
449
+ this.error = String(e?.message ?? e);
450
+ this.busy = false;
451
+ cx.notify();
452
+ }
453
+ });
454
+ }
455
+
410
456
  nudge(cx) {
411
457
  if (this.busy) return;
412
458
  const p = props();
@@ -455,6 +501,8 @@ export default class BondBoard extends View {
455
501
  story: storyText.trim() ? storyText : this.pickedPr ? "" : undefined,
456
502
  bondify: this.bondify,
457
503
  docker: this.docker,
504
+ azure_login: this.azureLoginOn && Boolean(this.azureSession?.configured), azure_subscription: this.azureSub,
505
+ loop: this.loop && this.loopAvailable(), loop_max: v("loopMax"), loop_unlimited: this.loopUnlimited,
458
506
  })
459
507
  : validateNewTicket({
460
508
  title: v("title"), issue: v("issue"), mode: this.mode, repo: repoUrl, repos: reposText, hub: v("hub"),
@@ -466,6 +514,8 @@ export default class BondBoard extends View {
466
514
  story: storyText.trim() ? storyText : this.pickedIssue ? "" : undefined,
467
515
  bondify: this.bondify,
468
516
  docker: this.docker,
517
+ azure_login: this.azureLoginOn && Boolean(this.azureSession?.configured), azure_subscription: this.azureSub,
518
+ loop: this.loop && this.loopAvailable(), loop_max: v("loopMax"), loop_unlimited: this.loopUnlimited,
469
519
  });
470
520
  this.errors = check.errors;
471
521
  this.error = null;
@@ -587,6 +637,13 @@ export default class BondBoard extends View {
587
637
  });
588
638
  }
589
639
 
640
+ openProceed(card) {
641
+ openOverlay({
642
+ mod: "bond-board", kind: "dialog", modal: true, width: 520,
643
+ props: { view: "proceed", runId: card.run.id, title: card.title, gaps: card.analysis?.gaps ?? [], summary: card.analysis?.summary ?? null },
644
+ });
645
+ }
646
+
590
647
  openCreate() {
591
648
  openOverlay(createOverlay());
592
649
  }
@@ -621,8 +678,8 @@ export default class BondBoard extends View {
621
678
  if (p.machine) {
622
679
  try {
623
680
  const list = spaces() ?? [];
624
- const sp = list.find((s) => s.machine === p.machine);
625
- if (sp) run("space.close", { id: sp.id, confirmed: true });
681
+ // Every space of the run's machine (an early bond-init one and gru's).
682
+ for (const sp of list.filter((s) => s.machine === p.machine)) run("space.close", { id: sp.id, confirmed: true });
626
683
  } catch {}
627
684
  }
628
685
  await deleteTicket(api, p.ticketId, force);
@@ -723,7 +780,7 @@ export default class BondBoard extends View {
723
780
  // never a terminal.show over whatever tab was open. space.new brings a shell in the
724
781
  // "bond-init" tab; bond-agents gives the orchestrator its own tab and closes that one.
725
782
  try {
726
- run("space.new", { machine: card.run.hc_machine, name: card.title || card.id, tab: "bond-init" });
783
+ run("space.new", { machine: card.run.hc_machine, name: card.title || card.id, tab: "bond-init", argv: INIT_ARGV });
727
784
  } catch {}
728
785
  } else if (card.terminal) {
729
786
  try {
@@ -985,6 +1042,7 @@ export default class BondBoard extends View {
985
1042
  primaryAction(card) {
986
1043
  if (card.canNudge) return ["nudge", "Desbloquear…", () => this.openNudge(card)];
987
1044
  if (card.canApprove) return ["approve", "Aprobar…", () => this.openApprove(card)];
1045
+ if (card.canProceed) return ["proceed", "Seguir…", () => this.openProceed(card)];
988
1046
  if (card.canDeliver) return ["deliver", "Entregar…", () => this.openDeliver(card)];
989
1047
  if (card.canLaunch) return ["launch", "Lanzar…", () => this.openLaunch(card)];
990
1048
  return null;
@@ -1378,20 +1436,99 @@ export default class BondBoard extends View {
1378
1436
  .child("El contenedor del run va privilegiado: un agente podría tomar este equipo (en Windows y Mac, la VM de Docker Desktop). La imagen necesita el grupo «Docker en el run».")));
1379
1437
  }
1380
1438
 
1439
+ /**
1440
+ * Issue #4 (P2): «Login de Azure»: the person's Azure session in the run. Ticked while there is a session;
1441
+ * with the risk said in the row; without a session (or expired) it cannot be ticked and says why.
1442
+ */
1443
+ azureLoginRow() {
1444
+ const t = theme();
1445
+ const az = this.azureSession;
1446
+ const usable = Boolean(az?.configured) && !az?.expired;
1447
+ const on = usable && this.azureLoginOn;
1448
+ const subs = az?.subscriptions ?? [];
1449
+ const chosen = this.azureSub ?? az?.subscription?.id ?? null;
1450
+ const why = !az ? "comprobando la sesión de Azure…"
1451
+ : !az.configured ? "sin sesión de Azure: inicia sesión en Ajustes → Azure"
1452
+ : az.expired ? "la sesión de Azure ha caducado: vuelve a iniciarla en Ajustes → Azure" : null;
1453
+ return v_flex().gap(2)
1454
+ .child(h_flex()
1455
+ .id("ticket-azure")
1456
+ .gap(7).items_center().px(2).py(3)
1457
+ .text_color(usable ? t.foreground : t.dim).font_family(UI.fontSans).text_size(UI.text.small)
1458
+ .when(usable, (el) => el.cursor_pointer().on_click((_e, cx) => { this.azureLoginOn = !this.azureLoginOn; this.azureTouched = true; cx.notify(); }))
1459
+ .child(div().w(13).h(13).rounded(3).border_1()
1460
+ .border_color(on ? t.accent : t.border)
1461
+ .bg(on ? t.accent : t.input)
1462
+ .child(div().text_size(10).text_center().text_color(t.chrome).child(on ? "✓" : "")))
1463
+ .child(`Login de Azure${usable && az.user ? ` (${az.user})` : ""}`))
1464
+ .when(Boolean(why), (el) => el.child(div().pl(22).text_size(UI.text.tiny).font_family(UI.fontSans).text_color(t.dim).child(why)))
1465
+ .when(on, (el) => el
1466
+ .child(div().pl(22).text_size(UI.text.tiny).font_family(UI.fontSans).text_color(t.dim)
1467
+ .child("Los agentes del run usan az con tu cuenta: tienen en Azure tus mismos permisos, producción incluida. La sesión va al run por stdin y se va con el contenedor."))
1468
+ .when(subs.length > 1, (el2) => el2.child(h_flex().pl(22).gap(6).flex_wrap().items_center()
1469
+ .child(div().text_size(UI.text.tiny).text_color(t.muted).child("Suscripción:"))
1470
+ .children(subs.map((sub) => this.choice(`azure-sub-${sub.id}`, sub.name, chosen === sub.id,
1471
+ () => { this.azureSub = sub.id === az.subscription?.id ? null : sub.id; })))))
1472
+ .when(subs.length === 1, (el2) => el2.child(div().pl(22).text_size(UI.text.tiny).text_color(t.muted).child(`Suscripción: ${subs[0].name}`))));
1473
+ }
1474
+
1475
+ /** LOOP P1: the loop is for hub tickets only (v1, decision D7). */
1476
+ loopAvailable() {
1477
+ return this.createKind === "pr" ? Boolean(this.pickedPr?.is_hub || this.pickedPrHub) : this.mode === "hub" || this.mode === "list";
1478
+ }
1479
+
1480
+ /** LOOP: shown, but off, on a ticket that is not a hub (v1, D7), saying why. */
1481
+ loopRowDisabled() {
1482
+ const t = theme();
1483
+ return v_flex().gap(2).opacity(0.6)
1484
+ .child(h_flex().id("ticket-loop-off").gap(7).items_center().px(2).py(3)
1485
+ .text_color(t.muted).font_family(UI.fontSans).text_size(UI.text.small)
1486
+ .child(div().w(13).h(13).rounded(3).border_1().border_color(t.border).bg(t.input))
1487
+ .child("Modo loop: gru supervisa al equipo y ejecuta el plan solo"))
1488
+ .child(div().pl(22).text_size(UI.text.tiny).font_family(UI.fontSans).text_color(t.dim)
1489
+ .child(this.createKind === "pr"
1490
+ ? "Solo en tickets de hub: elige la PR de un hub (o de un repo que esté en un hub)."
1491
+ : "Solo en tickets de hub: en «Dónde», elige «Hub existente» o un repo con hub.toml."));
1492
+ }
1493
+
1494
+ /** LOOP P1 (issue #2): «Modo loop» with its iterations, or «sin límite». */
1495
+ loopRow(error) {
1496
+ const t = theme();
1497
+ const box = (id, on, label, action) => h_flex().id(id).gap(7).items_center().px(2).py(3).cursor_pointer()
1498
+ .text_color(t.foreground).font_family(UI.fontSans).text_size(UI.text.small)
1499
+ .on_click((_e, cx) => { action(); cx.notify(); })
1500
+ .child(div().w(13).h(13).rounded(3).border_1().border_color(on ? t.accent : t.border).bg(on ? t.accent : t.input)
1501
+ .child(div().text_size(10).text_center().text_color(t.chrome).child(on ? "✓" : "")))
1502
+ .child(label);
1503
+ return v_flex().gap(2)
1504
+ .child(box("ticket-loop", this.loop, "Modo loop: gru supervisa al equipo y ejecuta el plan solo", () => { this.loop = !this.loop; }))
1505
+ .when(this.loop, (el) => el
1506
+ .child(h_flex().pl(22).gap(10).items_center()
1507
+ .child(div().text_size(UI.text.tiny).text_color(t.dim).font_family(UI.fontSans).child("Iteraciones"))
1508
+ .when(!this.loopUnlimited, (row) => row.child(div().w(70).child(Input.new(this.fields.loopMax).h(26).px(8).rounded(UI.radius).border_1()
1509
+ .border_color(error ? t.blocked : t.input).bg(t.background).text_size(12))))
1510
+ .child(box("ticket-loop-unlimited", this.loopUnlimited, "sin límite", () => { this.loopUnlimited = !this.loopUnlimited; })))
1511
+ .child(div().pl(22).text_size(UI.text.tiny).font_family(UI.fontSans).text_color(error ? t.blocked : t.dim)
1512
+ .child(error || (this.loopUnlimited
1513
+ ? "Sin límite de iteraciones: lo paran el plan terminado, el timeout del ticket o un atasco."
1514
+ : "Cada iteración es una vuelta de revisión de gru. El bucle arranca con «Iniciar loop» en el run, con el plan listo."))));
1515
+ }
1516
+
1381
1517
  /** P4: asks the orchestrator whether the repo carries a devcontainer; pre-ticks Docker. */
1382
1518
  checkDevcontainer(cx) {
1383
- const m = /github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(String(this.fields.repo.value() ?? "").trim());
1384
- if (!m || this.mode === "list") return;
1519
+ if (this.mode === "list") return;
1520
+ // GitHub (owner/repo) or Azure Repos (the URL: the API resolves it): both can be a hub.
1385
1521
  const base = String(this.fields.base?.value?.() ?? "").trim();
1386
- const key = `${m[1]}/${m[2]}@${base}`;
1522
+ const check = repoCheckQuery(this.repoSel?.url ?? String(this.fields.repo.value() ?? "").trim(), base);
1523
+ if (!check) return;
1524
+ const key = check.key;
1387
1525
  if (key === this.devcontainerChecked) return;
1388
1526
  this.devcontainerChecked = key;
1389
1527
  cx.spawn(async (cx) => {
1390
1528
  try {
1391
- const q = `owner=${encodeURIComponent(m[1])}&repo=${encodeURIComponent(m[2])}${base ? `&ref=${encodeURIComponent(base)}` : ""}`;
1392
- const res = await api(`/repos/devcontainer?${q}`);
1529
+ const res = await api(`/repos/devcontainer?${check.query}`);
1393
1530
  if (key !== this.devcontainerChecked) return;
1394
- this.devcontainerRepo = res?.devcontainer ? `${m[1]}/${m[2]}` : null;
1531
+ this.devcontainerRepo = res?.devcontainer ? check.label : null;
1395
1532
  if (res?.devcontainer && !this.dockerTouched) this.docker = true;
1396
1533
  this.hubDetected = res?.hub ? (this.repoSel?.url ?? String(this.fields.repo.value() ?? "").trim()) : null;
1397
1534
  this.applyHubMode();
@@ -2010,11 +2147,14 @@ export default class BondBoard extends View {
2010
2147
  : Input.new(this.fields.model).h(30).px(9).rounded(UI.radius).border_1().border_color(t.input).bg(t.background).text_size(12.5), e.model));
2011
2148
  }
2012
2149
  const summary = [`bondificar ${this.bondify ? "sí" : "no"}`, `Docker ${this.docker ? "sí" : "no"}`, timeoutLabel(String(this.fields.timeout.value() ?? "").trim() || 0)];
2150
+ if (this.azureLoginOn && this.azureSession?.configured) summary.push("Azure sí");
2151
+ if (this.loop && this.loopAvailable()) summary.push(`loop ${this.loopUnlimited ? "sin límite" : `${String(this.fields.loopMax.value() ?? "").trim()} it.`}`);
2013
2152
  rows.push(h_flex().id("opts-toggle").gap(6).items_center().cursor_pointer().on_click((_e, cx) => { this.optionsOpen = !this.optionsOpen; cx.notify(); })
2014
2153
  .child(div().text_size(12).text_color(t.muted).child(this.optionsOpen ? "▾ Opciones" : "▸ Opciones"))
2015
2154
  .when(!this.optionsOpen, (el) => el.child(div().text_size(UI.text.small).text_color(t.dim).child(summary.join(" · ")))));
2016
2155
  if (this.optionsOpen) {
2017
- const box = v_flex().gap(6).pl(14).child(this.bondifyRow()).child(this.dockerRow())
2156
+ const box = v_flex().gap(6).pl(14).child(this.bondifyRow()).child(this.dockerRow()).child(this.azureLoginRow())
2157
+ .child(this.loopAvailable() ? this.loopRow(e.loop) : this.loopRowDisabled())
2018
2158
  .child(h_flex().gap(10)
2019
2159
  .child(div().w(110).child(this.field("Timeout min (0 = sin)", Input.new(this.fields.timeout).h(30).px(9).rounded(UI.radius).border_1().border_color(e.timeout ? t.blocked : t.input).bg(t.background).text_size(12.5), e.timeout)))
2020
2160
  .when(CONFIG.costs, (el) => el.child(div().w(110).child(this.field("Tope USD", Input.new(this.fields.budget).h(30).px(9).rounded(UI.radius).border_1().border_color(e.budget ? t.blocked : t.input).bg(t.background).text_size(12.5), e.budget)))))
@@ -2022,7 +2162,7 @@ export default class BondBoard extends View {
2022
2162
  .children(TEAM_ENGINES.map((en) => this.choice(`engine-${en.id}`, en.label, this.team_engine === en.id, () => { this.team_engine = en.id; }))), null)));
2023
2163
  rows.push(box);
2024
2164
  }
2025
- return this.createBlock(3, "Quién", null, rows, e.agent || (!this.optionsOpen ? e.timeout || e.budget : null));
2165
+ return this.createBlock(3, "Quién", null, rows, e.agent || (!this.optionsOpen ? e.timeout || e.budget || e.loop : null));
2026
2166
  }
2027
2167
 
2028
2168
  createSummary() {
@@ -2176,6 +2316,9 @@ export default class BondBoard extends View {
2176
2316
  .when(Boolean(card.canFinish), (el) =>
2177
2317
  el.child(item(`menu-finish-${card.id}`, "Terminado…", "✓", false, () => this.openFinish(card), true))
2178
2318
  )
2319
+ .when(Boolean(card.canProceed) && shown !== "proceed", (el) =>
2320
+ el.child(item(`menu-proceed-${card.id}`, "Seguir sin ellos…", "→", false, () => this.openProceed(card), true))
2321
+ )
2179
2322
  .when(Boolean(card.canApprove) && shown !== "approve", (el) =>
2180
2323
  el.child(item(`menu-approve-${card.id}`, "Aprobar arreglos…", "✓", false, () => this.openApprove(card), true))
2181
2324
  )
@@ -2318,6 +2461,17 @@ export default class BondBoard extends View {
2318
2461
  this.button("dlg-approve", this.busy ? "Aplicando…" : "Aprobar arreglos", "primary", (cx) => this.approve(cx)),
2319
2462
  ]);
2320
2463
  }
2464
+ if (this.view === "proceed") {
2465
+ const gaps = p.gaps ?? [];
2466
+ return this.renderDialog(`Seguir sin ellos «${p.title ?? ""}»`, [
2467
+ div().text_size(12.5).text_color(t.muted).child("El agente de hub cree que falta esto, pero es su opinión: si no hace falta (por ejemplo, un repo que solo es contexto), el equipo arranca con los repos que ya tiene el hub."),
2468
+ ...(p.summary ? [div().text_size(11.5).text_color(t.foreground).child(`Resumen del agente: ${p.summary}`)] : []),
2469
+ ...gaps.map((g) => div().text_size(11.5).text_color(t.dim).child(`◇ ${g.message}`)),
2470
+ ], [
2471
+ this.button("dlg-back", "Volver", "plain", () => closeOverlay(p.overlay)),
2472
+ this.button("dlg-proceed", this.busy ? "Arrancando…" : "Seguir sin ellos", "primary", (cx) => this.proceed(cx)),
2473
+ ]);
2474
+ }
2321
2475
  if (this.view === "nudge") {
2322
2476
  return this.renderDialog(`Desbloquear «${p.title ?? ""}»`, [
2323
2477
  div().text_size(12.5).text_color(t.muted).child(p.reason ? `Bloqueado: ${p.reason}` : "El run está bloqueado."),